Sum of all Elements in a Linked List

Sum of all Elements in a Linked List using C Language with Examples:

In this article, I am going to discuss How to find the Sum of all elements in a Linked List using C Language with Examples. Please read our previous article, where we discussed Counting Nodes in a Linked List using C Language with Examples.

How to find the Sum of all elements in a Linked list?

Here, we will write a function for finding the sum of all these elements in a linked list.

Sum of all elements in a Linked List using C Language with Examples

We want to add all these elements one by one. So, for adding we have to traverse all the nodes. We need a pointer for traversing the nodes. So let us write a function for adding all these values.

Iterative Version:
int Add(struct Node *p){
    int sum = 0;	
    while(p){
       sum += p->data;
       p = p->next;
    }
    return(sum);
}

Now let us write the same function for finding the sum of all the elements using recursion.

Recursive Version:
int Add(struct Node *p){
    if(p == 0)
       return 0;
    else
       return Add(p->next) + p->data;
}

The same recursive method we have already seen in the previous article where we were calculating the number of nodes in a linked list. Now let us write the full program in the C language.

Program to find the Sum of all the Elements in a Linked List using C Language:
#include <stdio.h>
#include <stdlib.h>
struct Node
{
    int data;
    struct Node *next;
}   *first = NULL;

void Create(int A[], int n)
{
    int i;
    struct Node *t, *last;
    first = (struct Node *) malloc (sizeof (struct Node));
    first->data = A[0];
    first->next = NULL;
    last = first;

    for (i = 1; i < n; i++)
    {
        t = (struct Node *) malloc (sizeof (struct Node));
        t->data = A[i];
        t->next = NULL;
        last->next = t;
        last = t;
    }
}

int Add(struct Node *p)
{
    int sum = 0;
    while (p)
    {
        sum += p->data;
        p = p->next;
    }
    return (sum);
}

int RAdd(struct Node *p)
{
    if (p == 0)
        return 0;
    else
        return RAdd(p->next) + p->data;
}

int main()
{
    int A[] = { 8, 3, 7, 12 };
    Create (A, 4);
    printf ("Sum %d\n", Add (first));
    return 0;
}
Output:

Program to find the sum of all the elements in a linked list using C Language

In the next article, I am going to discuss How to Find the Maximum Element in a Linked List using C Language with Examples. Here, in this article, I try to explain the Program for finding the Sum of all elements in a Linked list in C Language with Examples and I hope you enjoy this How to find the Sum of all elements in a Linked list in C Language with Examples article.

Leave a Reply

Your email address will not be published.