Doubt about while loop on C?

Asked

Viewed 43 times

0

I need to know why 0 has to be typed twice in order for the program to stop traversing the loop.

And the same thing happens when I use the do-while.

#include <stdio.h>
#include <stdlib.h>
void main(){
    int num = 1, maior, menor, resultado, count = 0;
    while(num != 0){
        scanf("%d\n", &num);
        if(count == 0){
            maior = num;
            menor = num;
            count = 1;
        }else{
            if (num > maior && num != 0) {
                maior = num;
            }
            if (num < menor && num != 0) {
                menor = num;
            }
        }
    }
    printf("%d, %d\n", maior, menor);
    system("pause");
}
  • if put the whole program, because count makes no sense and bigger and smaller had no statement either

  • I didn’t put the whole program in because I didn’t think it made sense, but I can change.

  • minor can never be 0! already has a conceptual error no need of Count in this case

1 answer

1


It’s a silly mistake in scanf was placed a line break (\n) and don’t need giving this problem:

#include <stdio.h>
#include <stdlib.h>
void main(){
    int num = 1, maior = 0, menor = 99999999999;
    while(num != 0) {
        scanf("%d", &num);        
        if (num > maior) {
            maior = num;
        }
        if (num < menor && num != 0) {
            menor = num;
        }        
    }
    printf("%d, %d\n", maior, menor);
    system("pause");
}

Online Test

Observing: some changes were made to the code.

Browser other questions tagged

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