histogram help

i am writing a histogram and i am almost done i just need help with the final format of the astericks:

The longest bar always should contain 50 asterisks, and the other bars should be scaled proportionally. The sample input

450 401 3 78 444 200 -1

should look like:


          0- 99   2|*********************************
        100-199   0|
        200-299   1|*****************
        300-399   0|
        400-499   3|**************************************************
          500+    0|


here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
	int a=0,b=0,c=0,d=0,e=0,f=0,i=0;

	while (cin>>i)
	{
		if (i>0 && i<100)
			a++;
		else if (i>=100 && i<200)
			b++;
		else if (i>=200 && i<300)
			c++;
		else if (i>=300 && i<400)
			d++;
		else if (i>=400 && i<500)
			e++;
		else if (i>=500)
			f++;
		else
			if (i == -1 ) 
				break;
	}

	cout << setw (7) << "0-99" << setw (4) << a << "|";
	for (int i=0;i<a;i++)
		cout <<"*";
	cout<< endl;
	cout << setw (5) << "100-199" << setw (4) << b << "|";
	for (int i=0;i<b;i++)
		cout <<"*";
	cout<< endl;
	cout << setw (5) << "200-299" << setw (4) << c << "|";
	for (int i=0;i<c;i++)
		cout <<"*";
	cout<< endl;
	cout << setw (5) << "300-399" << setw (4) << d << "|";
	for (int i=0;i<d;i++)
		cout <<"*";
	cout<< endl;
	cout << setw (5) << "400-499" << setw (4) << e << "|";
	for (int i=0;i<e;i++)
		cout <<"*";
	cout<< endl;
	cout << setw (6) << "500+" << setw (5) << f << "|";
	for (int i=0;i<f;i++)
		cout <<"*";
	cout<< endl;
}

how should i do that??


Last edited on
You need to find the maximum value of a through f.
Then adjust the scale of the histogram by a factor of 50/max. i.e. change the number of asterisks printed by that factor.
i dont really know how to find the max of those numbers. do i need and array of some sort?


An array would be good if you had many values to deal with.
For just six, you can simply code it line by line.

First, declare an integer called max, and set it equal to a.
Then compare it with each of the other values, like this,
if (b>max) max = b; and do the same for c through f.
Last edited on
ok thanks i got that down but the scale of the histogram part still is knda confusing
well, this is what you have now:
1
2
    for (int i=0; i<a; i++)
        cout << "*";

Here the number of asterisks printed is a.
You just need to use a * 50 / max.
oh ok i was trying to repalce a with 50/max for some reason

thanks alot
Topic archived. No new replies allowed.