 範例(圖6.8)會從陣列讀取數值,再以⾧條圖(histogram)印出來,先印出每個數字,然後再根據其大小印出相同數目的星號。

 巢狀for敘述式會負責印出這些⾧條圖(#18-20),最後再使puts(“”)結束每個⾧條圖的列印(#22)。

Untitled

#include <stdio.h>
#define SIZE 5
// function main begins program execution 
int main(void)
{
// use initializer list to initialize array n 
int n[SIZE] = {19, 3, 15, 7, 11};
printf("%s%13s%17s\\n", "Element", "Value", "Histogram");
// for each element of array n, output a bar of the histogram 
for (size_t i = 0; i < SIZE; ++i) {
 	printf("%7u%13d ", i, n[i]);
	for (int j = 1; j <= n[i]; ++j) {
	// print one bar
	printf("%c",'*');
	}
	puts("");
	// end a histogram bar with a newline 
}
}