I've being asked to write a program in C that will take data of students from the user(name,marks obtained,roll numbers). Then to write a function that will sort data according to marks obtained(ascending order). Then to write a search function that will search using roll number, and another search function that will search using name.
The code I wrote is:
#include<stdio.h>
#include<string.h>
struct data{
char roll_No[5],name[15],marks[5];
};
struct data stInfo[50];
struct data temp[50];
void sortMarks(int n, struct data *stInfo){
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(stInfo[i].marks>stInfo[j].marks){
strcpy(temp[i].marks,stInfo[i].marks);
strcpy(stInfo[i].marks,stInfo[j].marks);
strcpy(stInfo[j].marks,temp[i].marks);
strcpy(temp[i].name,stInfo[i].name);
strcpy(stInfo[i].name,stInfo[j].name);
strcpy(stInfo[j].name,temp[i].name);
strcpy(temp[i].roll_No,stInfo[i].roll_No);
strcpy(stInfo[i].roll_No,stInfo[j].roll_No);
strcpy(stInfo[j].roll_No,temp[i].roll_No);}}}
for(i=0;i<n;i++){
printf("\nAfter sorting data of student %d:
%s,%s,%s\n",i+1,stInfo[i].name,stInfo[i].roll_No,stInfo[i].marks);}
return;}
void searchRoll_No(int n,char *roll_NoToFind, struct data *stInfo){
int i;
for(i=0;i<n;i++){
if(!strcmp(roll_NoToFind,stInfo[i].roll_No)){
printf("The student is: %s having marks: %s\n",stInfo[i].name,stInfo[i].marks);
break;}}
if(strcmp(roll_NoToFind,stInfo[i].roll_No)){
printf("Record not found!\n");}
return;}
void searchName(int n,char *nameToFind, struct data *stInfo){
int i;
for(i=0;i<n;i++){
if(!strcmp(nameToFind,stInfo[i].name)){
printf("The student has roll no: %s and marks: %s\n",stInfo[i].roll_No,stInfo[i].marks);
break;}}
if(strcmp(nameToFind,stInfo[i].name)){
printf("Record not found!\n");}
return;}
int main(){
int n,i;
printf("Enter the number of students: \n");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter roll no of student %d: \n",i+1);
scanf("%s",&stInfo[i].roll_No);
printf("Enter name of student %d: \n",i+1);
scanf("%s",&stInfo[i].name);
fflush(stdin);
printf("Enter marks of student %d: \n",i+1);
scanf("%s",&stInfo[i].marks);}
sortMarks(n,stInfo);
char roll_NoToFind[5];
printf("\nEnter the roll number you want to search: \n");
scanf("%s",&roll_NoToFind);
fflush(stdin);
searchRoll_No(n,roll_NoToFind,stInfo);
char nameToFind[15];
printf("\nEnter the name you want to search: \n");
scanf("%s",&nameToFind);
fflush(stdin);
searchName(n,nameToFind,stInfo);
return 0;}
The search functions are working fine but the sort function is giving wrong output. Whe data for two students is entered it is sorting correctly(sort marks in ascending order) but when I ener data for more than two students, the data is not being sort in ascending order. I want that if there are 5 students and there marks are entered randomly,then sorting must be done and whole data must be displayed according to marks. I think there is an issue with loop condition but I can't figure it out.