Write a loop statement that will show the following output: 1 12 123 1234 12345
Write a loop statement that will show the following output:
1
12
123
1234
12345
Write a loop statement that will show the following output:
1
12
123
1234
12345
Best answer
Use two nested for loops: the outer loop picks the row number, and the inner loop prints 1 up to that row number, followed by a new line.
#include <stdio.h>
int main() {
int a, b;
for (a = 1; a <= 5; a++) {
for (b = 1; b <= a; b++)
printf("%d", b);
printf("\n");
}
return 0;
}Output:
1
12
123
1234
12345
When a = 1 the inner loop prints 1; when a = 2 it prints 12; and so on up to 12345. The braces around the outer loop body are needed so that printf("\n") runs after every row, and the outer loop must update its own variable (a++).
Log in or create a free account to answer this question.