Ask Question

4.2.3: Basic while loop expression. Write a while loop that prints userNum divided by 2 (integer division) until reaching 1. Follow each number by a space. Example output for userNum = 40: 20 10 5 2 1 Note: These activities may test code with different test values. This activity will perform four tests, with userNum = 40, then with userNum = 2, 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 "Program end never reached." The system doesn't print the test case that caused the reported message.

+3
Answers (1)
  1. 1 October, 03:18
    0
    import java. io.*;

    import java. util. Scanner;

    class divide {

    public static void main (String[] args) {

    Scanner num=new Scanner (System. in); //scanner object.

    int userNum=num. nextInt ();

    while (userNum>1) / /while loop.

    {

    userNum/=2; //dividing the userNum.

    System. out. print (userNum+" "); //printing the userNum.

    }

    }

    }

    Input:-

    40

    Output:-

    20 10 5 2 1

    Input:-

    2

    Output:-

    1

    Input:-

    0

    Output:-

    No Output

    Input:-

    -1

    Output:-

    No Output.

    Explanation:

    In the program While loop is used. In the while loop it divides the userNum by 2 in each iteration and prints the value of userNum. The inputs and corresponding outputs are written in the answer.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “4.2.3: Basic while loop expression. Write a while loop that prints userNum divided by 2 (integer division) until reaching 1. Follow each ...” 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