Data storage problem in the vector

Asked

Viewed 37 times

0

I’m learning to program and I’m having a hard time finding the error of this program.

The note array is storing the 6 notes (2 of each student), but only puts the last two in the array. The problem must be in the loop/for, but I can’t identify.

/* Criar um programa capaz de ler duas notas de cada
um dos 3 alunos de uma turma, calculando a média
geral da primeira e da segunda prova. OBS: use função.
*/

#include <stdio.h>
#include <string.h>
#define qtdAlunos 3
#define qtdNotas 2

float media(float notas[20]){
    float soma, media;
    for(int i=0; i<qtdAlunos; i++){
        for(int n=0; n<qtdNotas; n++){
            soma+=notas[n];
        }
    }
    media=soma/(qtdNotas*qtdAlunos);
    
    return media;
}

int main(){
    float notas[20];
    
    for(int i=0; i<qtdAlunos; i++){
        for(int n=0; n<qtdNotas; n++){
            printf("Digite a nota %d do aluno %d: ", n+1, i+1);
            scanf("%f", &notas[n]);
            
        }
        printf("\n");
    }
   
    printf("A media das notas é: %f", media(notas));
}

1 answer

0


The point is that you are only using a vector (unidimentsional) to store the notes. So what happens is that you are trying to store 6 notes in the same two positions of the vector "notes[]", then the program ends up overwriting and getting only the last.

You’re going to have to use an array, which is a two-dimensional vector, basically, and when you put that matrix inside the for, implement that you’re going to access each student’s row, and each student’s column (or vice versa). Thus:

(considering up to 3 students, and up to 20 grades per student)

int main() {

float notas[3][20];

for(int i=0; i<qtdAlunos; i++){
    for(int n=0; n<qtdNotas; n++){
        printf("Digite a nota %d do aluno %d: ", n+1, i+1);
        scanf("%f", &notas[i][n]);

}

If you haven’t seen this content, I recommend studying it. Video lessons on youtube about c language matrix should help you. I hope I’ve helped!

Browser other questions tagged

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