Ask Question

Write a while loop that prints userNum divided by 4 (integer division) until reaching 2. Follow each number by a space. Example output for userNum = 160:

40 10 2

Note: These activities may test code with different test values. This activity will perform four tests, with userNum = 160, then with userNum = 8, then with userNum = 0, then with userNum = - 1. See "How to Use zyBooks".

Also note: If the submitted code has an infinite loop, the system will stop running the code after a few seconds, and report "Programend never reached." The system doesn't print the test case that caused the reported message.

#include

using namespace std;

int main () {

int userNum;

cin >> userNum;

/ * Your solution goes here * /

cout << endl;

return 0;

}

+3
Answers (1)
  1. 6 December, 02:25
    0
    Answer / Explanation:

    #include

    using namespace std;

    int main ()

    {

    int userNum = 0;

    userNum = 20;

    cout << userNum << " ";

    while (userNum > 1)

    {

    userNum = userNum/2;

    cout << userNum << " ";

    }

    cout << endl;

    return 0;

    }

    However, we should note that the above codes divides properly but when it gets to 0, it will always give output as 0 instead of terminating the program.

    Hence to make it terminate, we include:

    while (userNum > 1)

    {

    cout << userNum << " ";

    userNum = userNum/2;

    }

    The above code alternatively should be replaced with int userNum = 0;.

    Also, for the sake of industry best standard and the general principle, we can say:

    The general principle is:

    while ()

    {

    / / Use the data

    / / Change the data as the last operation in the loop.

    }

    A for loop provides natural placeholders for these.

    for (;; )

    {

    / / Use the data

    }

    If you were to switch to using a for loop, which I recommend, your code would be:

    for (userNum = 20; userNum > 0; userNum / = 2)

    {

    cout << userNum << " ";
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a while loop that prints userNum divided by 4 (integer division) until reaching 2. Follow each number by a space. Example output for ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers