Newbie C question

ramyh96

BANNED
Joined
Feb 8, 2012
Messages
924
Reaction score
137
Hello, I'm trying to make a function to scan 5 numbers from the user and to print the minimum, but once I run it, it's printing the last inputted number:


{
int i, num, min,k;
for (i=0;i<5;i++){
scanf("%d",&num);
for (k=0;k<1;k++){
min=num;
}
if (num<min){
min=num;
}

}

printf("%d",min);
}
 
what are you trying to do exactly?

Code:
#include <stdio.h>

int main(void) {
    int i, num, min,k;
    for (i=0;i<5;i++){

        //here you put the input in a int called num
        scanf("%d",&num);

        //here you assign num to min
        for (k=0;k<1;k++){
            min=num;
        }

        // here you check if num is smaller than min, but num is already min so it will always be false.
        if (num<min){
            min=num;
        }

    }

    printf("%d",min);
    return 0;
}
 
<code>
#include <stdio.h>

int main(void) {
int i, num, min,k;
for (i=0;i<5;i++){

scanf("%d",&num);

if (num<min){
min=num;
}

}

printf("%d",min);
return 0;
}
</code>
i think you messed it a liitle bit up now it should work as i understood
 
<code>
#include <stdio.h>

int main(void) {
int i, num, min,k;
for (i=0;i<5;i++){

scanf("%d",&num);

if (num<min){
min=num;
}

}

printf("%d",min);
return 0;
}
</code>
i think you messed it a liitle bit up now it should work as i understood
Shouldn’t you also initialise min before using it in the loop?
May be like min=0 or min=-65535 if you’re also inputting negative values.
 
Hello, I'm trying to make a function to scan 5 numbers from the user and to print the minimum, but once I run it, it's printing the last inputted number:


{
int i, num, min,k;
for (i=0;i<5;i++){
scanf("%d",&num);
for (k=0;k<1;k++){
min=num;
}
if (num<min){
min=num;
}

}

printf("%d",min);
}

In your code invariant num < min is always false and that's why your code have wrong behavior. Just remove this useless cycle with k and it will work. Also initialize min with INT_MAX as other's stated before.
 
I'm not sure what you tried to do there. But i suggest storing these numbers inside array and just traversing array and picking minimum number. There is no need to assign minimum to INT_MAX, you can just assume that first number in array is minimum.
 
Back
Top