Function for this

I have a basic program where you choose a number 0-9 and depending on what you choose you win money..
I know you can put this into an array, but could it be easier to make it into a function. If so how?

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
cin >> selection;

if (selection == 0){
	user_winnings = 100;
}
if (selection == 1){
	user_winnings = 500;
}
if (selection == 2){
	user_winnings = 1000;
}
if (selection == 3){
	user_winnings = 0;
}
if (selection == 4){
	user_winnings = 10000;
}
if (selection == 5){
	user_winnings = 0;
}
if (selection == 6){
	user_winnings = 1000;
}
if (selection == 7){
	user_winnings = 500;
}
if (selection == 8){
	user_winnings = 100;
}
er, just copy/paste that code into a function. =P Maybe return the user_winnings value:

1
2
3
4
5
6
7
8
9
int yourfunction()
{
  int selection;
  int user_winnings;

  // copy/paste the above code

  return selection;
}


But of course, as you said... this would be much better if you use a lookup table (array). I try to avoid long if chains like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int user_winnings[9] = {
  100,
  500,
  1000,
  0,
  10000,
  0,
  1000,
  500,
  100
};

if((selection >= 0) && (selection < 9)) // make sure the user entered a valid selection
  return user_winnings[ selection ];
else
  // do something to indicate the user entered something invalid 


EDIT: fixed function error
Last edited on
er, void yourfunction() isn`t meant to return a value is it?
you're absolutely right, buffbill. Modified original post to correct that.
Topic archived. No new replies allowed.