I am supposed to write a program that prints the minimum value from vector.This is what i tried. It only prints 0. I tried to change the sign both ways but it doesnt work.
#include <stdio.h>
int read(int v[], int size)
{
int i = 0;
do
{
scanf("%i", &v[i]);
i++;
} while (v[i-1] != 0 && i < size);
int n = i;
return n;
}
int minim(int v[], int n)
{
int m;
m = v[0];
int i;
for (i = 1; i <= n-1; i++)
{
if (v[i] < m)
{
m = v[i];
}
}
return m;
}
int main()
{
int arr[100];
int n = read(arr, 100);
int min = minim(arr, n);
printf("\nMinimum vrom vector is %i\n", min);
return 0;
}
Since your
scanf
loop (I'd recommend staying away from function names likeread
, which are part of the C standard, even if you didn't includeunistd.h
) ends when 0 is entered, you need to include a check at the end to decrement the size of the array if 0 is the last entry. Basically, replace everything after your do-while loop with this:This will return
i
if all 100 elements are non-zero, otherwise it will decrement to remove the 0 from your array before returning. No need to declareint n=i
just to instantlyreturn n
.Edit: I saw your comment that it worked properly for finding the maximum. This is because you almost certainly entered a number into the array that's greater than 0, so adding 0 at the end would not affect the maximum number. Try finding the max again, but only enter negative numbers. The result will be 0.