C (programming language)

C Program to Print Mirrored Rhombus Star Pattern

Introduction

This guide will explore the creation of a C program that generates a visually appealing mirrored rhombus pattern composed of stars. We’ll break down the logic, code structure, and key steps involved in crafting this pattern.

Understanding the Pattern

  • Shape: The pattern resembles a diamond-like shape with a vertical line of symmetry.
  • Composition: Stars (*) form the visual elements of the pattern.
  • Arrangement: The stars are arranged in rows to create the rhombus shape.
  • Symmetry: The pattern is mirrored, meaning the first half of the rows mirror the second half.

Steps to Implement

  1. Include Necessary Header:

C

#include <stdio.h>
  1. Declare Variables:

C

int rows, i, j, spaces;
  1. Get Input for Number of Rows:

C

printf("Enter the number of rows: ");
scanf("%d", &rows);
  1. Print the Upper Half of the Rhombus:

C

for (i = 1; i <= rows; i++) {
    // Print spaces before stars
    for (spaces = 1; spaces <= rows - i; spaces++) {
        printf(" ");
    }

    // Print stars
    for (j = 1; j <= 2 * i - 1; j++) {
        printf("*");
    }

    printf("\n");  // Move to the next line
}
  1. Print the Lower Half of the Rhombus:

C

for (i = rows - 1; i >= 1; i--) {
    // Print spaces before stars
    for (spaces = 1; spaces <= rows - i; spaces++) {
        printf(" ");
    }

    // Print stars
    for (j = 1; j <= 2 * i - 1; j++) {
        printf("*");
    }

    printf("\n");  // Move to the next line
}

Complete Example Code:

C

#include <stdio.h>

int main() {
    int rows, i, j, spaces;

    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    // Print upper half of the rhombus
    for (i = 1; i <= rows; i++) {
        for (spaces = 1; spaces <= rows - i; spaces++) {
            printf(" ");
        }
        for (j = 1; j <= 2 * i - 1; j++) {
            printf("*");
        }
        printf("\n");
    }

    // Print lower half of the rhombus
    for (i = rows - 1; i >= 1; i--) {
        for (spaces = 1; spaces <= rows - i; spaces++) {
            printf(" ");
        }
        for (j = 1; j <= 2 * i - 1; j++) {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}

Key Points to Remember

  • The nested for loops handle the printing of stars and spaces in each row.
  • The spaces variable controls the indentation of stars to form the rhombus shape.
  • The program uses two separate loops to print the upper and lower halves, ensuring symmetry.
  • Adjust the rows variable to control the size of the rhombus pattern.

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

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

Back to top button