Monday, 7 October 2019

C program for pyramid

Logic to print pyramid star pattern

    *
   ***
  *****
 *******
*********
Before you read further have a close look at the above pattern. The pattern consists of N (for this case 5) rows. Each row contain exactly 2 * N - 1 stars. In addition to stars the pattern has leading spaces. Each row contain N - i spaces (where i is current row number). To count total spaces per row point your mouse over the above pattern.
Step by step descriptive logic to print Pyramid star pattern.
  1. Input number of rows to print from user. Store it in a variable say rows.
  2. To iterate through rows, run an outer loop from 1 to rows. The loop structure should look like for(i=1; i<=rows; i++).
  3. To print spaces, run an inner loop from i to rows - 1. The loop structure should look like for(j=i; j<rows; j++). Inside this loop print single space.
    Note: Iterating from 1 to N - i or i to rows - 1 both are equal.
  4. To print star, run another inner loop from 1 to 2 * i - 1. The loop structure should look like for(j=1; j<=(2*i - 1); j++). Inside this loop print star.
  5. After printing stars for current row, move to next line i.e. print new line.

Program to print pyramid star pattern series

/** * C program to print equilateral triangle or pyramid star pattern */ #include <stdio.h> int main() { int i, j, rows; /* Input number of rows to print */ printf("Enter number of rows : "); scanf("%d", &rows); /* Iterate through rows */ for(i=1; i<=rows; i++) { /* Print leading spaces */ for(j=i; j<rows; j++) { printf(" "); } /* Print star */ for(j=1; j<=(2*i-1); j++) { printf("*"); } /* Move to next line */ printf("\n"); } return 0; }

No comments:

Post a Comment