Program 20:
#include<stdio.h> main() { int i,j,k,count,number; printf("Enter number of rows\n"); scanf("%d",&number); count=number-1; for(i=1;i<=2*(number)-1;i+=2)//first for loop { for(k=1;k<=count;k++) { printf(" "); } count--; for(j=1;j<=i;j++) { printf("*"); } printf("\n"); } //end of first for loop count=1; for(i=2*(number)-1;i>=1;i-=2)//second for loop { if(i!=(2*(number)-1)) { for(k=1;k<=count;k++) { printf(" "); } count++; for(j=i;j>=1;j--) { printf("*"); } printf("\n"); } }//end of second for loop }Explanation:
- The program starts with initializing
- i,j,k → helping variable
- number → to store number of rows
- count → to store number of spaces
- There are two for loops. First one is used to print a normal triangle and second is used to print reverse triangle
- Say in the below example we want 10 rows to be printed.First for loop prints 10 rows of normal triangle and second will do the same in reverse.
- Coming to 1st for loop
-
for(i=1;i<=2*(number)-1;i+=2)
-
for(k=1;k<=count;k++) { printf(" "); }
count--;
- As if you see in the output below:for 1st star it needs 9 spaces from the left end and it should go on decreasing for every loop which is why we used count--
-
for(j=1;j<=i;j++) { printf("*"); } printf("\n"); } //end of first for loop
- So till now we got upper triangle.
-
- Coming to 2nd for loop
-
for(i=2*(number)-1;i>=1;i-=2)//second for loop {
-
if(i!=(2*(number)-1)) {
-
for(k=1;k<=count;k++) { printf(" "); } count++;
-
for(j=i;j>=1;j- -) { printf("*"); }
-
No comments:
Post a Comment