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;
}
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.:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With