While loop

Hello,

I am trying to get a while loop to work only while a number is divided by 2 and stop once the result is 1 but can not quite figure out how to do it. When I run my code using c9.io my loop in infinite. Can you help me figure out how to make the loop finite please? Here is the code that I have so far. I am I allowed to put a while loop into an if statement? How can I print on the screen all of the numbers from the loop? Thank you.

#include <iostream>
using namespace std;
int main ()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
    cout<<"Please enter a positive number: ";                                   
    int even, odd, number;                                                       
    cin>>number; 
        if((number%2)<=1)                                                            
            {  
             even=number*3+1;
             cout<<even;
                    while (number%2<=1)
                    {
                         number=number/2;
                    }
                cout<<number;
            }                   
        else                                                       
            {  
                 cout<<"ERROR:Please enter a positive number.";
            }
            
}   
Last edited on
First, the use of code tags makes code easier to read and comment http://www.cplusplus.com/articles/jEywvCM9/


Second, the modulus operator returns the remainder of division. Therefore, the number % 2

equals 0 if the number is even (a multiple of 2)
OR
equals 1 if the number is odd

Those are the only possibilities. In your condition you therefore have either

0 <= 1 which is always true
OR
1 <= 1 which is always true
Thank you. I see what I did there. I was actually just checking if it was even or odd.
1
2
3
4
while((number/2)!=1)
        {
                 number=number/2;
        }

Would this give me what I want: to keep dividing the number until it is equal to one?

I am still not sure how to print out all of my results? Thank you.
Last edited on
That loop ... lets start with number=14

1. 14/2 == 7 and therefore the number is updated to 7
2. 7/2 == 3 and therefore the number is updated to 3
3. 3/2 == 1
After the loop the number is 3.

Was that what should happen?


You can print the number within the loop's body.
This is actually what happened after I ran a number and I am still trying to see how to fix it... can you have a while loop withing a while loop? Thanks
Yes, one iteration of a loop can execute so other "nested" loop. However,
I am still trying to see how to fix it

"Trying to fix" implies that the code does not do what it should.

What should it do? How does the current result differ from what you expect?
Topic archived. No new replies allowed.