fbpx

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.

Our team found a curious site for our readers that are fans of online gaming, a rather exciting site that provides the latest gaming technology. Casinodots.com is the site, they compile the best reviews of MGA casino utan svensk licens sites. This site might pique your curiosity and you can win extra money!