For loop - summing numbers

Hello !!

Could anyone please provide guidance on where I have gone wrong for the following exercise.

Write a program that computes a running sum of inputs from the user, terminating when the user gives an input value of 0

Using a while loop - no problem. Its only when I try to code it with a for loop that the program doesn't terminate with a 0 input. It terminates with a -1 input!!

while loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

int main()
{
    float input=1;
    float sum = 0;

   
    while ( input != 0 )
    {
        cout << "Please enter a number :" <<  endl;
        cin >> input;
        sum += input;
        cout << "Running total is :" << sum << endl;
   }

}


for loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

int main()
{
    
    float sum = 0;

    for (float input=1; input != 0  ; input++)
  
    {
        cout << "Please enter a number :" <<  endl;
        cin >> input;
        sum += input;
        cout << "Running total is :" << sum << endl;
    }

}
Because when the user enters a zero when it is starting the next loop the 'input' variable is incremented from 0 to 1 and hence when you enter a -1 it will exit and not when you enter a 0.

You would be better to do a 'do ... while();' loop. A 'for(...)' loop does not lend itself to this problem.
There is no any sense in the expression input++ that is used in the control statement of the loop.

The loop can be written for example the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main()
{
	float sum = 0.0f;
	float input;


	for ( std::cout << "Please enter a number: "; 
	      std::cin >> input && input != 0;
	      std::cout << "Please enter a number: " )
	{
		sum += input;
		std::cout << "Running total is " << sum << std::endl;
	}
}


Enjoy!:)
Last edited on
Or even more interesting for statement


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main()
{
	float sum = 0.0f;


	for ( std::cout << "Please enter a number: "; 
	      float input = ( input = 0.0f, std::cin >> input, input );
	      std::cout << "Please enter a number: " )
	{
		sum += input;
		std::cout << "Running total is " << sum << std::endl;
	}
}


Investigate. It will be very useful for you.
Last edited on
Thank you for the replies guys. I see the error of my ways in logic. It also appears as long as a conditional expression is "true" the loop is infinite. nice ! :)


Topic archived. No new replies allowed.