Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct a compound for loop in C++?

Is another for loop allowed in the counter section (third part) of a for loop? In my attempt to get elegant in writing code to produce a right triangle, I wrote this but it wouldn't compile:

#include <stdio.h>
int main()
{   
    int i, j, N = 5;
    for (i = 1;
         i <= N; 
         (for (j = 1; j <= i; j++, printf("%c", '0'));), i++)
       printf("\n");
    }
    return 0;
}
like image 423
lifebalance Avatar asked Sep 07 '14 17:09

lifebalance


1 Answers

No there are allowed only expressions or declarations.

EDIT: I am sorry. I thought you are speaking about the condition part of the loop. In the expression part of the loop there are allowed only expressions.

You could use a lambda expression that would contain this for loop. For example

for ( i = 1;
      i <= N;
      []( int i ) { for ( j = 1; j <= i; j++, printf("%c", '0' ) ); }( i ), i++)

Here is a demonstrative example

#include <iostream>

int main() 
{
    int N = 10;

    for ( int i = 1;
          i < N;
          []( int i ) 
          { 
            for ( int j = 1; j < i; j++, ( std::cout <<  '*' ) ); 
          }( i ), i++ )
    {
        std::cout << std::endl;
    }               

    return 0;
}

The output is

*
**
***
****
*****
******
*******
********

Or your could define the lambda expression outside the outer loop that to make the program more readable. For example

#include <iostream>

int main() 
{
    int N = 10;

    auto inner_loop = []( int i ) 
    { 
        for ( int j = 1; j < i; j++, ( std::cout <<  '*' ) ); 
    };


    for ( int i = 1; i < N; inner_loop( i ), i++ )
    {
        std::cout << std::endl;
    }               

    return 0;
}

Take into account that in general case the nested loops showed in other posts are unable to substitute the loop with the lambda-expression. For example the outer loop can contain continue statements that will skip the inner loop. So if you need that the inner loop will be executed in any case independing on the continue statements then this construction with the lambda expression will be helpful.:)

like image 96
Vlad from Moscow Avatar answered Oct 05 '22 19:10

Vlad from Moscow