Questions about C-language loop/array

Asked

Viewed 40 times

0

Hello!

I did a basic program to calculate the averages of 4 students.

The problem is that the result of it, in the final screen, appears the phrase "Insert 4 Notes student 5 here: " without having placed student 5 as an option for data entry. I also tried to start the matrix with value 0, as I saw in a video class, but I could not, because it returns the error:

  1. variable-sized Object may not be initialized

  2. Warning: excess Elements in array initializer

My doubts are:

  1. How could I solve this problem?

  2. Why can’t I start matrix with 0?

Follows code:

#include <stdio.h>

int main(void)
{

    // programa para testar vetores/calcular média.

    const int bimonthly = 4; // número de bimestres.

    const int num_students = 4; // quantidade de estudantes.

    float notasAlunos[num_students][bimonthly]; // notas dos alunos.

    float mediaTotal[num_students]; // média dos alunos.

    float media = 0; // variável para calcular média.

    printf("\nInsert 4 notes student 1 here: "); //insira os dados.

    //lógica do programa.
    for (int aluno = 0; aluno < num_students; ++aluno)
    { // for para linha.
        for (int notas = 0; notas < bimonthly; ++notas)
        { // for para linha coluna.

            scanf("%f", &notasAlunos[aluno][notas]); // lerá as notas dos alunos 4 vezes.
            media += notasAlunos[aluno][notas];      // fará a soma das médias.
        }
        mediaTotal[aluno] = media / bimonthly;                  // fará a divisão para achar o total.
        media = 0;                                              // reseta a variável média para iniciar o próximo aluno.
        printf("Insert 4 notes student %i here: ", aluno + 2); // aluno começa com 0, quando ele chega a esta parte do programa, ele está com 1, mas seu valor definido é 0. aluno + 2 trará o número atual que a variável se encontra mais o número dois, automatizando os valores de entrada.
           
    }

    for (int aluno = 0; aluno < num_students; ++aluno)
    {
        printf("\nAverage student %i is %.2f", aluno + 1, mediaTotal[aluno]);
      

    }

    return 0;
}
  • You do: for (int aluno = 0; aluno < num_students; ++aluno) { ... printf("Insert 4 notes student %i here: ", aluno + 2); as num_students = 4 when student = 3 will print the phrase you missed. To initialize the arrays you can do the assignment within 2 loops.

  • I changed the code, I took the example of someone else and I got it. Thanks!

1 answer

0

Make sure that the logic is correct. You used logical operator for comparison and it is he who should be checked, because he is looping the most.

  • I changed the code, I took the example of someone else and I got it. Thanks!

Browser other questions tagged

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