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.
CodePudding user response:
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;
}
}
}
CodePudding user response:
Just us 2 for loops instead of 1:
for (y = 0; y < 10; y )
for (x = 0; x < y; x )
printf("this is x = %d",x);
If you wan't to change the maximum number, just change the value in the condition of the first loop (y < 10
).
CodePudding user response:
two loops, the outer one increments the maximum number to count up to for the inner loop.