Hey guys ! I just started learning c programming in college . And i am stuck on a problem .
It says: Using two nested for loops print the following output:
1
22
333
4444
55555
I tried a couple of times but could not produce the output.
Please help.
Hey guys ! I just started learning c programming in college . And i am stuck on a problem .
It says: Using two nested for loops print the following output:
1
22
333
4444
55555
I tried a couple of times but could not produce the output.
Please help.
We can probably fix the code that you've already tried if you post it.
output:Code:#include<stdio.h> int main(void) { int i; int j; for(i=1;i<=5;i++){ printf("%d\n",i); for(j=i+1;j<=i+1;j++){ printf("%d",j); } } getch(); return 0; }
1
22
33
44
55
6
Two nested for loops are an easy way to work with printing out patterns like this. Use the outer one to count the rows you are printing, and use the inner one to control the actual char you will print, within that row.
Add an if statement inside the inner for loop, and you'll be good to go. Note the patterns you see, as you work through it by hand, with paper and pen. That's the logic, and you'll see it if you do it by hand, several times, and make yourself the computer cursor, in your imagination.
TRON!
Okay so, if the first loop controls what line you're on, the inner loop will actually have to do the printing. When the inner loop finishes, you have to start on a new line.
Your mistakes:
1. The first printf is not necessary.
2. Because you included 5 (see the code where i<=5), on i+1 when i = 5, it will print 6. So that is wrong.
3. Your first printf was also causing line breaks in the wrong places.
4. You printed j when you probably meant to print i. You want to print the line number i times. The j variable is only counting for you.
All together if you make some minor adjustments along these lines, it's fixed.
Good job!Code:#include<stdio.h> int main(void) { int i; int j; for(i=1; i<=5; i++) { for(j=1; j<=i; j++) { printf("%d", i); } printf("\n"); } return 0; }
Thankyou very much whiteflags !
i got it .