# Sum of the nodes of a Singly Linked List in C Program

CServer Side ProgrammingProgramming

A singly linked list is a data structure in which an element has two parts one is the value and other is the link to the next element. So to find the sum of all elements of the singly linked list, we have to navigate to each node of the linked list and add the element's value to a sum variable.

For example

Suppose we have a linked list: 2 -> 27 -> 32 -> 1 -> 5
sum = 2 + 27 + 32 + 1 + 5 = 67.

This can be done by using two methods :

Method 1 - Using a loop that loops over all the values of the linked list and finds the sum.

The loop runs till the end of the linked list i.e. when the pointer of an element points to null, this loop will run and find the sum of values of each element.

## Example

#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push(struct Node** nodeH, int nodeval) {
struct Node* new_node = new Node;
new_node->data = nodeval;
new_node->next = (*nodeH);
(*nodeH) = new_node;
}
int main() {
int sum = 0;
while (ptr != NULL) {
sum += ptr->data;
ptr = ptr->next;
}
cout << "Sum of nodes = "<< sum;
return 0;
}

## Output

Sum of nodes = 260

Method 2 - Using a recursive function that calls itself until the linked list has elements. The recursive function calls itself again and again. The call to the recursive function sends the next node values as a parameter along with the sum address location.

## Example

#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push(struct Node** head_ref, int new_data) {
struct Node* new_node = new Node;
new_node->data = new_data;
}
void nodesum(struct Node* head, int* sum) {
return;
}
int main() {
int sum= 0;
}
Sum of nodes = 260