Incorrect exit in practice

Asked

Viewed 30 times

1

The data output from this exercise is not correct. I don’t know what I did wrong, if you can help me thank you very much

Create a program that reads 10 integers and stores them in a vector. After filling the vector, print only the even numbers of the vector:

#include <stdio.h>

int main ()
{
    int veto [10];
    int par [10];
    int j = 0;
    int n;
    printf("Digite 10 numeros para identificar se sao pares ou nao\n");

    for (int i = 0; i < 10; i++)
    {
        scanf("%i", &veto[i]);
        if (veto[i] % 2 == 0)
        {
            par[j] = veto[i];
            j++;
            n = j;
        }
    }

    for (; n > 0; n--)
    {
        printf("Os numeros pares sao %i", par[n]);
    }
    return 0;
}
  • 1

    Put an example of input and output. And the last loop should be n>=0 instead of n>0

  • Invert the commands j++; n = j; for n = j; j++;, thus n indicate the last element, and for (; n > 0; n--) utilize n >= 0, because index 0 is the index of the first element of the vector.

1 answer

2

Your problem is in the last loop repeat, try to do this way:

for (int i = n-1; i >= 0; i--){
    printf("Os numeros pares sao %i\n", par[i]);
}

I put i = n-1 it gives 9 (the vector has 10 positions but starts at 0) and goes to 0 which is the first position.

Browser other questions tagged

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