-1

It's really complicated to me as a beginner to do it so I tried this code :

    int x,sum=0;

while (x)
    cin >> x;
    sum+=x;
    cout << sum ;

I want to let the program when the user enters "0" the program should print the sum of these numbers entered by the user.

Mohamed Magdy
  • 345
  • 3
  • 15
  • 1
    Your indentation is confusing you. A `while` will only execute the next statement in the absence of curly braces. – François Andrieux Oct 20 '17 at 19:25
  • 6
    Indentation has no impact on the code execution. As your loop is written, **only** the `cin >> x;` would be executed inside the loop. Consider learning from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) rather than trying to code randomly. – Algirdas Preidžius Oct 20 '17 at 19:25
  • Should I use for instead of while? – Mohamed Magdy Oct 20 '17 at 19:25
  • 1
    @MohamedMagdy You should surround the code, you wanted to be exucted inside a loop, in braces (`{`/`}`). Otherwise, only the first statement would be executed. – Algirdas Preidžius Oct 20 '17 at 19:27
  • ***Should I use for instead of while?*** No that will not help fix the problem. – drescherjm Oct 20 '17 at 19:51
  • Possible duplicate of [Why is it considered a bad practice to omit curly braces?](https://stackoverflow.com/questions/359732/why-is-it-considered-a-bad-practice-to-omit-curly-braces) – mbx Oct 20 '17 at 21:15

1 Answers1

1

One way to do it is here:

#include <iostream>

int main() 
{
   int x;
   int sum = 0;

   std::cin >> x;

   while(x)
   {
      sum += x;
      std::cin >> x;
   }

   std::cout << "Sum: " << sum << std::endl;

   return 0;
}

You are missing {}s around the statements in your while loop, so only cin >> x gets executed.

Honza Dejdar
  • 947
  • 7
  • 19