Q:

The while loop is particularly good at executing while some condition holds; for example

0

 The while loop is particularly good at executing while some condition holds; for example, when we need to read values until end-of-file. The for loop is generally thought of as a step loop: An index steps through a range of values in a collection. Write an idiomatic use of each loop and then rewrite each using the other loop construct. If you could use only one loop, which would you choose? Why?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <iostream>
#include <vector>

int main() {
  int i;
  while (std::cin >> i) { /* ... */ }
  for (int j; std::cin >> j;) { /* ... */ }

  std::vector<int> iv(10, 1);
  for (auto it = iv.begin(); it != iv.end(); ++it) { /* ... */ }
  auto it2 = iv.begin();
  while (it2 != iv.end()) {
    ++it2;
    /* ... */
  }

  // I would choose `for`-loop, because it can do what a `while`-loop can, but
  // not vise versa.

  return 0;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now