C guide to structures programming

C structures programming involves declaring a structure in a C program after macro definitions before declaring any function. C structure is a collection of different datatypes within single datatype of structure type.Following example illustrate the use of structures in C programming.

C structures programming example:

This C program involves a structure named cricketer, which is used to store name and batting average of a cricketer.Users are asked to enter details of 10 players including their name and batting average. Program then sorts the list and display list in descending order according to batting average of cricketers.

Source code:

[c]

#include<stdio.h>
#include<conio.h>
#include<string.h>
struct cricketer
{
char name[20];
int avgr;
};

void bsort(struct cricketer a[]);
void display(struct cricketer a[]);

void main()
{
struct cricketer a[10];
int i;
int *ptr;
clrscr();
/*To enter the details of 11 players*/
for(i=0;i<10;i++)
{
printf("\n\nenter the details of %dth cricketer",i+1);
printf("\nenter runs: ");
scanf("%d",&a[i].avgr);
printf("enter name: ");
scanf("%s",&a[i].name);

}
bsort(a);
display(a);
getch();
}

/*To sort list of cricketers according to the run scrored*/
void bsort(struct cricketer a[])
{
struct cricketer temp;
int pos,i,j,max;
for(i=0;i<10;i++)
{
pos=i;
max=a[i].avgr;
for(j=i+1;j<10;j++)
{
if(max<a[j].avgr)
{
pos=j;
max=a[j].avgr;
}
}
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
}

/*To display the details of cricketers accoring to runs*/
void display(struct cricketer a[10])
{
int i;
printf("\nthe details are\n");
for(i=0;i<10;i++)
{
printf("%d-",a[i].avgr);
puts(a[i].name);
}
}

[/c]

Download Source Code: Cricketer structures programming

Download Executable File: cricketer structures programming

Output:


structures programming

structures programming

structures programming

 

Logic:

Batting average of a particular player is matched with batting average of other players. Following that player in the list. If its batting average is lesser than any other player in the list than their position are swapped using basic structures programming logic.Each time batting average of a player is compared to the players following him.

 If you face any problem regarding implementation of structures programming in C, feel free to comment below or discuss it on our 24*7 active facebook group.

Posted in C Programs, structures programming Tagged with: