fbpx

C++: Execute Only Part of Loop

Bjarne-stroustrup
 


Quite often one needs loops which, in the last iteration, execute only part of the loop body. The goal of this task is to demonstrate the best way to do this.

Write a loop which writes the comma-separated list

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

using separate output statements for the number and the comma from within the body of the loop.

#include <iostream>
 
int main()
{
  for (int i = 1; ; i++)
  {
    std::cout << i;
    if (i == 10)
      break;
    std::cout << ", ";
  }
  std::cout << std::endl;
  return 0;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.