C++ program to print the sum of N natural numbers
In this program, you will find the sum of n natural numbers in the C++ program. There are two ways you can calculate 1) add all consecutive numbers from 1 to n. 2) use formula n(n+1)/2.
- Sum of first 10 natural number is 1 + 2 + 3+ 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.
- Use formula: n(n+1)/2 = 10 ( 10 + 1 ) / 2 = 55.
calculate the sum of n using for loop
#include <iostream>
using namespace std;
int main() {
int num, sum = 0;
cout << "Enter the number: ";
cin >> num;
for (int i = 1; i <= num; i++) {
sum += i;
}
cout << "Sum = " << sum;
return 0;
}
output
Enter the number: 10 Sum = 55
Explanation:
- In this program, you have taken a number from the user and stored it in a variable
num. - Iterate the for loop from 1 to num, inside
forloop, add the current iteration to a variablesum. - After the end of a loop print the
sumvalue.
Sum of n using while loop in C++ program
#include <iostream>
using namespace std;
int main() {
int num, sum = 0, i = 1;
cout << "Enter the number: ";
cin >> num;
while(i <= num){
sum += i;
i++;
}
cout << "Sum = " << sum;
return 0;
}
output
Enter the number: 8 Sum = 36
time complexity: O(n)
Calculate the sum of n using the formula
#include <iostream>
using namespace std;
int main() {
int num, sum = 0;
cout << "Enter the number: ";
cin >> num;
sum = num * (num + 1) / 2;
cout << "Sum = " << sum;
return 0;
}
output
Enter the number: 5 Sum = 15
By using the above formula time complexity will become O(1).