I’m not managing to sort the notes with the use of struct

Asked

Viewed 79 times

0

I wanted to sort the grades of the students, only I’m not able to do because at the time of receiving the grades I’m using the index j, I think that’s the problem only I don’t know how to solve.

 #include<stdio.h>
 #include<stdlib.h>

double ordena(double *a, double *b);

struct notas
{
  double notas[3];
  char nome[100];
};


int main(void)
{
  int i, j;
  struct notas aluno[2];
  for(i = 0; i < 2; i++)
  {
    printf("Informe os nomes dos alunos :");
    scanf("%s", aluno[i].nome);
    system("cls");
    for(j = 0; j < 3; j++)
    {
        printf("Informe as notas do aluno %d:", j + 1);
        scanf("%lf", &aluno[i].notas[j]);
        system("cls");
    }
    system("cls");
   }
   for(i = 0; i < 2; i++)
   {
      for(j = i + 1; j < 3; j++)
       {
        ordena(&aluno[i].notas[j], &aluno[j].notas[j]);
       }
   }
   for(i = 0; i < 2; i++)
    {
      printf("Nome dos alunos %s:", aluno[i].nome);
       for(i = 0; i < 3; i++)
       {
        printf("%.2lf\n", aluno[i].notas[j]);
       }
  }
  system("pause");
  return 0;
}

double ordena(double *a, double *b)
{
  double o;
  if(*a > *b)
  {
    o = *a;
    *a = *b;
    *b = o;
  }
   return 0;
}
  • The function that has called ordena actually does not order and simply exchange values of variables, what is usually called swap. Start by reading about bubblesort for example, which is one of the simplest sorting algorithms.

1 answer

0

The function commands that you write does nothing more than exchange the elements. The right thing would be to sort within the function. Ex:

void ordena(double vet[]) {
    int i, j;
    double aux;

    for (i = 1; i < 3; i++) {
        aux = vet[i];

        for (j = i - 1; (j >= 0) && (aux < vet[j]); j--) {
            vet[j + 1] = vet[j];
        }

        vet[j+1] = aux;
    }
}

To order just call:

for(i = 0; i < 2; i++){
   ordena(alunos[i].notas);
}

And at the time of displaying the values you are using the variable 'i' in 2 loops for different in the same scope. The right one would be like this:

for(i = 0; i < 2; i++){
     printf("Nome dos alunos %s:", alunos[i].nome);
     for(j = 0; j < 3; j++) {
        printf("%.2lf\n", alunos[i].notas[j]);
     }
}

And just to finish avoid always declaring variables with the same name of the struct in which it belongs, otherwise your code will become difficult to read. What I suggest is that instead of 'grades', you declare the struct with the name 'Students' since it stores information about students.

Browser other questions tagged

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