Thread: 1 to 20 Triangle

1. 1 to 20 Triangle

Hi everyone! I need some help to shorten my code.
We have to use loops, since it's our current lesson.
We have to make something like this:

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6

20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20

The value of the number determines how many times it should be repeated. It then forms a right triangle.
I was able to make it, but is there any possible way to shorten it?

Code:
```#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
int z;
printf(“\n”);
printf(" 1");
printf("\n");
for(z=0;z<2;z++)
printf(" 2");
printf("\n");
for(z=0;z<3;z++)
printf(" 3");
printf("\n");
for(z=0;z<4;z++)
printf(" 4");
printf("\n");
for(z=0;z<5;z++)
printf(" 5");
printf("\n");
for(z=0;z<6;z++)
printf(" 6");
printf("\n");
for(z=0;z<7;z++)
printf(" 7");
printf("\n");
for(z=0;z<8;z++)
printf(" 8");
printf("\n");
for(z=0;z<9;z++)
printf(" 9");
printf("\n");
for(z=0;z<10;z++)
printf(" 10");
printf("\n");
for(z=0;z<11;z++)
printf(" 11");
printf("\n");
for(z=0;z<12;z++)
printf(" 12");
printf("\n");
for(z=0;z<13;z++)
printf(" 13");
printf("\n");
for(z=0;z<14;z++)
printf(" 14");
printf("\n");
for(z=0;z<15;z++)
printf(" 15");
printf("\n");
for(z=0;z<16;z++)
printf(" 16");
printf("\n");
for(z=0;z<17;z++)
printf(" 17");
printf("\n");
for(z=0;z<18;z++)
printf(" 18");
printf("\n");
for(z=0;z<19;z++)
printf(" 19");
printf("\n");
for(z=0;z<20;z++)
printf(" 20");
getch();
return 0;
}```
*looks more of a stairs than a triangle though

2. Look at your code and try to recognize the pattern:

Code:
```for(z=0;z<1;<++)
printf(" 1");
printf("\n");
for(z=0;z<2;z++)
printf(" 2");
printf("\n");
// ...
for(z=0;z<20;z++)
printf(" 20");
printf("\n");```
The only thing that changes is the number you are comparing against, and you print this number as well. I would write this in its own loop like this

Code:
```for(int j=1; j<=20; j++) {
// your code here
}```

3. Yikes!
Code:
```for(z=0;z<1;<++)
printf(" 1");
printf("\n");
for(z=0;z<2;z++)
printf(" 2");
printf("\n");
// ...
for(z=0;z<20;z++)
printf(" 20");
printf("\n");```

When you see your code starting to go this way, < STOP >, because it's nearly always a huge waste of time, that you'll just end up deleting later, anyway.

Take a step back, and get a better perspective on the problem.

Popular pages Recent additions