Height Pattern Printing
Generate a graphical column chart using '#' and '-' characters based on a given list of integer heights.
Understand the Problem
Problem Statement
You are given the heights of N cats. Your task is to print a graphical representation of these heights as a vertical column chart.
The chart should be constructed using the # character to represent the bars and the - character for empty space, as shown in the examples.
Constraints
2 <= N <= 100(Number of cats)1 <= Height of each cat <= 100
Examples
6
10 4 2 6 7 2# - - - - -
# - - - - -
# - - - - -
# - - - # -
# - - # # -
# - - # # -
# # - # # -
# # - # # -
# # # # # #
# # # # # # The maximum height is 10, so 10 rows are printed. The first cat has height 10, so it gets a '#' in all 10 rows. The second cat has height 4, so it gets a '#' only in the bottom 4 rows (when the height level is 1, 2, 3, or 4), and so on.
10
1 2 3 4 5 6 7 8 9 10- - - - - - - - - #
- - - - - - - - # #
- - - - - - - # # #
- - - - - - # # # #
- - - - - # # # # #
- - - - # # # # # #
- - - # # # # # # #
- - # # # # # # # #
- # # # # # # # # #
# # # # # # # # # # The maximum height is 10. The heights increase from 1 to 10. This creates a diagonal pattern. The last cat (height 10) has a '#' in every row, while the first cat (height 1) only has a '#' in the very last row (when the height level is 1).
Solution
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int heights[n];
int max_height = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &heights[i]);
if (heights[i] > max_height) {
max_height = heights[i];
}
}
for (int level = max_height; level >= 1; level--) {
for (int i = 0; i < n; i++) {
if (heights[i] >= level) {
printf("# ");
} else {
printf("- ");
}
}
printf("\n");
}
return 0;
}- Include Header: We include
<stdio.h>for input/output functions. - Read N: We read the number of cats,
n, from the first line of input. - Declare Array and Find Max: An integer array
heightsof sizenis declared (using a Variable-Length Array). We also initializemax_heightto 0. We then loopntimes to read each cat's height. Inside this loop, we updatemax_heightif the current height is greater than the current max. - Outer Loop (Rows): The first
forloop iterates fromlevel = max_heightdown to1. This loop controls which row of the chart is currently being printed. - Inner Loop (Columns): The second, nested
forloop iterates fromi = 0ton-1. This loop goes through each cat for the current row (level). - Print Character: Inside the inner loop, an
ifcondition checks if the height of the current cat (heights[i]) is greater than or equal to the currentlevel. If it is,#is printed; otherwise,-is printed. - Newline: After the inner loop completes,
printf("\n");is called to move the cursor to the next line for the next row of the chart.