C++ Program to Sum Integers

Beginner

Introduction

In this lab, you will learn how to write a C++ program that reads 'n' integers from the user and outputs their sum.

Writing the Code to Find Sum of n Numbers

In WebIDE, open a new terminal by selecting Terminal > New Terminal from the menu bar. In the terminal, type the command below to create a new file called main.cpp

touch ~/project/main.cpp

Now open the file main.cpp and paste the following code in it:

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to the program to find the Sum of n numbers entered by the user :-)\n\n\n";

    // Variable declaration
    int n, i, temp;

    // Initializing sum to zero
    int sum = 0;

    // Taking 'n' as input from the user
    cout << "Enter the number of integers you want to add : ";
    cin >> n;
    cout << "\n\n";

    // Taking n integers as input from user and adding them to find the final sum
    for (i = 0; i < n; i++)
    {
        cout << "Enter number " << i + 1 << " :  ";
        cin >> temp;

        // Add each number to the sum of all the previous numbers to find the final sum
        sum += temp;
    }

    // Output the sum
    cout << "\n\nSum of the " << n << " numbers entered by the user is : " << sum << endl;
    cout << "\n\n\n";

    return 0;
}

Compiling and Running the Code

Type the following command in the terminal to compile the code:

g++ ~/project/main.cpp -o main

Then type the following command to run the executable file:

./main

You will see the output similar to what's shown below:

Welcome to the program to find the Sum of n numbers entered by the user :-)

Enter the number of integers you want to add : 4


Enter number 1 : 2
Enter number 2 : 3
Enter number 3 : 5
Enter number 4 : 10


Sum of the 4 numbers entered by the user is : 20

Summary

In this lab, you learned how to write a C++ program that reads 'n' integers from the user and outputs their sum. You have successfully completed the lab. Congrats!

Other Tutorials you may like