This tutorial will guide you through creating a hollow number triangle pattern in C. This is an excellent intermediate pattern programming exercise that builds upon your knowledge of nested loops and conditional statements. By the end, you'll be able to create this classic pattern and understand the core logic of printing specific characters at certain positions.
Final Output
The final output is a number triangle with an empty interior. Only the numbers on the edges and the base are printed. For a user input of 5
, the output will look like this:
Enter the number of rows: 5
1
1 2
1 3
1 4
1 2 3 4 5
Deconstructing the Pattern: The Logic
The key to creating a hollow pattern is to use a conditional statement (if-else
) inside the inner loop. Instead of printing a number in every position, you will only print a number when the current position meets specific conditions. Otherwise, you'll print a space.
Problem Statement: The program should take an integer input n
from the user and print a hollow number triangle pattern.
Pattern Analysis & Logic:
Outer Loop (Rows): The pattern has
n
rows, so our outer loop will run fromi = 1
ton
. This loop controls the row number.Inner Loop (Columns): The number of columns in each row is equal to the row number,
i
. So, the inner loop will run fromj = 1
toi
.Conditional Printing: This is the most important part. Inside the inner loop, you need to check if the current position
(i, j)
should contain a number. The conditions are:If the current column is the first column (
j == 1
).If the current column is the last column of the current row (
j == i
).If the current row is the last row of the entire pattern (
i == n
).
The Conditional Statement: You will use an
if
statement to check these conditions:if (j == 1 || j == i || i == n)
. If any of these conditions are true, you print the value ofj
. Otherwise, you print a space.
Here is the step-by-step breakdown of the algorithm:
Start the program.
Declare integer variables
n
,i
, andj
.Prompt the user to enter the number of rows.
Read the user's input and store it in
n
.Create an outer
for
loop that iterates fromi = 1
ton
(for the rows).Inside the outer loop, create an inner
for
loop that iterates fromj = 1
toi
(for the columns).Inside the inner loop, use an
if-else
statement to check the conditions for printing a number vs. a space.After the inner loop finishes, use
printf("\n");
to move to the next line.Repeat the process until the outer loop completes.
The Code Implementation
Here is the complete C program, with inline comments to explain the logic of each loop and conditional statement.
#include <stdio.h>
int main() {
// Declare variables for rows and user input
int i, j, n;
// Prompt the user for the number of rows
printf("Enter the number of rows: ");
scanf("%d", &n);
// Outer loop for the rows
for (i = 1; i <= n; i++) {
// Inner loop for the columns
for (j = 1; j <= i; j++) {
// Check conditions for printing a number
if (j == 1 || j == i || i == n) {
printf("%d ", j);
} else {
printf(" "); // Print two spaces for alignment
}
}
// Move to the next line after each row is complete
printf("\n");
}
return 0;
}
Explanation:
for (i = 1; i <= n; i++)
: This is the outer loop that controls the total number of rows.for (j = 1; j <= i; j++)
: This inner loop runs for each row and controls the number of characters to be printed.if (j == 1 || j == i || i == n)
: This is the core of the hollow pattern.j == 1
: This condition is true for the first number in every row, creating the left edge.j == i
: This condition is true for the last number in every row, creating the right edge.i == n
: This condition is true for all numbers in the last row, creating the base.
printf("%d ", j);
: If any of the above conditions are true, this statement prints the numberj
followed by a space.printf(" ");
: If none of the conditions are met (meaning it's an interior position), this statement prints two spaces to maintain proper alignment.printf("\n");
: After the inner loop finishes, this statement moves the cursor to the next line.
Sample Output
Here is a dry-run example with a user input of n=4
.
i (Rows) | j (Cols) | Conditions j==1 , j==i , i==n | Output j |
1 | 1 | j==1 (True) | 1 |
2 | 1 | j==1 (True) | 1 |
2 | j==i (True) | 2 | |
3 | 1 | j==1 (True) | 1 |
2 | (False) | | |
3 | j==i (True) | 3 | |
4 | 1 | i==n (True) | 1 |
2 | i==n (True) | 2 | |
3 | i==n (True) | 3 | |
4 | i==n (True) | 4 |
Variations and Enhancements
Hollow Square: Modify the conditions to create a hollow square pattern.
Change the Character: You can easily adapt this logic to print a hollow star triangle by replacing
printf("%d ", j)
withprintf("* ")
.Challenge: Try to create a more complex hollow shape, such as a hollow full pyramid.
Common Mistakes and Troubleshooting
Incorrect Spacing: If the spacing is not consistent (e.g., using one space for numbers and two for the empty part), the pattern will look distorted. Make sure your
printf(" ");
is aligned correctly with the number output.Wrong Conditions: A small logical error in the
if
statement can break the entire pattern. Double-check that your conditions correctly identify the edges and base.Forgetting
\n
: Forgetting theprintf("\n");
statement will cause all the numbers and spaces to print on a single line, destroying the triangular shape.
Complexity Analysis
Time Complexity: The time complexity is O(n^2) because the program uses nested loops, and the number of operations grows quadratically with the input
n
.Space Complexity: The space complexity is O(1) as the program only uses a constant amount of memory for variables, regardless of the number of rows.
Conclusion
You have successfully learned how to build a hollow number triangle pattern, which is a key step toward understanding how to use conditional logic to manipulate output. This exercise strengthens your skills in using nested loops and if-else
statements, which are crucial for many programming challenges.
....till next post, bye-bye & take care!
No comments:
Post a Comment