How to print a line chart using printf in C language?
To print a line graph using printf, you can use loops and conditional statements to control the output of characters. Here is an example code:
#include <stdio.h>
void printLineChart(int data[], int n) {
int max = data[0];
for (int i = 1; i < n; i++) {
if (data[i] > max) {
max = data[i];
}
}
for (int i = max; i > 0; i--) {
for (int j = 0; j < n; j++) {
if (data[j] >= i) {
printf("* ");
} else {
printf(" ");
}
}
printf("\n");
}
for (int i = 0; i < n; i++) {
printf("%d ", data[i]);
}
printf("\n");
}
int main() {
int data[] = {5, 3, 8, 2, 7};
int n = sizeof(data) / sizeof(data[0]);
printLineChart(data, n);
return 0;
}
In the above code, the printLineChart function takes an integer array and the array length as parameters, with the array data storing the data to be plotted on the line chart. Initially, by iterating through the array and finding the maximum value, the highest point of the chart is determined.
Next, utilize nested for loops to iterate through each row and each column, determining whether or not to print an asterisk * in the corresponding position based on the data size. If the data is greater than or equal to the current row number, an asterisk is printed; otherwise, a space is printed. This allows for the output to be printed in the form of a line graph.
Finally, use a simple for loop to output the data itself as the bottom scale.
When running the above code, the output is as follows:
* *
* *
* * *
* * *
* * * *
5 3 8 2 7
By using printf to print characters according to certain rules, a simple line graph effect can be achieved.