This code is for printing the inverse half pyramid:
* * *
* *
*
#include<stdio.h>
int main() {
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d", &rows);
for (i=rows; i>=1; --i)
{
for (j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}
Let's say if I enter rows = 5, then "i" will initialize its value as 5, check if it's greater than 1, then we go to the 2nd for loop, where j has the initial value of 1, and then check if it's less than the value of "i= 5", which it IS, then after that, how will the second loop run?
The first for
loop is to decrement from 5 ( rows
variable) to 1 (since it is inverted half pyramid).
The second/inner for
loop (loop j
) is to print the *
character i
times ( i
is set in outer for
loop).
Once the inner for
loop exits, a new line is printed ( \\n
) and i
is decremented and the inner loop runs again for the new value of i
.
* * * *
* * *
* *
*
The above pattern contains N
rows and each row contains Ni + 1
columns (where i
is the current row number). Considering this let us write a step by step descriptive logic to print inverted right triangle star pattern.
Input number of rows to print from user. Store it in a variable say rows
.
To iterate through rows run an outer loop from 1 to rows
. The loop structure should look like for(i=1; i<=rows; i++)
.
To iterate through columns run an inner loop from i
to rows
. The loop structure should look like for(j=i; j<=rows; j++)
. Inside this loop print star.
Note: Instead of iterating from i
to rows
you can also iterate from 1 to rows - i + 1
.
After printing all columns of a row, move to next line ie print new line.
Good explanation taken from https://codeforwin.org/2015/07/inverted-right-triangle-star-pattern-program-in-c.html
/**
* Reverse right triangle star pattern program in C
*/
#include <stdio.h>
int main()
{
int i, j, rows;
/* Input number of rows from user */
printf("Enter number of rows : ");
scanf("%d", &rows);
/* Iterate through rows */
for(i=1; i<=rows; i++)
{
/* Iterate through columns */
for(j=i; j<=rows; j++)
{
printf("* ");
}
/* Move to the next line */
printf("\n");
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.