Sunday, February 24, 2013

Demo on Structures in C

The Structure is a special type of C data type. A structure contains a number of data types grouped together. Structure in C allows multiple data types to be grouped together.
The below mentioned program is to demonstrate structures in C Programming Language.
#include<stdio.h>
#include<conio.h>
void main(){
struct animal{
int age;
char name[10];
char gender;
}a[10];

int no,i;
clrscr();
printf("Enter the number of animals: ");
scanf("%d",&no);
for(i=0;i<no;i++){
printf("\nEnter the age of animal %d: ", i+1);
scanf("%d",&a[i].age);
printf("\nEnter the name of animal %d: ",i+1);
scanf("%s",&a[i].name);
printf("\nEnter the gender(M/F) of animal %d: ",i+1);
scanf("%s",&a[i].gender);
}

for(i=0;i<no;i++){
printf("\n%d",a[i].age);
printf("\t%s",a[i].name);
printf("\t%c",a[i].gender);
}
getch();
}

Output:

Enter the number of animals: 2

Enter the age of animal 1: 06

Enter the name of animal 1: Sam

Enter the gender(M/F) of animal 1: M

Enter the age of animal 2: 05

Enter the name of animal 2: Maxie

Enter the gender(M/F) of animal 2: F

6 Sam M
5 Maxie F

No comments:

Post a Comment