rosemary - 1 year ago 82
C Question

# Sorting array of structure with members as arrays

Problem:- write a c program to accept names and marks of 10 students in 4 subjects and print the rank list in ascending order of average of marks in 4 subjects.Also print individual marks for each student.

``````1.Start
2.Get student name and marks in 4 subjects
3.Calculate average for each student
4.Sort average in acsending order
5.Swap student names in the same order as average
6.Swap student marks in the same order as average
7.Display rank list
8.Display individual marks for each student
9.Stop
``````

My Question:- I have written the following program only to stumble at the step 6 of the algorithm. Is there any approach to accomplish step 6?

``````#include<stdio.h>
#include<conio.h>
#include<string.h>
#define sub 4
#define sno 10
struct student
{
char sname[20];
int avg,marks[4];
};
void main()
{
int i,j,max;
char swapname[20];
struct student s[sno];
clrscr();
for(i=0;i<sno;i++)
{
printf("Enter the name of student %d:",i+1);
scanf("%s",s[i].sname);
printf("Enter marks in four subjects\t");
for(j=0;j<sub;j++)
{
scanf("%d",&s[i].marks[j]);
}
//initialize structure member
s[i].avg=0;
//compute average
for(j=0;j<sub;j++)
{
s[i].avg+=s[i].marks[j];
}
s[i].avg/=sub;
}//FOR LOOP ends
printf("\n\n");

//SORTING
for(i=0;i<sno;i++)
{
for(j=i+1;j<sno;j++)
{
if(s[i].avg>s[j].avg)
{
max=s[i].avg;
s[i].avg=s[j].avg;
s[j].avg=max;
strcpy(swapname,s[i].sname);//Swap student names
strcpy(s[i].sname,s[j].sname);
strcpy(s[j].sname,swapname);
//Swap student marks????
}
}
}
//Display result
printf("Student Name in the ascending order of Average obtained:\n");
for(i=0;i<sno;i++)
{
printf("%s:\t",s[i].sname);
printf("%d\n",s[i].avg);
}
getch();
}
``````

You can do steps 5 and 6 all in one go by swapping the entire `struct`.
``````if(s[i].avg > s[j].avg)