Displaying a Star Triangle in C: Beginner-Friendly Guide
Introduction
Learning to print patterns in C is a fundamental exercise for beginners. One of the simplest yet interesting patterns is the star triangle.
Problem Statement
Write a C program to display n lines of the following triangle pattern:
*
* *
* * *
* * * *
The program should take the number of lines n as input and print the triangle using nested loops.
Logic
To print the star triangle:
- Take input
nfrom the user, which represents the number of lines. - Use a for loop to iterate from
1ton. - Inside this loop, use another for loop to print stars
*equal to the current line number. - Move to the next line after printing stars for a row.
This simple nested loop structure ensures the triangle grows line by line.
Source Code
#include <stdio.h>
int main() {
int n, i, j;
// Ask user for number of lines
printf("Enter the number of lines: ");
scanf("%d", &n);
// Loop through each line
for(i = 1; i <= n; i++) {
// Loop to print stars in each line
for(j = 1; j <= i; j++) {
printf("* ");
}
// Move to next line
printf("\n");
}
return 0;
}
Tip for beginners: The outer loop controls the number of rows, and the inner loop controls the number of stars printed on each row.
Sample Output
If the user enters 4 as input:
Enter the number of lines: 4
*
* *
* * *
* * * *
Viva Questions
- Q: What is a nested loop in C?
A: A nested loop is a loop inside another loop, used here to print stars row-wise. - Q: What does
printf("\n")do in this program?
A: It moves the cursor to the next line after printing stars for the current row. - Q: Can we print the triangle without using nested loops?
A: Yes, but it requires advanced logic like using a single loop with conditional printing. - Q: What type of variable is
iandjin the program?
A: They are integers used as loop counters. - Q: How can we modify the program to print a triangle upside down?
A: Start the outer loop fromndown to1and print stars accordingly.
