The example programs will show you how to calculate the sum of numbers from 1 to 100 in C++.
Using for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <iostream> using namespace std; int main() { int sum=0; for(int i=1; i<=100; i++) { // adding 1 to 100 numbers sum=sum+i; } cout << "\n The sum of numbers from 1 to 100 is: "<<sum << endl; return 0; } |
Using while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> using namespace std; int main() { int i = 1, sum=0; while (i <= 100) { sum = sum+i; i++; } cout << "\n The sum of numbers from 1 to 100 is: "<<sum << endl; return 0; } |
Output:
1 2 3 | The sum of numbers from 1 to 100 is: 5050 |