Pseudo code to print triangle
1. Take the number of rows as input from the user
2. For each row from 1 to the number of rows:
a. Print (number of rows - current row) spaces
b. Print current row number of asterisks
c. Move to the next line
3. End
This pseudo-code describes a simple algorithm for printing a triangle shape of asterisks, with one less space on each row than the previous row. The outer loop iterates from 1 to the number of rows and the inner loop iterates from 1 to the current row number which is used to print the number of asterisks. The first inner loop is used to print the spaces before the asterisks, and the second inner loop is used to print the asterisks. Each row has one more asterisk than the previous row, and one less space than the previous row, creating a triangle shape.
Approach to Print Triangle in C
- Take the number of rows as input from the user.
- Create a nested loop structure, with the outer loop iterating from 1 to the number of rows, and the inner loop iterating from ‘A’ to ‘A’ + current row – 1.
- Inside the outer loop, print (number of rows – current row) spaces before the inner loop starts.
- Inside the inner loop, print the current column character, which is the current iteration of the loop variable.
- Move to the next line after the inner loop finishes.
- End the program after the outer loop finishes.
C program to print the triangle
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for(i=1; i<=rows; i++) {
for(j=1; j<=rows-i; j++) {
printf(" ");
}
for(j=1; j<=i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
When you run this program, it will prompt the user to enter the number of rows for the triangle and then it will print a triangle shape of asterisks.
For example, if the user enters 5 as the number of rows, the program will output:
*
* *
* * *
* * * *
* * * * *
The outer loop controls the number of rows, and the inner loops control the number of spaces and asterisks in each row. The first inner loop is for printing the spaces before the asterisks, and the second inner loop is for printing the asterisks. Each row has one more asterisk than the previous row, and one less space than the previous row, creating a triangle shape.