A program that sums up n numbers where the odd numbers will be disregarded, where it works as it should

Asked

Viewed 94 times

-2

#include <stdio.h>

int main()
{

    int i, nmrs, n, soma = 0;

    printf("De quantos numeros quer fazer a soma? (impares serao desconsiderados)\n");
    scanf("%d", &nmrs);

    for (i = 1; i <= nmrs; i++)
    {
        if (n % 2 == 0)
        {
            soma = soma + n;
        }
        printf("digite um numero:  ");
        scanf("%d", &n);

    }

    printf("A soma dos numeros pares que aqui apareceram: %d", soma);

}
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

2

You are using the variable n which was declared and not initialized, so it may have junk in memory and that junk value that was already there was used for sum. It makes no sense to use the value before asking the first time, changing the order of the code solves this. Then it takes advantage and declares the variable only in use, it is more readable and obvious (I always say that declaring before is confusing, but the staff always teaches this way because in the 70s it was like this).

#include <stdio.h>

int main() {
    int nmrs, soma = 0;
    printf("De quantos numeros quer fazer a soma? (impares serao desconsiderados)\n");
    scanf("%d", &nmrs);
    for (int i = 1; i <= nmrs; i++) {
        int n;
        printf("digite um numero:  ");
        scanf("%d", &n);
        if (n % 2 == 0) soma += n;
    }
    printf("A soma dos numeros pares que aqui apareceram: %d", soma);
}

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

I haven’t changed your interpretation, but it may be that it is wrong. It may be that you should only count the pairs as well and your algorithm counts the odd ones. If you can’t count, you’d have to put one else decreasing i not to count the number that was dropped.

  • thank man B)

  • 1

    @Arthurribeirodantas see on the [tour] that you can accept the answer if it solved the question for you. And you can vote on the answer as well. Look there on the left side of the answer where to vote and accept.

Browser other questions tagged

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