C Chapters

C Program to create A record contains name of cricketer, his age, and number of test matches
that he has played and the average runs that he has scored in each test match.
Create an array of structure to hold records of 20 such cricketer and then
write a program to read these records and arrange them in ascending order by
average runs. Use the qsort( ) standard library function.

Arrays within Structure - Structures
#include<stdio.h>
#include<stdlib.h>
int compare(const void * a, const void * b);
struct cricketers
{
	int avrun;
	char name[30];
	int age;
	int notm;
}india[5] = {
	122, "Sachin Tendulkar", 30, 67,
	97, "Yuvaraj Singh", 35, 56,
	66, "Virat kohli", 32, 45,
	153, "Ms Dhoni", 36, 21,
	101, "Dravid", 32, 45,
};

int main()
{
	int i;
	qsort(india, 5, sizeof(struct cricketers), compare);
	for (i = 0; i < 5; i++)
	{
		printf("Name : %s", india[i].name);
		printf("\nAge : %d", india[i].age);
		printf("\nTotal Test Matches played : %d", india[i].notm);
		printf("\nAverage Run : %d\n\n\n", india[i].avrun);
	}
	return 0;
}

int compare(const void * a, const void * b)
{
	return (*(int*)a - *(int*)b);
}

Output :
Name : Virat kohli
Age : 32
Total Test Matches played : 45
Average Run : 66


Name : Yuvaraj Singh
Age : 35
Total Test Matches played : 56
Average Run : 97


Name : Dravid
Age : 32
Total Test Matches played : 45
Average Run : 101


Name : Sachin Tendulkar
Age : 30
Total Test Matches played : 67
Average Run : 122


Name : Ms Dhoni
Age : 36
Total Test Matches played : 21
Average Run : 153

Leave a comment
Recent Comments
No Comments