How do I make "while" repeat 4 times only and break to the next C command?

Asked

Viewed 117 times

1

int numeros, calculo, soma;
    numeros = 0;
    calculo = 0;


    while (calculo > 0) {
        printf("Digite o número: ");
        scanf("%d", &numeros);
        calculo++;
    }
soma = calculo + soma;
printf("A soma entre os valores digitados é de: %d", soma);

I want to make the while repeat only 4 times asking the question "Enter a number" receiving a value and then adding these numbers and showing the value on the screen.

2 answers

2


There are some errors in this code. I think I should even use a for in this case, but it may have been required to use a while.

I organized and gave more meaningful names for the variables. The sum is not inside the loop so it is not adding up at each step that picks up a new number.

The sum has not been initialized with 0 so it can take a random value in memory and in some cases go very wrong, not at all, and that’s the worst part.

The condition is not checking if the count is going up to 4.

#include <stdio.h>

int main(void) {
    int contador = 0, soma = 0;
    while (contador < 4) {
        int numero;
        printf("Digite o número: ");
        scanf("%d", &numero);
        contador++;
        soma += numero;
    }
    printf("A soma entre os valores digitados é de: %d", soma);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • It worked obg. And yes, it is mandatory to use While, unfortunately kk.

  • See on [tour] the best way to say thank you.

0

when you put calculation++ means adding 1 to the current value of calculation, ie,

calculo=0;
calculo++; //calculo passa a valer 1

in the code you showed the incorrect use of ++ ta, it will not store sum of numbers so, in fact, to store the correct sum would be:

soma= soma + numeros;

or

soma+=numeros;

Browser other questions tagged

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