C++ Source Code: The sum of all numbers using a for loop
// Add all numbers up to the amount you enter.#include<iostream>
using namespace std;
int main()
{
int number = 0; // Variable for user to enter a number.
int sum = 0; // To hold the running sum during all loop iterations.
cout << "Enter a number: ";
cin >> number;
// Loop keeps adding until it reaches the number entered.
for (int index = 0; index <= number; index++)
{
sum += index; // Each iteration Adds to the variable sum.
}
// cout statement is put after the loop.
cout << "\nThe sum of all numbers from 0 to " << number
<< " equals: " << sum << "\n\n";
return 0;
}
/*===========================[output]===================================
Enter a number: 6
The sum of all numbers from 0 to 6 equals: 21
Press any key to continue . . .
========================================================================*/