Reputation: 57
An output is given in the following form :
OUTPUT :
0
111
22222
3333333
... up to 9.
The task I was given was to write a code for this output using nested for
loops.
The closest I have gotten to figuring it out is this:
#include <stdio.h>
#include <conio.h>
int main()
{
int x=0, y=0, z=0;
for (x=1; x<=9; x=x+1)
{
printf("\n");
for (y=0; y<=10; y=y+1)
{
for(z==y; y<x; y++)
{
printf("%d", x);
}
}
}
}
I was also instructed to "Refrain from using Arrays or others methods of solving this question."
I cant figure out my mistake. Help would be appreciated.
The output from this program is here: https://i.sstatic.net/IfNPe.png
Upvotes: 1
Views: 127
Reputation: 16184
Iterate all numbers (x
), while incrementing the number of prints (y
) by 2, strting from 1
(see online):
for (int x = 0, y = 1; x <= 9; x++, y += 2)
{
for (int z = 0; z < y; z++)
printf("%d", x);
printf("\n");
}
I would say
for (int x = 0; x <= 9; x++) {
for (int y = 0; y < x * 2 + 1; y++)
printf("%d", x);
printf("\n")
}
is more elegant, but it can be a little tricky to follow.
Upvotes: 4
Reputation: 25286
That would be then:
int main()
{
int x, y, z;
printf("0");
for (x=1, y=3; x<=9; x++, y+=2)
{
printf("\n");
for (z=y; z; z--)
{
printf("%d", x);
}
}
}
Output:
0
111
22222
3333333
444444444
55555555555
6666666666666
777777777777777
88888888888888888
9999999999999999999
Upvotes: 1