How can I not display the null positions of a vector in the output?

0

How do I not display those gigantic numbers referring to the empty positions of my vector?

My code:

int main(int argc, char** argv) {

double notas[10];
double soma = 0, media = 0;
int i, P[10];
int j = 0, count = 0;

for(i=0;i<10;i++){
    printf("Digite %d: ", i);
    scanf("%lf", &notas[i]);
}

for(i=0;i<10;i++){
    if(notas[i] > 5){
        soma = soma + notas[i];
        count++;
    }
}
media = soma/ count;

for(i=0;i<10;i++){
    if(notas[i]>= media){
        P[j] = i;
        j++;
    }
}
    printf("%.2lf\n", media);


for(i=0;i<10;i++){
    printf("%d  ", P[i]);
}
return (EXIT_SUCCESS);
}

Output:

Curiosity: What are the names of these big numbers that appear?

    
asked by anonymous 20.08.2016 / 01:51

1 answer

3

The final print is printing the 10 array of notes that were above average, you can only print the number of notes that have been inserted there, ie it can only go to j (bad name for variable since it does not indicate what it is). Another solution would be to just mark the unused positions as invalid and then check if it is invalid (I could even mark the first invalid position and stop reading the others), but I do not like it. I no longer like to use a fixed array for this, but I understand exercise use. Maybe I have some logic problem too, but I can not talk about it. Something like this:

#include <stdio.h>

int main(void) {
    double notas[10];
    for (int i = 0; i < 10; i++) {
        printf("Digite %d: ", i);
        scanf("%lf", &notas[i]);
    }
    int j = 0, count = 0;
    double soma = 0;
    for (int i = 0; i < 10; i++) {
        if (notas[i] > 5) {
            soma = soma + notas[i];
            count++;
        }
    }
    double media = soma / count;
    int P[10];
    for (int i = 0; i < 10; i++) {
        if (notas[i] >= media) {
            P[j] = i;
            j++;
        }
    }
    printf("%.2lf\n", media);
    for (int i = 0; i < j; i++) {
        printf("%d  ", P[i]);
    }
    return 0;
}

See working on ideone .

The "big" numbers that appear are memory garbage, since you are accessing array positions that were not initialized in the program, it takes whatever crap it had in memory before its execution. In C, full memory management has to be done manually.

    
20.08.2016 / 02:03