I want to sort the data inputed 3 different ways, as a choice from the user. Eit
ID: 3657935 • Letter: I
Question
I want to sort the data inputed 3 different ways, as a choice from the user. Either Alphabetical by name, by decending order for the ID or decending grades. How would I manipulate the program to sort the strings? maybe by usingstrcmp()?
#include <stdio.h>
#include <string.h>
struct student {
int student_id;
char name[30];
char grade[15];
};
int i;
struct student stu[20];
int students;
int sort;
int main(void)
{
printf("How many students in the Class?: ");
scanf("%d", &students);
for(i = 0; i < students; i++)
{
printf("Enter name: ");
scanf("%s",stu[i].name);
printf("Enter id: ");
scanf("%d", &stu[i].student_id);
printf("Enter grade: ");
scanf("%s",stu[i].grade);
printf(" ");
}
printf("how do you want to sort the records? [0 - name, 1 - id, 2 - grade]: ");
scanf("%d", &sort);
if (sort==0)
for(i = 0; i < students; i++)
printf(" Name: %s Sudent id: %d Grade: %s ",
stu[i].name,stu[i].student_id,stu[i].grade);
else if (sort==1)
for(i = 0; i < students; i++)
printf(" Student id: %d Name: %s Grade: %s ",
stu[i].student_id,stu[i].name, stu[i].grade);
else if (sort==2)
for(i = 0; i < students; i++)
printf(" Grade: %s Name: %s Student id: %d ",
stu[i].grade,stu[i].name,stu[i].student_id);
return 0;
}
Explanation / Answer
//use this fxn void sort(struct student st[],int cnt,int choice){//(0 - name, 1 - id, 2 - grade) int i,j; struct student temp; /* char last_name[30]; int student_id; // five digits char grade; */ for(i=0;ist[j+1].student_id) ||(choice==2 && st[j].grade>st[j+1].grade)) { temp=st[j]; st[j]=st[j+1]; st[j+1]=temp; } } } return; }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.