-
Histogram
Okay, I'm on the last section of my program, and I'm stuck yet again. I need to make a histogram for the data in my program. Here is my function for it:
Code:
void display_histogram( int arr[], int no_items )
/*========================================================================
This function displays a histogram (bar graph) of the data in intervals of 10.
INPUT: an array of integers, an integer which represents the number of items
OUTPUT: this function returns nothing
========================================================================*/
{
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
int counter7 = 0;
int counter8 = 0;
int counter9 = 0;
int counter10 = 0;
int data;
data = arr[no_items];
for ( int i = 0; i < no_items; i++ )
{
if ( data >= 0 && data <= 10 )
{
counter1++;
}
if ( data >= 11 && data <= 20 )
{
counter2++;
}
if ( data >= 21 && data <= 30 )
{
counter3++;
}
if ( data >= 31 && data <= 40 )
{
counter4++;
}
if ( data >= 41 && data <= 50 )
{
counter5++;
}
if ( data >= 51 && data <= 60 )
{
counter6++;
}
if ( data >= 61 && data <= 70 )
{
counter7++;
}
if ( data >= 71 && data <= 80 )
{
counter8++;
}
if ( data >= 81 && data <= 90 )
{
counter9++;
}
if ( data >= 91 && data <= 100 )
{
counter10++;
}
}
cout << " 1 - 10: " << counter1 << endl;
cout << "11 - 20: " << counter2 << endl;
cout << "21 - 30: " << counter3 << endl;
cout << "31 - 40: " << counter4 << endl;
cout << "41 - 50: " << counter5 << endl;
cout << "51 - 60: " << counter6 << endl;
cout << "61 - 70: " << counter7 << endl;
cout << "71 - 80: " << counter8 << endl;
cout << "81 - 90: " << counter9 << endl;
cout << "91 - 100: " << counter10 << endl << endl;
}
This isn't working, although I'm not really sure if it even should. The Code:
data = arr[no_items];
line especially seems off to me. Also, is there any way I can take the numbers stored in each counter variable and use them to display the appropriate number of asterisks next to each interval of 10?
-
Code:
data = arr[no_items]; //delete this
for ( int i = 0; i < (no_items - 1); i++ )
{
data = arr[i];
if ( data >= 0 && data <= 10 )
{
counter1++;
}
.....and so on ....
note: You could reconstruct this to an if-else statement and
you won't need to check both lower and upper limit for data's
value each run. I leave it to you to figure that out.
>> Also, is there any way I can take the numbers stored in each counter variable and use them to display the appropriate number of asterisks next to each interval of 10?
Construct a for loop than runs as many times as the value of the counter; print an asterisk for each run.