3

I am new to C++ . Is there any way that I can use the "for...else" method? I came from a python background there is a method called for...else loop

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print( n, 'equals', x, '*', n/x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')

Is there any process in c++ like the "for...else" loop in python?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93

2 Answers2

4

No, there is nothing equivalent to for-else of Python in C++.

There are a few alternatives to transform the function. I'll use a simpler example:

for i in range(a, b):
    if condition(i):
        break
else:
    not_found()

The closest transformation can be achieved using goto, but you may find that some colleagues are likely to object (because goto is "evil" and scary):

for (int i = a; i < b; i++) {
    if (condition(i)) {
        goto found;
    }
}
not_found();
found:;

Other alternatives, which are also possible in Python are to introduce an additional boolean variable and if:

bool found = false;
for (int i = a; i < b; i++) {
    if (condition(i)) {
        found = true;
        break;
    }
}
if (!found) {
   not_found();
}

Or to encapsulate the whole thing within a function, which I think is the most widely accepted alternative both in Python and in C++.

void function()
{
    for (int i = a; i < b; i++) {
        if (condition(i)) {
            return;
        }
    }
    not_found();
}
eerorika
  • 232,697
  • 12
  • 197
  • 326
1

You can achieve something similar. Simply add a branch to test if the exit condition for the loop is satisfied. Here is an example:

#include <cstdio>

int main() {
  for (int n = 2; n < 10; ++n) {
    int x = 2;
    for (; x < n; ++x) {
      if (n % x == 0) {
        std::printf("%d equals %d * %d\n", n, x, n / x);
        break;
      }
    }
    if (x == n)
      std::printf("%d is a prime number\n", n);
  }
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93