so I'm confused about how to solve this problem in C. The answer to this question is more likely solve if I can understand the logic. But it seems I cant understand it. Sorry if the question title does not matches the explanation of the problem. So:
In C, loop with using for like this, for(x=0;x<10;x++)
, this will result to loop simultaneously without a break.
For example:
for(x=0;x<10;x++)
printf("this is x = %d",x);
result example:
this is x = 0
this is x = 1
.
.
this is x = 10
So how to loop, but will break in each new number and start over then break/pause until new numbers and so on. For example:
for(x=0;x<//variables;x++)
printf("this is x = %d",x);
result:
(start)
this is x = 0
this is x = 1
(over/break)
(start)
this is x = 0
this is x = 1
this is x = 2
(over/break)
(start)
this is x = 0
this is x = 1
this is x = 2
this is x = 3
(over/break)
.
.
.
(start)
this is x = 0
this is x = 1
this is x = 2
this is x = 3
.
.
.
this is x = 10
(over/break)
So how to do this? This maybe seems simple but I can't find the solution. I hope the explanation can make the problem clear. Thank you.
Just use nested for loops as for example
for ( int i = 0; i < 10; ++i )
{
for ( int x = 0; x <= i + 1; ++x )
{
printf( "this is x = %d\n", x );
}
}
Here is a demonstration program
#include <stdio.h>
int main( void )
{
for ( int i = 0; i < 10; ++i )
{
for ( int x = 0; x <= i + 1; ++x )
{
printf( "this is x = %d\n", x );
}
}
}
Its output is
this is x = 0
this is x = 1
this is x = 0
this is x = 1
this is x = 2
this is x = 0
this is x = 1
this is x = 2
this is x = 3
this is x = 0
this is x = 1
this is x = 2
this is x = 3
this is x = 4
and so on.
If you want to separate outputs with a blank line like
this is x = 0
this is x = 1
this is x = 0
this is x = 1
this is x = 2
this is x = 0
this is x = 1
this is x = 2
this is x = 3
this is x = 0
this is x = 1
this is x = 2
this is x = 3
this is x = 4
...
then write the loops like
for ( int i = 0; i < 10; ++i )
{
for ( int x = 0; x <= i + 1; ++x )
{
printf( "this is x = %d\n", x );
}
putchar( '\n' );
}
If you want to use only one for loop then the program can look for example the following way
#include <stdio.h>
int main( void )
{
for ( int x = 0, i = x + 1; i <= 10; )
{
printf( "this is x = %d\n", x );
if ( x == i )
{
putchar( '\n' );
++i;
x = 0;
}
else
{
++x;
}
}
}