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.
#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;
}
Enter the number: 10 Sum = 55
Explanation:
num
.for
loop, add the current iteration to a variable sum
.sum
value.
#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;
}
Enter the number: 8 Sum = 36
time complexity: O(n)
#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;
}
Enter the number: 5 Sum = 15
By using the above formula time complexity will become O(1).