Software Engineering

How to Build a Tower in C


The challenge

Build a pyramid-shaped tower, as an array/list of strings, given a positive integer number of floors. A tower block is represented with "*" character.

For example, a tower with 3 floors looks like this:

[
  "  *  ",
  " *** ", 
  "*****"
]

And a tower with 6 floors looks like this:

[
  "     *     ", 
  "    ***    ", 
  "   *****   ", 
  "  *******  ", 
  " ********* ", 
  "***********"
]

The solution in C

Option 1:

void build_tower(unsigned n, char tower[n][2 * n - 1]) {
  for (unsigned int i = 0; i < n; i++)
    for (unsigned int j = 0; j < 2 * n - 1; j++)
      if (j >= (n - 1) - i && j <= (n - 1) + i)
        tower[i][j] = '*';
      else
        tower[i][j] = ' ';
}

Option 2:

void build_tower(unsigned n, char tower[n][2 * n - 1]) {
  int len = 2 * n - 1;
    for (int i = 0; i < n; i++) {
        memset(tower[i], ' ', len);
        memset(tower[i] + len/2 - i, '*', i * 2 + 1);
    }
}

Option 3:

void build_tower(unsigned n, char tower[n][2 * n - 1]) {
  for(unsigned i = 0; i < n; i++){
    for(unsigned j = 0; j < (2 * n - 1); j++){
      (j >= n - 1 - i && j <= n - 1 + i) ? (tower[i][j] = '*') : (tower[i][j] = ' ');
    }
  }
}

Test cases to validate our solution

#include <criterion/criterion.h>

extern void do_test (unsigned n, const char expected[n][2 * n - 1]);

Test(tests_suite, sample_tests) {
	do_test(1, (char[1][1]){"*"});
	do_test(2, (char[2][3]){" * ", "***"});
	do_test(3, (char[3][5]){"  *  ", " *** ", "*****"});
}