How to build a pyramid from the numbers 3, 7, 5, 2, 4, 8, 6, 9, 0, 3 in C

1 Answer

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

#define MAX 20

// ------------------------------------------------------------
// Build a pyramid from a flat list of numbers
// ------------------------------------------------------------
int buildPyramid(const int nums[], int count, int pyramid[][MAX]) {
    int index = 0;
    int rowSize = 1;
    int rows = 0;

    while (index + rowSize <= count) {
        for (int i = 0; i < rowSize; i++) {
            pyramid[rows][i] = nums[index++];
        }
        rows++;
        rowSize++;
    }

    return rows; // number of rows in the pyramid
}

// ------------------------------------------------------------
// Print the pyramid centered
// ------------------------------------------------------------
void printPyramid(int pyramid[][MAX], int rows) {
    for (int r = 0; r < rows; r++) {
        // Print leading spaces
        int spaces = (rows - r - 1) * 2;
        for (int s = 0; s < spaces; s++)
            printf(" ");

        // Print row values
        for (int c = 0; c <= r; c++) {
            printf("%d   ", pyramid[r][c]);
        }
        printf("\n");
    }
}

// ------------------------------------------------------------
// Main program
// ------------------------------------------------------------
int main() {
    int numbers[] = {3, 7, 5, 2, 4, 8, 6, 9, 0, 3};
    int count = sizeof(numbers) / sizeof(numbers[0]);

    int pyramid[MAX][MAX] = {0};

    int rows = buildPyramid(numbers, count, pyramid);

    printf("Pyramid:\n");
    printPyramid(pyramid, rows);

    return 0;
}


/*
run:

Pyramid:
      3   
    7   5   
  2   4   8   
6   9   0   3   

*/

 



answered 2 hours ago by avibootz
...