Need a little explanation pls - C language

So this is the full code, just for context:

#include <stdio.h>
#include <locale.h>
int main(){

        setlocale(LC_ALL, "portuguese");

/* Exercise: Create a programme in C that asks for 10 numbers, save them in a vector and print which one is the smallest. */

    int vetA[10] , i=0 , menor;          //menor=small

    printf("Escreva 10 números:\n");

    for(i=0 ; i<10 ; i++){

         printf("Número %d:\t", i+1);
         scanf("%d", &vetA[i]);
    }
    for(i=0 ; i<10 ; i++){
        if(menor>vetA[i]){
            menor=vetA[i];
        }
    }
    printf("\n %d é o menor número.", menor);


return 0;
        }

But I only need someone to explain to me what is going on and why this part is here:

   for(i=0 ; i<10 ; i++){
        if(menor>vetA[i]){
            menor=vetA[i];
        }

It looks like it is looping through all the ints in vetA and trying to find the lowest. If menor is greater than the current vetA int, then replace menor with that value, it is the new “smallest” int.

This is correct, but one caution. Since menor is uninitialized, there’s no guarantee the code will work as intended. Depending on the compiler and language version, menor might well start out as INT_MIN, which means the test in the loop will always fail. I think recent versions of the C language standard require implicit initialization to 0, but I wouldn’t count on it.

jrm

2 Likes

Rather than INT_MIN, I’d just start with the firs value and start your loop with 1. Besides, it would have to be INT_MAX, I think.

1 Like

Yep – INT_MAX. That’s what I get for debugging late at night. And concur on initializing to the first value in the vector. I wouldn’t start the loop at 1, however, since that’s not idiomatic for C.

jrm