Home > OS >  Where does the loop break?
Where does the loop break?

Time:01-03

I'm writing an algorithm to check if a given number is a power of two. I've found a solution online. It does this by continually dividing the number by 2. The solution works, but I don't understand why?

i = 32;

 // keep dividing i if it is even
    while (i % 2 == 0) {
      cout << i << " is the current val of i\n";
      cout << i%2 << " is current i mod 2\n*****\n";
      i = i / 2;

// check if n is a power of 2
    if (i == 1) {
      cout << n << " is a power of 2";

OUTPUT:

32 is the current val of i
0 is current i mod 2
*****
16 is the current val of i
0 is current i mod 2
*****
8 is the current val of i
0 is current i mod 2
*****
4 is the current val of i
0 is current i mod 2
*****
2 is the current val of i
0 is current i mod 2
*****
32 is a power of 2

My question: I don't understand why it's not an infinite loop. Where does the loop break? Doesn't i % 2 == 0 always evaluate to 0?

CodePudding user response:

Doesn't i % 2 == 0 always evaluate to 0?

No, that is not true. % is so-called modulo. Modulo is a math operation that finds the remainder when one integer is divided by another. For example:

11 % 4 = 3, because 11 divides by 4, with 3 remaining.

25 % 5 = 0, because 25 divides by 5, with 0 remaining.

So, there is only one possibility when the while cycle stops: When i becomes an odd number, the loop will terminate because i % 2 is no longer equal to 0.

If the loop terminates, the program will continue to execute the code following the loop. In this case, that would be the if statement that checks if i is equal to 1:

  • If i!=1, then the program will skip that if statement.
  • If i=1, it means the initial number must be a power of two, so it executes the inside of if statement.

CodePudding user response:

Let's assume the complete program is as follows.

#include <iostream>

using namespace std;

int main()
{
    int n = 32;
    int i = n;

    // keep dividing i if it is even
    while (i % 2 == 0) {
        cout << i << " is the current val of i\n";
        cout << i % 2 << " is current i mod 2\n*****\n";
        i = i / 2;
    }
    // check if n is a power of 2
    if (i == 1) {
        cout << n << " is a power of 2";
    }
}

In the last iteration, i becomes 2 so i == 2/2 == 1 and i % 2 == 1, which breaks while loops.

  • Related