LAST UPDATED: OCTOBER 9, 2020
C++ Find Sum of n Numbers entered by the User
Hello Everyone!
In this tutorial, we will learn how to Sum of n numbers entered by the user, in the C++ programming language.
Code:
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to find the Sum of n numbers entered by the user ===== \n\n";
//variable declaration
int n,i,temp;
//As we are dealing with the sum, so initializing with 0.
int sum = 0;
//taking input from the command line (user)
cout << " Enter the number of integers you want to add : ";
cin >> n;
cout << "\n\n";
//taking n numbers as input from the 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;
}
cout << "\n\nSum of the " << n << " numbers entered by the user is : "<< sum << endl;
cout << "\n\n\n";
return 0;
}
Output:
Now let's see what we have done in the above program.
Program Explained:
Let's break down the parts of the code for better understanding.
//taking n numbers as input from the 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;
}
One thing to learn from this code is that, when we don't have to make use of the individual elements entered by the user, there is no need to create and array or any such data structre to store them as this would just lead to wasteage of space.
For example, in the above code, as we need to find the sum of all the numbers, we are taking each of the number entered by the user into the same variable and addiing it to the sum
variable and then again making use of that same variable again for the next number and so on.
Keep Learning : )