How to create an alphabet rangoli (geometric and character pattern) of size N in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

/* Function to generate and print the alphabet rangoli of size N */
void printAlphabetRangoli(int n) {
    if (n <= 0) return;

    /* Total width of the grid based on character and hyphen spacing */
    int total_width = 4 * n - 3;

    /* Loop from -(n-1) to (n-1) to handle top/bottom symmetry mathematically */
    for (int i = -(n - 1); i <= (n - 1); ++i) {
        int current_row_dist = abs(i); /* Distance from the center row */

        /* In C we build strings manually using char buffers */
        char line_chars[256] = "";
        char temp[4];

        /* 1. Build the left/descending side of characters (e.g., e -> d -> c) */
        for (int j = 0; j < n - current_row_dist; ++j) {
            temp[0] = (char)('a' + n - 1 - j);
            temp[1] = '\0';
            strcat(line_chars, temp);
        }

        /* 2. Build the right/ascending side of characters (e.g., d -> e) */
        for (int j = n - current_row_dist - 2; j >= 0; --j) {
            temp[0] = (char)('a' + n - 1 - j);
            temp[1] = '\0';
            strcat(line_chars, temp);
        }

        /* 3. Insert hyphens between characters */
        char standard_row[512] = "";
        size_t len = strlen(line_chars);
        for (size_t k = 0; k < len; ++k) {
            temp[0] = line_chars[k];
            temp[1] = '\0';
            strcat(standard_row, temp);

            if (k != len - 1) {
                strcat(standard_row, "-");
            }
        }

        /* 4. Calculate necessary hyphen padding for centering */
        int total_padding = total_width - (int)strlen(standard_row);
        int side_len = total_padding / 2;

        char side_hyphens[256];
        memset(side_hyphens, '-', side_len);
        side_hyphens[side_len] = '\0';

        /* 5. Print the complete constructed row */
        printf("%s%s%s\n", side_hyphens, standard_row, side_hyphens);
    }
}

int main(void) {
    int n = 5;

    printAlphabetRangoli(n);
    
    return 0;
}


/*
run:

--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz
...