How to store numbers in a vector to display it later in C?

Asked

Viewed 75 times

0

I have to make a code in which the user type 20 values, I must count the values greater than 10 and then display them later. I am able to count how many values are greater than 10, but the display part does not work.

#include <stdio.h>

#include <stdlib.h>

#include <locale.h>

#include <conio.h>

#include <string.h>



main () {

int vet[5],i,contador=0, num[5],j;


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

    printf("Digite o valor %i:",i+1);

    scanf("%i",&vet[i]);

    if (vet[i]>=10)
    {
        contador++;


    }

    }
 for (j=0;j<5;j++)

    {
        if (vet[i]>=10)
        {
            printf("Estes são os valores maiores que 10:%i",vet[i]);
        }

    }

    printf("Há este total de numeros maiores que 10:%i\n\n", contador);

}
  • Maybe here: for (j=0;j<5;j++)&#xA;&#xA; {&#xA; if (vet[i]>=10)&#xA; {&#xA; printf("Estes são os valores maiores que 10:%i",vet[i]);&#xA; }&#xA;&#xA; }&#xA; the index should be j nay?

1 answer

0


One problem is that you’re not reading 20 but only 5. Okay, you might have done so just to make it easier. But it is easier to use a definition that can be changed everywhere with ease.

It’s creating all variables before and making them global for every function. This is taught by many, but it’s something old, it doesn’t make sense to do this anymore, when making the variable have as little scope as possible can make less mistakes. This case in the second loop used a variable that is not from that loop, so it takes an area of invalid memory because it is the variable of the other loop. Keeping the variables more restricted where they are used can facilitate and prevent this tip ode error because it can use the same name and be different variables.

And still changed the comparison operator because the statement speaks in values greater than 10 and not or that are equal, one of the two was wrong, I changed the code.

And of course, I simplified and organized the code more. pay attention to all the details.

#include <stdio.h>
#define MAX 20

int main () {
    int vet[MAX];
    int contador = 0;
    for (int i = 0; i < MAX; i++) {
        printf("Digite o valor %i:",i+1);
        scanf("%i", &vet[i]);
        if (vet[i] > 10) contador++;
    }
    for (int i = 0; i < MAX; i++) if (vet[i] > 10) printf("Estes são os valores maiores que 10: %d\n", vet[i]);
    printf("Há este total de numeros maiores que 10: %d", contador);
}

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

  • Thank you very much, Maniero. Yes, I had set at 5 to take the tests. I will study this code and apply in the others so I can learn.

Browser other questions tagged

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