Find Average of Singly Linked list by R4R Team

Example-
Linked list is: 2->3->1->6
Average is 3

program-

#include< stdio.h>
#include< conio.h>
#include< alloc.h>
struct node{
struct node *link;
int data;
};
struct node *first=NULL;

void average(struct node *ptr)
{
int sum=0,count=0,avg;
while(ptr!=NULL)
{
sum=sum+ptr->data;
count++;
ptr=ptr->link;
}
avg=sum/count;
printf("Average is %d",avg);
}

void main()
{
struct node *cpt,*ptr;
int n,pos;
char ch;
clrscr();
first=(struct node*)malloc(sizeof(struct node));
printf("Enter first element in Linklist\n");
scanf("%d",&first->data);
ptr=first;
do
{
cpt=(struct node*)malloc(sizeof(struct node));
printf("Enter another data\n");
scanf("%d",&cpt->data);
ptr->link=cpt;
ptr=ptr->link;
printf("Continue(y/n) ?");
ch=getch();
}while(ch=='y');
ptr->link=NULL;
average(first);
getch();
}


output-

Enter first element in Linked list
2
Enter another data
4
Continue(y/n)?
Enter another data
1
Continue(y/n) ?
Enter another data
8
Continue(y/n) ?
Enter another data
0
Continue(y/n) ?
Average is 3




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!