Complementary task for topic: 2

M Nemeth · 2023-08-29 15:21:04.611220'

Loops: For loop: Print pyramid

Loops: For loop: Print pyramid

Task: Print a pyramid pattern:
Write a C program that uses nested for loops to print a pyramid pattern of asterisks (*). The number of rows in the pyramid should be determined by the user. Display the pyramid pattern using printf().

Hint: it is a challange to give the number of asterixes and required spaces in a parametric manner (row number). It alwas worth to try out on paper with a small example (e.g. rows=4)

Solution
#include 

int main() {
    int numRows;
    
    printf("Enter the number of rows in the pyramid: ");
    scanf("%d", &numRows);
    
    if (numRows <= 0) {
        printf("Invalid number of rows. Please enter a positive integer.\n");
        return 0;
    }
    
    int row, col, space;
    
    for (row = 1; row <= numRows; row++) {
        // Print spaces before the asterisks
        for (space = 1; space <= numRows - row; space++) {
            printf(" ");
        }
        
        // Print asterisks
        for (col = 1; col <= 2 * row - 1; col++) {
            printf("*");
        }
        
        // Move to the next line
        printf("\n");
    }
    
    return 0;
}



Explanation
In this example, the program prompts the user to enter the number of rows in the pyramid and stores it in the numRows variable. It performs input validation to ensure a valid number of rows.

The program uses nested for loops to print the pyramid pattern. The outer for loop controls the rows of the pyramid, and the inner for loops control the spaces and asterisks to be printed in each row.

Inside the outer for loop, the program uses another for loop to print the spaces before the asterisks. The number of spaces decreases as the row number increases, creating the pyramid shape.

After printing the spaces, the program uses another for loop to print the asterisks. The number of asterisks in each row is calculated using the formula 2 * row - 1, where row represents the current row number.

The program repeats this process for each row of the pyramid until the outer for loop terminates.
< < previous    next > >