Better way? ...again ;)

Fee per person based on number of people.
1-4 $100 per
5-10 $80 per
11 <= $60 per

Just wondering if there is a more efficient way to do this. Would it be better to put the 'cout << "Invalid number of people";' in the if statement? Or leaving it in the switch statement good practice?

Thanks again!!!

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
// Ch6Ex13.cpp - Display the amount a company 
// owes for a seminar based on number of people registered
// Created by  12 Sept 2012

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	// Declare variables
	int numPeople			= 0;
	int caseNum				= 0;
	double amtOwed			= 0.0;
	
	// Enter Input
	cout << "Number Registered: ";
	cin >> numPeople;
	
	// Determind valid number of people
	if (numPeople >= 1 && numPeople <= 4)
	{
		caseNum = 1;
	}
	else if (numPeople >= 5 && numPeople <= 10)
	{
		caseNum = 2;
	}
	else if (numPeople >= 11)
	{
		caseNum = 3;
	}	
	//end if

	// Determine Amount Owed
	switch(caseNum)
	{
		case 1:
			amtOwed = numPeople * 100;
			cout << fixed << setprecision(2);
			cout << "Amount Owed: $" << amtOwed;
			break;
		case 2:
			amtOwed = numPeople * 80;
			cout << fixed << setprecision(2);
			cout << "Amount Owed: $" << amtOwed;
			break;
		case 3:
			amtOwed = numPeople * 60;
			cout << fixed << setprecision(2);
			cout << "Amount Owed: $" << amtOwed;
			break;
		default:
			cout << "Invalid Number of People.";
			break;
	}	// End Switch

	cout << endl;
	//system("pause")
	return 0;
}	// End of main function 
Leaving it in the switch statement is the best because it makes the work easier and also makes the code look simple.
You can declare a double array caseRates[3] to hold the rate for each case.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
double caseRates[3] = {100, 80, 60};

...

if (caseNum > 0 && caseNum <= 3)
{
    amtOwed = numPeople * caseRates[caseNum - 1];
    cout << fixed << setprecision(2);
    cout << "Amount Owed: $" << amtOwed;
}
else
{
    cout << "Invalid Number of People.";
}
Appreciate the responses. I'm not that far into C++, don't really know about double arrays.

why [caseNum - 1]? Why is there a subtraction?

Again thanks for the responses. I won't be using double array due it being a school assignment, but still interested on how it works.
Last edited on
caseRates maps caseNum to the appropriate caseRate. (1->100, 2->80, 3->60)

Because caseRates hold maximum 3 values, index 0,1,2, so if you want to use caseRates[caseNum - 1], first you have to check if (caseNum-1) is in range [0,2], which means caseNum is in range [1,3].

Last edited on
I see, thanks!! Appreciate it.
Topic archived. No new replies allowed.