Timur Almamedov Timur Almamedov - 2 months ago 6
C Question

How to write proper loop in [C]

I need to make 10 numbers display using "loops" like this:

1
2 3
4 5 6
7 8 9 10


I managed to make it happen with the code below. But I feel like there must be an easier way to do this. What if I needed to do the same pattern, but had 1000 numbers? That would be a lot of code.

#include <stdio.h>

int main(){

int x;
x=1;

do {
printf("%i \n", x);
x++;
} while (x<=1);

do {
printf("%i ", x);
x++;

} while (x<=3); {
printf("\n");
}

do {
printf("%i ", x);
x++;

} while (x<=6); {
printf("\n");
}
do {
printf("%i ", x);
x++;

} while (x<=10); {
printf("\n");
}


return 0;
}

Answer
#include <stdio.h>

void main() {
    int row = 1;
    int column = 1;

    for (int i = 1; i <= 10; i++) {
        printf("%d", i);

        if (column == row) {
            printf("\n");
            row++;
            column = 1;
        }
        else {
            printf(" ");
            column++;
        }
    }
}