0

how we can print a number triangle?

like this 1 with input 10. 2 3 4 5 6 7 8 9 10

19th Mar 2021, 5:10 AM
reza
reza - avatar
7 Answers
+ 4
Yaa ... Eddy M you are right, I'm sorry for it. It happened because of my misunderstanding.
19th Mar 2021, 8:48 AM
axita
axita - avatar
+ 2
You can use for or while loop for it. for (i = 1; i <= 10; ++i) { printf(" "); for (j = 1; j <= i; ++j) { printf("%d ", i); } printf("\n"); }
19th Mar 2021, 7:31 AM
axita
axita - avatar
+ 1
@axita I think your code would print 10 rows made up of identical numbers. Probably it's not necessary to write the code for arbitrary input so the number of spaces printed first need to descend from 3 on first row to 0 on the 4th.
19th Mar 2021, 7:51 AM
Eddy M
+ 1
@reza let us see your attempt
19th Mar 2021, 7:51 AM
Eddy M
+ 1
Try to understand this code and then write your own version. I used "-" instead of " " to align better in Code PlayGround. It only prints 10 numbers now, as in your sample output. Can you generalize it? #include <stdio.h> int main() { int n = 0; for (int i = 1; i <= 4; ++i) { for (int j = 4-i; j>0; j--) { printf("-"); } for (int j = 1; j <= i; ++j) { n++; printf("%d ", n); } printf("\n"); } return 0; }
19th Mar 2021, 1:22 PM
Eddy M
0
hey guys thanks for your help @axita but i want an output like this 1 2 3 4 5 6 7 8 9 10
19th Mar 2021, 9:25 AM
reza
reza - avatar
0
hey @Eddy ok this is my code but i think it has many problems #include <stdio.h> int main() { int x; scanf("%d",&x); int i,j; for(i=1;i<=x/2;i++) { for(j=1;j<=x-i;j++) { printf(" "); } for(j=i+1;j<2*i+1;j++) { printf("%d ",j); } printf("\n"); } return 0; }
19th Mar 2021, 9:27 AM
reza
reza - avatar