Printing a simple histogram using 2D array C program example

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: Printing a simple histogram using 2D array C program example

To show: How to print a simple histogram using 2D array in C programming

 

 

// Printing simple histogram

#include <stdio.h>

#include <stdlib.h>

#define SIZE 10

 

int main(void)

{

// declare and initialize an array named n with size SIZE...

int n[SIZE] = {19, 3, 15, 7, 11, 9, 13, 5, 17, 1};

int i, j;

 

// display the table header...

printf("%s%13s%17s\n","Element/index", "Value", "Histogram");

// do the iteration, outer for loop, read row by row...

for(i=0; i <= (SIZE-1); i++)

{

printf("%9d%15d ", i, n[i]);

 

// inner for loop, for every row, read column by column and print the bar...

for(j = 1; j<= n[i]; j++)

// print the 'bar', and repeat...

printf("*");

// go to new line for new row, and repeats...

printf("\n");

}

return 0;

}

 

Output example:

 

Element/index Value Histogram

0                            19 *******************

1                              3 ***

2                            15 ***************

3                              7 *******

4                            11 ***********

5                              9 *********

6                            13 *************

7                              5 *****

8                            17 *****************

9                              1 *

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index