C++: While Loops

Bjarne-stroustrup
 


Start an integer value at 1024. Loop while it is greater than 0. Print the value (with a newline) and divide it by two each time through the loop.

int i = 1024;
while(i > 0) {
  std::cout << i << std::endl;
  i /= 2;
}

Alternatively, it can be done with for:

for (int i = 1024; i>0; i /= 2)
  std::cout << i << std::endl;

Indeed, in C++,

for (init; cond; update)
  statement;

is equivalent to

{
  init;
  while (cond)
  {
    statement;
    update;
  }
}

SOURCE

Content is available under GNU Free Documentation License 1.2.