Write a program in c++ to print the sum of the first 100 natural numbers using for control structure
Write a program in c++ to print the sum of the first 100 natural numbers using for control structure
Answer: the program below prints 5050.
#include <iostream>
using namespace std;
int main() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum = sum + i;
}
cout << "Sum of first 100 natural numbers = " << sum << endl;
return 0;
}
How it works:
sum starts at 0.for loop runs with i = 1, 2, 3, …, 100. In each pass the current value of i is added to sum.sum holds 1 + 2 + … + 100, which is printed.Output: Sum of first 100 natural numbers = 5050. You can check this with the formula \(\dfrac{n(n+1)}{2} = \dfrac{100 \times 101}{2} = 5050\).
Log in or create a free account to answer this question.