The Right Triangle, often referred to as a Half Pyramid, is a quintessential pattern in C programming
What You Will Learn
In this tutorial, we will walk through the implementation of a C program that prints a right triangle of stars. You will learn how to structure nested loops to create a pattern that expands linearly with each row
Prerequisites:
A solid understanding of nested
forloops. Familiarity with the
printffunction.
Final Output:
If we choose a triangle height of 5, the output will appear as follows:
**
***
****
*****
Deconstructing the Pattern: The Logic
1. The Visual Representation
The right triangle is characterized by a "staircase" effect
Row 1: 1 star
. Row 2: 2 stars
. Row 3: 3 stars
. Row 4: 4 stars
. Row 5: 5 stars
.
2. Problem Statement
The objective is to print a pattern of symbols where the number of stars in each row is equal to the current row number
3. Pattern Analysis & Logic
Identifying the Rows: We use an outer loop to control the vertical height, running from i = 1 to n.
Identifying the Columns: We use an inner loop to print the star symbol horizontally
. To create the triangular effect, the inner loop runs from j = 1 to i. Algorithm:
Initialize the size n.
Start an outer loop for the rows (from 1 to n)
. Inside, start an inner loop for the columns (from 1 to i)
. Print the star symbol
. Print a newline character after the inner loop finishes to move to the next row
.
The Code Implementation
int main() {
int n = 5; // Height of the triangle
// Outer loop for rows
for (int i = 1; i <= n; i++) {
// Inner loop for columns, dependent on row number i
for (int j = 1; j <= i; j++) {
printf("*"); // Print the star symbol
}
// Move to the next line after each row
printf("\n");
}
return 0;
}
Explanation:
int n = 5;: We define the total height of our triangle. for (int i = 1; i <= n; i++): The outer loop manages the rows. for (int j = 1; j <= i; j++): This is the core logic. By limiting the inner loop to $i$, we ensure that each row contains exactly $i$ stars . printf("\n");: This ensures that the program moves to a new line after printing the required number of stars for the current row.
Sample Output and Analysis
User Input:
The code is set for n = 5.
Program Output:
**
***
****
*****
Output Analysis:
In the first iteration (i=1), the inner loop runs once. In the fifth iteration (i=5), the inner loop runs five times, creating the characteristic right-angled slope
Complexity Analysis
Time Complexity: O(n^2), as the inner loop execution increases with each row, resulting in approximately \frac{n(n+1)}{2} operations
. Space Complexity: O(1), as the logic uses a constant amount of memory
.
Conclusion
You have successfully implemented a right triangle pattern by nesting a dynamic loop inside an outer loop
For all Pattern Programs list click here:
…till the next post, bye-bye & take care