Q : Write a program which asks the user to enter the name and age of persons in his group. The numbers of persons is not known to the user in the beginning of the program. The user keeps on entering the data till the user enters the age as zero. The program finally prints the average
age.
Solution :
#include<stdio.h>
#include<conio.h>
typedef struct stu
{
char name[20];
int age;
struct stu * next;
}EMP;
EMP *start=NULL;
void adddata(char*,int);
int average();
void main()
{
char name[20];
int age;
clrscr();
while(1)
{
printf("Enter
Age>> ");
scanf("%d",&age);
fflush(stdin);
if(age==0)
break;
printf("Enter
name>> ");
gets(name);
adddata(name,age);
}
printf("\n\tAverage age is
%d",average());
}
void adddata(char *nm,int ag)
{
EMP *nw,*pt;
nw=(EMP*) malloc(sizeof(EMP));
strcpy(nw->name,nm);
nw->age=ag;
if(start==NULL)
start=nw;
else
{
for(pt=start;pt->next!=NULL;pt=pt->next)
{
}
pt->next=nw;
}
}
int average()
{
EMP *pt;
int i,total;
for(i=0,pt=start,total=0;pt!=NULL;pt=pt->next,i++)
total+=pt->age;
return(total/i);
}
No comments:
Post a Comment