FYBCom(CA) C Practical Slip 3 Q 1.A

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:

  1. Take input n from the user, which represents the number of lines.
  2. Use a for loop to iterate from 1 to n.
  3. Inside this loop, use another for loop to print stars * equal to the current line number.
  4. 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

  1. 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.
  2. 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.
  3. 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.
  4. Q: What type of variable is i and j in the program?
    A: They are integers used as loop counters.
  5. Q: How can we modify the program to print a triangle upside down?
    A: Start the outer loop from n down to 1 and print stars accordingly.
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top