While repeating structure to recalculate in C

Asked

Viewed 1,492 times

7

I solved this exercise below and thought about putting a structure while repeat, for the person to calculate again. But when I put’s' to return and calculate again, the exercise sums up the values of the 10 numbers I calculated earlier and sums up with the next 10 numbers. Why does this happen?

/*Ex: Faça um programa que solicite ao usuário a entrada de 10 números e
imprima como resultado a soma de todos os pares */

int vetor[10], i;
float res=0;
char op;

do {

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

    printf("\nInforme um numero: ");
    scanf("%i", &vetor[i]);

    if (vetor[i] % 2 == 0) {

        res = res + vetor[i];

    }

}

printf("\nA soma dos pares e: %.2f", res);

printf("\nDeseja calcular novamente? ");
scanf("%s", &op);
fflush(stdin);

} while (op == 's' || op == 'S');

return(0);

3 answers

3

The problem is that the variable res does not have its value reset in the next loop iteration do..while. This can be corrected in two ways

1-Moving the variable declaration res into the loop do...while:

do {

    float res = 0;

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

Note that this is the correct way to remove the variable’s previous statement res, since it will not be used due to differences in scopes.

2- Restarting its value with each iteration of do...while through an allocation only:

do {

    res = 0;

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

Observing

Like res receives only integer values, it does not need to be declared as float, it is sufficient to declare it as int or how long, if you believe your values will cause integer overflow.

I hope I’ve helped.

  • 1

    Thank you guys, you’ve really helped me! ;)

3


The problem is that you are not restarting the variable value res when will you recalculate:

#include <iostream>
using namespace std;

int main() {
    int vetor[10], i;
    char op;
    do {
        float res = 0; //agora toda vez que for repetir o pedido vai zerar a variável
        for (i = 0; i <= 9; i++) {
            printf("\nInforme um numero: ");
            scanf("%i", &vetor[i]);
            if (vetor[i] % 2 == 0) {
                res += vetor[i];
            }
        }
        printf("\nA soma dos pares e: %.2f", res);
        printf("\nDeseja calcular novamente? ");
        scanf("%s", &op);
        fflush(stdin);
    } while (op == 's' || op == 'S');
}

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

Some small code problems beyond this but that does not prevent the functioning.

1

You can also use the while as follows:

#include <stdio.h>

#define MAX 10

int main(void)
{
    int vetInt[MAX], soma_par, i, op;           

    while(1)
    {
        soma_par = 0;
        printf("\nInforme 10 numeros inteiros.\n");

        /*Leitura dos numeros inteiros.*/
        for (i = 0; i < MAX; i++)
        {
            printf("\nInforme o %i° numero: ", i + 1);
            scanf("%i", &vetInt[i]);
        }

        /*Soma dos numeros pares.*/
        for (i = 0; i < MAX; i++)
            if (vetInt[i] % 2 == 0)
                soma_par += vetInt[i];

        printf("\nSoma de todos numeros pares é %i\n\n", soma_par);

        printf("\nDigite 0 para finalizar o programa ou 1 para continuar: ");
        scanf("%d", &op);

        if (op == 0)
            break;
        else
            system("clear");
    }

    return 0;
}

In this case to close the loop it is necessary for the user to enter 0, thus the loop will be shut down by break;.

  • Thanks Dener, I’ll try to fix it this way too. ;)

Browser other questions tagged

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