Hi alll!
I've created this C program(see attachments please) to accept names, roll numbers and percentages of 6 students. I've created an array of 6 structs each comprising above mentioned variables. The aim is to display the records in the descending order of the students' percentages(using bubble sort) I've written two copies of the program: one which uses a function for sorting and another in which all code is written in main. Although there aren't any errors in both of them, I ain't getting the desired results for any copy.
P.S. I tried using pointers too with no different results.
Any help would be greatly appreciated!
Just in case those attachments get deleted within one hour the program typed for you:
WITHOUT FUNCTION:
Code:#include<stdio.h> #include<conio.h> #include<string.h> struct stu { char name[15]; int roll_no; float per; }; void main() { int i,j; struct stu s[6],temp; clrscr(); for(i=0;i<6;i++) { printf("Enter name,roll number and percentage of student:"); scanf("%s %d %f",s[i].name,&s[i].roll_no,&s[i].per); } for(i=0;i<6;i++) { for(j=0;j<6;j++) { if (s[i].per<s[j].per) {temp.per=s[i].per; //per swap// s[i].per=s[j].per; s[j].per=temp.per; strcpy(temp.name,s[i].name); strcpy(s[i].name,s[j].name); //name swap strcpy(s[j].name,temp.name); temp.roll_no=s[i].roll_no; s[i].roll_no=s[j].roll_no; //roll no swap s[j].roll_no=temp.roll_no; } } } for(i=0;i<6;i++) {printf("%s %d %f",s[i].name,s[i].roll_no,s[i].per); } getch(); }
WITH SORT FUNCTION:
Code:#include<stdio.h> #include<conio.h> #include<string.h> struct stu { char name[15]; int roll_no; float per; }; void sort(struct stu *s); void main() { int i; struct stu s[6]; clrscr(); for(i=1;i<=6;i++) { printf("Enter name,roll number and percentage of student %d:",i); scanf("%s %d %f",s[i].name,&s[i].roll_no,&s[i].per); } sort(&s[0]); } void sort(struct stu *s) { int i,j; struct stu temp; for(i=0;i<6;i++) { for(j=0;j<6;j++) { if((*(s+i)).per<(*(s+j)).per) { temp.per=(*(s+i)).per; (*(s+i)).per=(*(s+j)).per; (*(s+j)).per=temp.per; strcpy(temp.name,(*(s+i)).name); strcpy((*(s+i)).name,(*(s+j)).name); strcpy((*(s+j)).name,temp.name); temp.roll_no=(*(s+i)).roll_no; (*(s+i)).roll_no=(*(s+j)).roll_no; (*(s+j)).roll_no=temp.roll_no; } } } for(i=0;i<6;i++) { printf("%s %d %f",s[i].name,s[i].roll_no,s[i].per); } getch(); }