### Problem with an "else" statement

Total rookie here. I did the Cola Machine exercise and without the "else" statement it works fine but I wanted to add a response for incorrect inputs.

So with what you see below it works if you select 5 or any number above 5 but selecting 1-4 will give the soda choice string as well as my bad selection string. So I tried putting the "else" after each "if" but that didn't work.

Heh, I was about to ask if I need to if (answer >= 6) tried it real quick and it works fine. Is that the optimal way to do it? is it possible with an "else"? I thought "else" would be ideal because it would cover anything someone input other than 1-5.

Now to go read about switches and make it work with that

I'm open to any constructive criticism to help me learn. I'm having a lot of fun with it and looking forward to seeing what I can build for fun.

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243`` ``````#include using namespace std; int main() { int answer; cout << "Please make your selection: \n"; cout << "For Coke press 1 \n"; cout << "For Mnt Dew press 2 \n"; cout << "For Dr Pepper press 3 \n"; cout << "For Redbull press 4 \n"; cout << "For Water press 5"; cout << endl; cin >> answer; if (answer == 1) { cout << "You've selected Coke. Enjoy! \n"; } if (answer == 2) { cout << "You've selected Mountain Dew. DO THE DEW! \n"; } if (answer == 3) { cout << "You've selected Dr Pepper. Drink It Slow, Dr's Orders. \n"; } if (answer == 4) { cout << "You've selected Redbull. Redbull gives you wings! \n"; } if (answer == 5) { cout << "You've selected water. Good choice. \n"; } else { cout << "You've failed to follow directions. Maybe im not the machine for you."; } return 0; }``````
 ``1234567891011121314151617181920`` ``````if(answer==1) { //enter your code } else if (answer==2) { //code } else if(answer==3) { //your code } else if(answer==5) { //code } else { //code }``````

EDIT:
I posted the same code twice, so I had to remove the post.
Last edited on
Thank you. So if I wasn't going to do the "else" at the end is it wrong to use all "if" statements the way I did, should it always be
if
else if
else if
?
No, it isn't wrong. It depends on how small your project is, you may decide to use if statement for everything or you may choose the method I wrote above. They are both "legal".
Understood, thanks!
Topic archived. No new replies allowed.