Help with arrays

Hello all. I need help with a classwork assignment. The original task I have to do is use a single-dimensional array and print a bar chart (using asterisks) for these ages: 14-17, 18-20, 19-21, 22-24, 25-27, 28-30, 31-33, 34-36, 37-39, 40-100. These are the students in each age range: 1, 2 , 4, 8, 20,8,7,4,3,1. The code I've modified comes from a very similar example of the c++ deitel book fig. 7.9 (in case anyone had it). I'm very new to c++ still and it's hard to try and pull things we've gone over and apply them here. Any help is welcome thanks in advance.

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
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;

int main()
{
	const size_t arraySize = 10;
	array < unsigned int , arraySize > n = 
        { 1, 2, 4, 8, 20, 8, 7, 4, 3, 1 };

	cout << "Age Range: " << endl;

	for ( size_t i = 0; i < n.size(); ++i )
	{
		if ( 0 == i )
			cout << "14-17: ";
		else if ( 10 == i )
			cout << "40-100: ";
		else
			cout << i * 18 << "-" << (i * 18) + 3 << ": ";
	for ( unsigned int stars = 0; stars < n[i]; ++stars )
		cout << '*';
		cout << endl;
	}
}

You need a "18-20" as well. The calculation in line 21 is wrong. Need a (i-2) in there. Line 18 should be if (9 == i).

But you could replace the if (..) else if (..) else sequence with a switch() statement with a case for every age range. Much simpler, less likely to make a mistake, easier to modify, easier to read.
See:
http://www.cplusplus.com/doc/tutorial/control/
for something like:
1
2
3
4
5
6
7
switch {
  case 0: cout << "14-17; break;
  case 1: cout << "18-20; break;
  ...
  case 9: ....
  default: ...
}
Last edited on
Topic archived. No new replies allowed.