Histogram help
May 16, 2015 at 7:59am UTC
Can't seem to figure out how to output the histogram in this form:
*
* * *
* * * * *
* * * * * * *
-------------
1 2 3 4 5 6 7
for an input of - 1 2 2 1 4 5 4 2 3 5 6 7 4 1 2 -1. Note this is just an example of an input of numbers. Also any negative number is the sentinel. The range of numbers that can be entered is 0-9 and maximum of 100 numbers can be entered.
Here's 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 54 55 56 57 58 59 60 61 62
#include <iostream>
using namespace std;
int main()
{
const int max = 100;
int numbers[max] = { 0 };
int frequency[9] = { 0 };
int num;
cout << "Enter a maximum of 100 numbers (from 0-9) and a negative to stop: " ;
for (int i = 1; i < max && numbers[i - 1] >= 0; i++)
{
cin >> numbers[i];
if (numbers[i] == 1)
frequency[0]++;
else if (numbers[i] == 2)
frequency[1]++;
else if (numbers[i] == 3)
frequency[2]++;
else if (numbers[i] == 4)
frequency[3]++;
else if (numbers[i] == 5)
frequency[4]++;
else if (numbers[i] == 6)
frequency[5]++;
else if (numbers[i] == 7)
frequency[6]++;
else if (numbers[i] == 8)
frequency[7]++;
else if (numbers[i] == 9)
frequency[8]++;
else if (numbers[i] > 9)
cout << "Enter a number from 0-9" ;
}
cout << endl;
for (int j = 1; j <= 9; j++)
{
cout << "\n" ;
for (int k = frequency[j]; k >= 1; k--)
{
cout << "* " ;
}
}
return 0;
}
Last edited on May 16, 2015 at 8:40am UTC
Topic archived. No new replies allowed.