How to make the while loop only go once around?

Nov 13, 2013 at 4:49pm
The program works but it keeps going and going. I don't know how to stop it. Can anyone advise me on how to do this?

// Program to split integer into its seperate digits

#include <iostream>
using namespace std;

int main()

{
while ( 1234 > 0)
{
int digit1 = 1234%10;
int digit2 = 1234/ 10%10;
int digit3 = 1234/ 100%10;
int digit4 = 1234/ 1000%10;

cout<< digit1 <<endl;
cout<< digit2 <<endl;
cout<< digit3 <<endl;
cout<< digit4 <<endl;

}

return (0);
}




Nov 13, 2013 at 4:52pm
While loop syntax:

1
2
3
4
while( condition )
{
    body
}


As long as the 'condition' is true, the 'body' will continue to execute (ie: it keeps looping). Once the condition is false, the loop will exit.

Your while loop:

while ( 1234 > 0)

Your condition is always going to be true (1234 is always greater than 0), so the loop will never stop, it will just keep looping forever.


If you do not want this code to loop, then why did you put a while loop there? If you only want it to run once, get rid of the loop.
Nov 13, 2013 at 5:01pm
check this out:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
  int num = 1234;

  while(num > 0)
  {
    int digit = num % 10;
    cout << digit << endl;

    num = num / 10;
  }

  return 0;
}
4
3
2
1

Nov 13, 2013 at 5:13pm
you could add a break statement as an if statement condition if you need to.
Nov 13, 2013 at 6:16pm
Thanks for your help. Had to do it with a while for the question.
Topic archived. No new replies allowed.