140k views
1 vote
What is wrong with the following loop that attempts to sum the numbers from 1 to n?

int total;
for (int i=1; i<=n; i++)
total = total + i;
cout << "The sum is " << total << endl;

User Achellies
by
8.2k points

1 Answer

3 votes

Final answer:

The issue with the loop is the uninitialized 'total' variable, which leads to incorrect output. Initialize the 'total' variable to 0 before the loop to fix the problem.

Step-by-step explanation:

The issue with the given loop is that the variable 'total' is not initialized before the loop starts. As a result, the value of 'total' is undefined, and when the loop tries to add 'i' to 'total', it is essentially adding an undefined value to 'i', resulting in incorrect output.

To fix this, initialize the 'total' variable to 0 before the loop:
int total = 0;

After making this change, the loop will correctly sum the numbers from 1 to 'n'.

User Rodolfo Neuber
by
7.9k points