Kev Kev - 1 month ago 5
C++ Question

While loop won't continue

int Day = 20;
while (Day >= 1)
{
cout << Day << " ";
userNum = Day / 2;
cin >> Day;
}


I don't get why the loop doesn't work. I want the output to be
20 10 5 2 1


Any help and if possible with explanation.

Answer

I don't understand what the purpose of cin is here, but if you want the output you requested in the question:

// Example program
#include <iostream>
#include <string>

using std::cout;
using std::endl;

int main()
{
 int Day = 20;
  while (Day >= 1)
  {
    cout << Day << " ";
    Day /= 2;
  }
}

You can see you stop whenever Date reaches 1 or is less than 1. And you divide it by 2 repeatedly. First, it becomes 20; then you divide it by 2 and it reaches 10; then you divide by two again and it reaches 5; then 5/2 is 2.5 but rounds to 2; and then 2/2 is 1, and finally exits the program.

Here it is compiled.

Comments