how to print triangle pattern in c
#include <stdio.h>
int main() {
int rows, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Explanation:
The
#include <stdio.h>
line includes the standard input/output library, which provides functions likeprintf
andscanf
.The
int main()
function is the entry point of the program. It returns anint
value, which is typically 0 to indicate successful execution.We declare three variables:
rows
,i
, andj
.rows
is used to store the number of rows the user wants to print, whilei
andj
are loop counters.The
printf
function is used to display a message asking the user to enter the number of rows.The
scanf
function is used to read the user's input and store it in therows
variable.The outer
for
loop is used to iterate over the rows. It starts from 1 and goes up torows
.The inner
for
loop is used to print the asterisks in each row. It starts from 1 and goes up to the current value ofi
.Inside the inner loop, the
printf
function is used to print an asterisk followed by a space.After printing all the asterisks in a row, the
printf
function is used to print a newline character (\n
) to move to the next line.Once all the rows are printed, the
return 0;
statement is used to indicate successful program execution.
This program uses nested loops to print a triangle pattern of asterisks. The outer loop controls the number of rows, while the inner loop controls the number of asterisks in each row.