Sum of n numbers using linked list

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *next;
};
struct node *head = NULL;
struct node *ptr = NULL;
void insert(int num)
{
    struct node *temp = (struct node*)malloc(sizeof(struct node));
    if(head==NULL)
    {
        temp->data=num;
        head=temp;
        ptr=head;
        head->next=NULL;
    }
    else
    {
        temp->data=num;
        ptr->next=temp;
        ptr=temp;
        ptr->next=NULL;
    }
}
void add()
{
    int sum=0;
    ptr=head;
    while(ptr!=NULL)
    {
        sum+=ptr->data;
        ptr=ptr->next;
    }
    printf("%d",sum);
}
int main()
{
    int num;
    printf("Enter the total numbers :  ");
    scanf("%d",&num);
    for(int i=0;i<num;i++)
    {
        int value;
        scanf("%d",&value);
        insert(value);
    }
    add();
}


output

Enter the total numbers :  10                                                                                                                    
1                                                                                                                                                
2                                                                                                                                                
3                                                                                                                                                
4                                                                                                                                                
5                                                                                                                                                
6                                                                                                                                                
7                                                                                                                                                
8                                                                                                                                                
9                                                                                                                                                
10                                                                                                                                               
55   

Comments

Popular posts from this blog

c++ program to print string along the diagonals of the matrix.

Kollywood Game

C program to print the following Pattern