Loop is not being completed

Asked

Viewed 43 times

0

I’m a beginner in programming and I’m still making several mistakes, you could help me find out why the loop is not completing the loop?

#include <stdio.h>

int main(){
    int N, X[N], controle = 0;
    int i, menor = 0, posicao = 0;

    setbuf(stdin, NULL);

    scanf("%d", &N);

    for(i = 0; i < N; i++){
        scanf("%d", &controle); 

        X[i] = controle;
    }

    for (i = 0; i < N; i++){
        if(X[i] <= menor){
            menor = [i];
            posicao = i;
        }
    }

    printf("Menor valor: %d\n", menor);
    printf("Posicao: %d\n", posicao);

    return 0;
}

1 answer

5

The way you declared the X array has no known N value at the time of the declaration. Declare the array after reading the N variable. If you start considering smaller as the first element of the array it is more comprehensive than considering smaller as zero. The way you did if all array elements are positive it won’t determine the smallest of them;

#include <stdio.h>

int main(){
    int N, controle = 0;
    int i, menor = 0, posicao = 0;

    setbuf(stdin, NULL);

    scanf("%d", &N);
    int X[N];
    for(i = 0; i < N; i++){
        scanf("%d", &X[i]); 
    }

    menor = X[0];
    posicao = 0;
    for (i = 1; i < N; i++){
        if(X[i] < menor){
            menor = X[i];
            posicao = i;
        }
    }

    printf("Menor valor: %d\n", menor);
    printf("Posicao: %d\n", posicao);

    return 0;

}
  • Ahhh, I understand perfectly, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.