Created
June 12, 2022 04:01
-
-
Save sumeet/b8f9acd8ed4086f330ff728a0dda9a3e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| // we're going for something like this | |
| // | |
| // * // row #0 // 1 star | |
| // * * * // row #1 // 3 stars | |
| // * * * * * // row #2 // 5 stars | |
| // * * * * * * * // row #3 // 7 stars | |
| // * * * * * * * * * // row #4 // 9 stars | |
| int num_stars(int row_index) { | |
| return 2*row_index+1; | |
| } | |
| void triangle(int num_rows) { | |
| int last_row = num_rows - 1; | |
| int num_stars_in_last_row = num_stars(last_row); | |
| int maximum_line_length = num_stars_in_last_row * 2; | |
| for (int this_row_index = 0; this_row_index < num_rows; this_row_index++) { | |
| int num_stars_in_this_row = num_stars(this_row_index); | |
| int line_length = num_stars_in_this_row * 2; | |
| int shift_distance = (maximum_line_length - line_length) / 2; | |
| for (int i = 0; i < shift_distance; i++) printf(" "); | |
| for (int i = 0; i < num_stars_in_this_row; i++) printf("* "); | |
| printf("\n"); | |
| } | |
| } | |
| int main() { | |
| triangle(5); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment