How to solve this peculiar nested for loops exercise?
-
06-06-2021 - |
Question
I've been studying C programming for a while and I've stumbled on this exercise I can't seem to solve:
Write nests of loops that cause the following output to be displayed:
0 01 012 0123 01234 012345 01234 0123 012 01 0
Until now I've managed to get to the sixth row, but I can't finish the exercise. This is the code I've written to obtain half of the solution to this problem:
#include <stdio.h>
int
main(void)
{
int i, j;
for(i = 1; i <= 6; ++i) {
for(j = 0; j < i; ++j)
printf("%d", j);
printf("\n");
}
return(0);
}
The answer had some reasearch effort, was clear; maybe useful for someone studying the same subject, so it was downvoted for no reason.
Solution
You can actually do this with a single nested loop:
#include <stdio.h>
int getLength(int i) {
/* Since this is homework, I'll leave this for you to complete. */
if (i < ?) return ?;
else return ?;
}
int main(void) {
for(int i = 0; i < 11; ++i) {
int length = getLength(i);
for(int j = 0; j < length; ++j) {
printf("%d", j);
}
printf("\n");
}
return 0;
}
OTHER TIPS
There's a clue in the question: "Write nests of loops". Count up, then count down.
Since this is an exercise I will only hint at a solution, as to learn you really should do this yourself.
for
loops can go in reverse.- You can have more than one nested loop.
for(int i=0;i<=10;i++)
{
if(i<=5)
{
for(int k=0;k<=i;k++)
printf("%d",k);
}
else if(i>5)
{
for(int j=0;j<=(10-i);j++)
printf("%d",j);
}
printf("\n");
}
i hope that will help
this is the defualt answer
I thought user should tell till which number to print. so my code is a bit complex.
include
include
int main (void) {
int rows;
int counter;
int backward;
int forward;
printf("Till which number you want to print??");
scanf("%d",&rows);
for(counter=0;counter<=rows;counter++)
{for(forward=0;forward<=counter;forward++)
printf("%d",forward);
printf("\n");
}
for(counter=rows;counter>=0;counter--)
{for(backward=0;backward<=counter;backward++)
printf("%d",backward);
printf("\n");
}
getch();
return 0;
}
Thank u !