HomeSoftware EngineeringMethods to Construct a Tower in C

# Methods to Construct a Tower in C

## The problem#

Construct a pyramid-shaped tower, as an array/record of strings, given a constructive integer variety of flooring. A tower block is represented with "*" character.

For instance, a tower with 3 flooring appears like this:

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

And a tower with 6 flooring appears like this:

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

Choice 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] = ' ';
}

Choice 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);
}
}

Choice 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] = ' ');
}
}
}

## Check circumstances to validate our resolution#

#embrace <criterion/criterion.h>

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

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