A triangle pattern in C is a pattern of characters arranged in successive rows to form a triangular shape. It can be printed using nested loops, where the outer loop controls the rows and the inner loop prints the characters.
- The number of characters increases with each row.
- Nested loops are used to control the rows and characters in the pattern.
Example
Input:Â 5
Output:
*Â
* *Â
* * *Â
* * * *Â
* * * * *
Approach
The triangle pattern can be printed using two nested loops:
- Take the number of rows n as input.
- Use the outer loop to iterate through each row.
- Use the inner loop to print stars in the current row.
- Print a newline after each row.
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
// Iterate through each row
for (int i = 1; i <= n; i++) {
// Print stars in the current row
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Output
For input 5, the output is:
*
* *
* * *
* * * *
* * * * *
Explanation
- The outer loop runs from 1 to n and represents the rows.
- The inner loop runs from 1 to i, so each row contains i stars.
- printf("\n") moves the cursor to the next line after printing each row.