Sum of n natural numbers in C++
Try it first
Sum of Non-Divisible Numbers
Give it a try before seeing the solution in this article.
Track completion, mastery, and revision.
Calculating the sum of numbers is a fundamental programming task. Depending on your requirements, this problem can be approached in two different ways:
- Sum of consecutive natural numbers: Adding all integers from $1$ up to $n$ (e.g., $1 + 2 + 3 + \dots + n$).
- Sum of $n$ arbitrary numbers: Adding $n$ different numbers provided by the user.
In this guide, we will explore three different methods to solve these problems in C++.
๐ก Pro-Tip: The Mathematical Shortcut For consecutive natural numbers from $1$ to $n$, you can calculate the sum instantly in $O(1)$ time complexity using the arithmetic progression formula: $$\text{Sum} = \frac{n \times (n + 1)}{2}$$ While loops are great for learning control flow, this mathematical formula is the most efficient approach in production.
Method 1: Sum of First $n$ Consecutive Natural Numbers (Using a while Loop)
This method calculates the sum of consecutive integers from $1$ to $n$ without storing them in an array. We decrement $n$ in each iteration of a while loop and add its value to a running total.
Algorithm
- Declare a variable
nto store the upper limit. - Prompt the user to enter a value for
n. - Declare a variable
sumand initialize it to0. - Use a
whileloop to iterate fromndown to1, adding the current value ofntosumin each iteration. - Print the final value of
sum.
Code Implementation
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
cout << "Enter number till which you would like to add: ";
cin >> n;
while (n > 0)
{
sum += n;
n--;
}
cout << "\nSum is: " << sum << endl;
return 0;
}
Output
Enter number till which you would like to add: 3
Sum is: 6
Complexity Analysis
- Time Complexity: $O(n)$ โ The loop runs exactly $n$ times.
- Space Complexity: $O(1)$ โ Only a few integer variables are used, consuming constant memory.
Method 2: Sum of $n$ Arbitrary Numbers (Without an Array)
If you need to sum $n$ numbers entered by the user dynamically, you do not need to store them all in memory. Instead, you can read each number one by one and immediately add it to the running sum.
Code Implementation
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0, number;
cout << "How many numbers do you want to add? ";
cin >> n;
cout << "\nEnter numbers: ";
while (n > 0)
{
cin >> number;
sum += number;
n--;
}
cout << "\nSum is: " << sum << endl;
return 0;
}
Output
How many numbers do you want to add? 7
Enter numbers:
1
2
3
4
5
89
34
Sum is: 138
Complexity Analysis
- Time Complexity: $O(n)$ โ The loop executes $n$ times to read and add each input.
- Space Complexity: $O(1)$ โ We reuse the
numbervariable, keeping memory usage minimal.
Method 3: Sum of $n$ Numbers (Using an Array and a for Loop)
Sometimes, you need to store the input values because they will be used for other operations later in the program (such as finding the average, sorting, or searching). In this case, we store the numbers in an array first, then iterate through the array to calculate the sum.
โ ๏ธ C++ Developer Note: Variable-Length Arrays (VLAs) In the code below,
int arr[n];is used to allocate an array of sizenat runtime. While some compilers (like GCC) support this as an extension, Variable-Length Arrays are not part of the standard C++ standard. For standard-compliant C++, it is highly recommended to usestd::vector<int> arr(n);instead.
Code Implementation
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
cout << "How many numbers do you want to add? ";
cin >> n;
int arr[n]; // Declares an array of size n
cout << "\nEnter numbers: ";
// Store inputs in the array
for (int i = 0; i < n; i++)
cin >> arr[i];
// Calculate sum from the array elements
for (int i = 0; i < n; i++)
sum += arr[i];
cout << "\nSum is: " << sum << endl;
return 0;
}
Output
How many numbers do you want to add? : 3
Enter numbers:
23
12
54
Sum is: 89
Complexity Analysis
- Time Complexity: $O(n)$ โ We use two sequential loops of size $n$, resulting in $O(2n)$ which simplifies to $O(n)$.
- Space Complexity: $O(n)$ โ Memory is allocated to store $n$ elements in the array.
Finished reading?