Write a C program to maintain cricketer’s information in tabular form using structures

CServer Side ProgrammingProgramming

Problem

How to store the cricketer’s data in tabular form in sorted order based on average runs using structures in C Programming language.

Solution

Let’s try to enter the cricketer information such as name, age, no of matches and average runs he scored. It will be entered in the console at runtime using the structure concept.

And try to display the information in tabular form in sorted order based on average runs scored by each person so that it is easy to identify each person's details clearly.

The logic we used to sort the cricketers in ascending order based on average runs they scored is −

for(i=0;i<2;i++){
   for(j=i+1;j<2;j++){
      if(c[i].avrn > c[j].avrn){
         temp1=c[i];
         c[i]=c[j];
         c[j]=temp1;
      }
   }
}

Program

#include<stdio.h>
#include<conio.h>
#include<string.h>
struct cricketer{
   char name[50];
   int age;
   int match;
   float avrn;
   char temp;
};
struct cricketer c[20],temp1;
void main() {
   int i,j;
   for(i=0;i<2;i++){
      printf("Enter data of cricketer %d\n",i+1);
      //fflush(stdin);
      printf("Name: ");
      gets(c[i].name);
      printf("\nAge: ");
      scanf("%d",&c[i].age);
      printf("\nMatches: ");
      scanf("%d",&c[i].match);
      printf("\n\nAverage runs: ");
      scanf("%f",&c[i].avrn);
      scanf("%c",&c[i].temp);
   }
   /******************/
   /* sorting records */
   /*******************/
   for(i=0;i<2;i++) {
      for(j=i+1;j<2;j++) {
         if(c[i].avrn > c[j].avrn){
            temp1=c[i];
            c[i]=c[j];
            c[j]=temp1;
         }
      }
   }
   printf("Sorted records:\n");
   for(i=0;i<2;i++){
      printf("%d\t%s\t%d\t%d\t%f\n\n\n",i+1,c[i].name,c[i].age,c[i].match,c[i].avrn);
   }
   getch();
}

Output

Enter data of cricketer 1
Name: Dhoni
Age: 39
Matches: 150
Average runs: 200
Enter data of cricketer 2
Name: virat
Age: 36
Matches: 135
Average runs: 190
Sorted records:
1    virat    36    135    190.000000
2    Dhoni    39    150    200.000000
raja
Published on 05-Mar-2021 12:13:56
Advertisements