The C program(main function)asks the user for the number of elements in an array(which this function works). The C function findSecondSmallest finds the second smallest element of an array(points toward the first index). The C function sortAscending arranges the array elements in ascending order (does not display the inputted elements, just garbage values) and the C function displayArray should display the arranged array in ascending order.
#include<stdio.h>
#include<limits.h>
int initializeArray(int num,int arr[]);
int findSecondSmallest(int num,int arr[]);
int *sortAscending(int num,int arr[]);
void displayArray(int num,int arr[]);
void main(){
int array[50],*arr;
int n = sizeof(array) / sizeof(array[0]);
initializeArray(n,array);
findSecondSmallest(n,array);
arr = sortAscending(n,array);
displayArray(n,arr);
}
int initializeArray(int num,int arr[]){
int i;
printf("Input the number of elements in an array: ");
scanf("%d", &num);
printf("\nEnter %d elements: ", num);
for(i = 0;i < num;i++){
scanf("%d", &arr[i]);
}
}
int findSecondSmallest(int num,int arr[]){
int i,secondSmall,small;
small = secondSmall = INT_MAX;
for(i = 1;i < num;i++){
if(arr[i] < small){
secondSmall = small;
small = arr[i];
}else if(arr[i] < secondSmall && arr[i] > small){
secondSmall = arr[i];
}
}
printf("The second smallest element is %d", secondSmall);
}
int *sortAscending(int num,int arr[]){
int i,j,temp;
for(i = 0;i < num;i++){
for(j = i + 1;j < num;j++){
if(arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
void displayArray(int num,int arr[]){
int i;
for(i = 0;i < num;i++){
printf("Element at Array[%d] = %d ", i, arr[i]);
}
}
In need of help
numelements, but you're sorting the entire array, which includes all the garbage values that weren't filled in.initialize_arrayreturnnum, then use that when you call the other functions.findSecondSmalleststarting fromi = 1instead ofi = 0?i = 1?0. Look at your loops ininitializeArrayanddisplayArray.