-
if / else statements
Say I have a program that has 5 different options which are displayed depending on what number you press, and im using if else statements.
"press 1 for my age, press 2 for my height, press 3 for my weight, press 4 for my hair color, and press 5 for my favorate food"
would it be improper/sloppy to write the program out like this:
Code:
#include<iostream>
using namespace std;
int main()
{
double x;
cout << "Press 1 - 5 for a random fact about me\n";
cin >> x;
if(x == 1)
{ cout << "I am 18 years old\n"; }
if(x == 2)
{ cout << "My height is 6 ft.\n"; }
if(x == 3)
{ cout << "My weight is 195 lbs\n"; }
if(x == 4)
{ cout << " I have brown hair\n"; }
if(x == 5)
{ cout << " My favorate food is icecream\n"; }
system("pause");
return 0;
}
-
If I enter 1, this program will output the age and then check every other possibility, returning false.
With a different program, say:
Code:
if(x == 1)
{ cout << "I am 18 years old\n"; }
else if(x == 2)
{ cout << "My height is 6 ft.\n"; }
else if(x == 3)
{ cout << "My weight is 195 lbs\n"; }
else if(x == 4)
{ cout << " I have brown hair\n"; }
else if(x == 5)
{ cout << " My favorate food is icecream\n"; }
This checks every possibility starting from the top, as long as the condition has been false so far. Therefore if I enter 1, the program outputs the age, and doesn't have to do any more logic.
It really depends on what you want. Sometimes, you do want to check every possibility anyway.
-
Thanks, Whiteflags. Couldn't have explained it better (: