Complementary task for topic: 2

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

Loops: For loop: complex: print diamond

Loops: For loop: complex: print diamond

Task: Generate a diamond pattern:
Write a C program that uses nested for loops to generate a diamond pattern of asterisks (*). The size of the diamond should be determined by the user. Display the diamond pattern using printf().

Hint:

Solution
#include 

int main() {
    int size;
    
    printf("Enter the size of the diamond: ");
    scanf("%d", &size);
    
    if (size <= 0 || size % 2 == 0) {
        printf("Invalid size. Please enter an odd positive integer.\n");
        return 0;
    }
    
    int spaces = size / 2;
    int asterisks = 1;
    
    for (int row = 1; row <= size; row++) {
        // Print leading spaces
        for (int space = 1; space <= spaces; space++) {
            printf(" ");
        }
        
        // Print asterisks
        for (int star = 1; star <= asterisks; star++) {
            printf("*");
        }
        
        // Move to the next line
        printf("\n");
        
        if (row <= size / 2) {
            spaces--;
            asterisks += 2;
        } else {
            spaces++;
            asterisks -= 2;
        }
    }
    
    return 0;
}



Explanation
In this example, the program prompts the user to enter the size of the diamond and stores it in the size variable. It performs input validation to ensure a valid size, which should be an odd positive integer.

The program uses nested for loops to generate the diamond pattern. The outer for loop controls the rows of the diamond, 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 leading spaces before the asterisks. The number of spaces decreases as the row number increases up to the middle row, and then increases as the row number exceeds the middle row. This creates the diamond shape.

After printing the spaces, the program uses another for loop to print the asterisks. The number of asterisks increases as the row number increases up to the middle row, and then decreases as the row number exceeds the middle row.

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