Reputation: 1
I am trying to write a nested for loop in order to produce the following output:
01234
2345
456
67
8
The code I have so far is:
#include <stdio.h>
#define SIZE 9
int main()
{
int i, j;
for(i=0; i < SIZE; i++)
{
for(j=0; j < SIZE; j++)
{
if(i <= j)
{
printf("%d", j);
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
/* This produces:
* 012345678
* 12345678
* 2345678
* 345678
* 45678
* 5678
* 678
* 78
* 8
/*
Any help in the right direction would be appreciated, thanks!
Upvotes: 0
Views: 120
Reputation: 40145
for(i=0; i < SIZE/2 + 1; i++){
for(j=0;j<i+SIZE/2 + 1;++j)
if(j<i*2){
printf(" ");
++j;
} else
printf("%d", j);
printf("\n");
}
Upvotes: 0
Reputation: 15121
Not a direct answer to the original question, but a solution to the task in the question:
#include <stdio.h>
#define LEVEL 5
int
main(void)
{
int i, j;
for (i = 0; i < LEVEL; i++) {
for (j = 0; j < i; j++)
printf(" ");
for (j = i*2; j < LEVEL+i; j++)
printf("%d", j);
printf("\n");
}
return 0;
}
Upvotes: 0
Reputation: 9413
Try this.
int start,stop, k;
start = 0;
stop = SIZE/2 + SIZE%2;
while(start<=stop)
{
for(k=0; k<start;++k)
printf(" ");
for(k=start;k<stop; ++k)
printf("%d ", k);
printf("\n");
start+=2;
stop++;
}
printf("\n");
Analyze that common pattern is that start
is increasing by 2 and stop
is incremented by 1.
Loop will over when start
overtakes stop
.
Upvotes: 1