chevron_left
226 points
13 5 3

In this post I will present the way to find the sum of n numbers usng for loop. Basically, we will use an array to store values and then use a variable to add values.

First of all, we need get - the amount of numbers and declare an array with elemets to store numbers:

int n;
cin >> n;
int arr[n];

Next, we need to get numbers and use the above array to store them:

for (int i = 0; i < n; i++)
{
	int number;
	cin >> number;
	arr[i] = number;
}

And now we need a variable, sum, to accumulate values of all numbers. Note that we must initialize sum with 0 or else it would have garbage value and lead to incorrect result.

int sum = 0;

Finally, we iterate through all elemets of the array add value of sum with their values:

for(int i = 0; i < n; i++)
{
	sum = sum + arr[i];
}

cout << sum;

Result:

5
1 2 3 4 5
15

Here is the completed code:

#include <iostream>

using namespace std;

int main()
{
	int n;
	cin >> n;
	int arr[n];

	for (int i = 0; i < n; i++)
	{
		int number;
		cin >> number;
		arr[i] = number;
	}

	int sum = 0;

	for(int i = 0; i < n; i++)
	{
		sum = sum + arr[i];
	}

	cout << sum;
}

I have shown you how to calculate sum of numbers. I hope that this article will help you solve similar problems.
Happy coding !

 

More Posts

C++ program to find largest and smallest of n numbers Jeevani - Jun 11
C++ range based for loop hhh98hd - Aug 23
C++ program to count number of vowels in a string hhh98hd - Aug 2
c++ program to find maximum and minimum of n numbers Lalit Kumar - Apr 16, 2020
How to assign values to array in java using for loop MallikaShaik672 - Nov 4, 2020
How to print multidimensional array in PHP using for loop Tushar Shuvro - May 19, 2020
How to break out of For Loop java MallikaShaik672 - Oct 23, 2020
Length of char* C++ hhh98hd - Aug 3
C program to find largest of three numbers using functions john_dev - 4 days
Add to a vector C++ hhh98hd - Aug 10