Skip to content

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:

[ " * ", " *** ", "*****" ]
Code language: plaintext (plaintext)

And a tower with 6 floors looks like this:

[ " * ", " *** ", " ***** ", " ******* ", " ********* ", "***********" ]
Code language: plaintext (plaintext)

The solution in C

Option 1:

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

Option 2:

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

Option 3:

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

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]){" * ", " *** ", "*****"}); }
Code language: C++ (cpp)

See also  How to Solve the Sum of Triangular Numbers in C
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x