### Can anyone help me start this program?

closed account (4wRjE3v7)

would this be right loop expression or can someone give me useful hints!
thanks
Last edited on
I don't see anything hard about implementing this. Your while loop looks right, you just have to do exactly what the question says. You need to get a number, check if that number plus your sum will be greater than 100; if it is, break out of the for-loop else add the number to sum
The loop will be less important than the conditional statements. The problem I see with relying on `while(sum>100)` (I think you meant `(sum<100)`, BTW) is that it will continue to sum numbers until it's too late!

Say sum makes it up to 98, then the user inputs 6. Sum will become 104, then the conditional will check it.

I would do something like:
 ``1234567891011121314`` ``````while(looping) { cout << "Enter number: "; cin >> nextnumber; if (sum+nextnumber>100) { dont_add; exit_loop; } else { do_add; } }``````

See you've got to catch the loop before it adds it, and the `while` condition can't if user input is generated within.
The simplest way is to use the following loop

 ``12345678910111213141516`` ``````int sum = 0; while ( true ) { std::cout << "Enter an integer number: "; int x; std::cin >> x; if ( 100 - sum < x ) break; sum += x; std::cout << "The intermediate sum is equal to " << sum << std::endl; } std::cout << "\n\nThe result sum is equal to " << sum << std::endl;``````
Last edited on
With a while loop:
 ``123456`` ``````int sum = 0 ; int num ; while( std::cout << "? " && std::cin >> num && num < (101-sum) ) sum += num ; std::cout << sum << '\n' ;``````

With a do-while loop:
 ``1234567891011`` ``````int sum = 0 ; int num ; do { std::cout << "? " ; std::cin >> num ; sum += num ; } while( sum < 101 ) ; std::cout << sum - num << '\n' ;``````
 ``12345678910111213141516171819202122232425`` ``````#include int main(void) { int sum=0, num; for(sum=0; sum <101;) { if(sum<101) { printf("Enter a number: "); scanf("%d", &num); sum = sum + num; } } printf("Sum of number you enter is %d: ",sum); return 0; }``````
Topic archived. No new replies allowed.