w3resource

C Exercises: Display the pattern like a pyramid containing odd number of asterisks

C For Loop: Exercise-20 with Solution

Write a C program to display the pattern as a pyramid using asterisks, with each row containing an odd number of asterisks.

The pattern is as below:

   *
  ***
 *****

Visual Presentation:

Display the pattern like a pyramid containing odd number of asterisks

Sample Solution:

C Code:

#include <stdio.h> // Include the standard input/output header file.

int main() {
    int i, j, n; // Declare variables to store input and control loop indices.

    // Prompt the user to input the number of rows for the pattern.
    printf("Input number of rows for this pattern :");
    scanf("%d", &n); // Read the value of 'n' from the user.

    for (i = 0; i < n; i++) // Loop for the number of rows.
    {
        for (j = 1; j <= n - i; j++) // Loop to print spaces before the stars.
            printf(" ");

        for (j = 1; j <= 2 * i - 1; j++) // Loop to print the stars.
            printf("*");

        printf("\n"); // Move to the next line after printing each row.
    }

    return 0; // Return 0 to indicate successful execution.
}


Sample Output:

Input number of rows for this pattern :5                                                                      
                                                                                                              
    *                                                                                                         
   ***                                                                                                        
  *****                                                                                                       
 ******* 

Flowchart :

Flowchart: Display the pattern like pyramid containing odd number of asterisks

C Programming Code Editor:

Previous: Write a program in C to display the n terms of harmonic series and their sum.
Next: Write a program in C to display the sum of the series [ 9 + 99 + 999 + 9999 ...].

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.