Search code examples
crecursionfor-loopprocedural-programmingrepeat

How to solve this peculiar nested for loops exercise?


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;
    }