I have written a small program which takes 5 numbers from the user and stores them in an array of integers. The array is passed to a function. The function is used to find the smallest number in the array and print it out. Sincerly the output is not correct and i don't know why. The function always prints out the first element of the array which should be the smallest number but it's not.
#include <stdio.h>
void smallestint (int intarray [], int n)
{
int i;
int temp1 = 0;
int temp2 = 0;
for(i = 0; i < n; i ++)
{
if (intarray [i] < temp1)
{
intarray [i-1] = intarray [i];
temp2 = intarray[i];
intarray[i] = temp1;
temp1 = temp2;
}
else
temp1 = intarray[i];
}
printf("%d\n", intarray[0]);
}
int main ()
{
const int n = 5;
int temp = 0;
int i;
int intarray [n];
printf("Please type in your numbers!\n");
for(i = 0; i < n; i ++)
{
printf("");
scanf("%d", &temp);
intarray[i] = temp;
}
smallestint (intarray, n);
getchar();
getchar();
return 0;
}
I have updated my code. Now I'm initializing the temp values before the for loop. But it's still not working.
INT_MAXas the initial smallest value. And don't shuffle the array!intarray[0]as your initial value (but make sure that(n > 0)first).