C++ Program for Sum of N numbers using Linked-List

Linked-list is a linear data structure that grows or shrinks dynamically. There are many benefits of using a linked-list like dynamic memory allocation.

This program uses linked-list to compute a sum of N numbers and then print the results. It is a demonstration of the linked-list program.

To understand this program, you must know C++ pointer concepts and that’s why this program is intended for intermediate level learners of C++ programming. Also, you will find the problem definition, flowchart, program code and a verified output to practice and learn this program.

The program is written using Dev-C++ version 4.9.9.2 installed on a windows 7 64-bit system. You are free to use any other C++ compiler, however, you may need to change the program code according to compiler specifications.

Problem Definition

In this program, we use two important functions – create() and summation(). The function create() will create a linked-list and each node of this linked-list will store an integer value.

The function summation() will add all the values and store the result in a variable called total.

Flowchart – Sum using Linked-list

Flowchart - C++ Program to Compute Sum of N numbers using Linked-List
Flowchart – C++ Program to Compute Sum of N numbers using Linked-List

Program Code – Sum using Linked-list

/* Program to compute some of N number using a Link-List */

#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>

struct node{

    int data;
    node *next;
}*node1,*node2,*head,*p;

void create();
void summation();

int main()
{

// Call function Create() to build the list of numbers

    create();

// Call function summation() to node all number
//in each node and print the result


    summation();

system("PAUSE");
return 0;

}

//create() function definition

void create()
{

    int n;
    char ch;

    cout << "How many nodes?:";
    cin >> n;
    cout << endl;

for(int i=0;i<n;i++)
{

    node1 = new node;
    node1->next = head;
    head = node1;

    cout << "Enter data for node"<< i<<":";
    cin >> head->data;
    cout << endl;
 }
   }

//function summation definition

void summation()
{

    int total = 0;
    p = head;

for(;p != NULL;p = p->next)
{

    total = total + p->data;

}

for(int i=0;i<30;i++)
cout << "_";cout << "\n\n";

    cout << "The Result is:"<< total << endl;

for(int i=0;i<30;i++)
cout << "_";cout << "\n\n";

}

Output

Output - C++ Program for Sum of N numbers using Linked-List
Output – C++ Program for Sum of N numbers using Linked-List
Advertisements