Thread: if / else statements

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    11

    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;
    }

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    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.

  3. #3
    Registered User
    Join Date
    Sep 2011
    Posts
    11
    Thanks, Whiteflags. Couldn't have explained it better (:

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. statements in C
    By forumuser in forum C Programming
    Replies: 9
    Last Post: 10-03-2007, 10:57 AM
  2. Which one of these if() statements is best?...
    By MathFan in forum C++ Programming
    Replies: 11
    Last Post: 05-07-2005, 02:19 AM
  3. how to 'and' statements
    By chris285 in forum C++ Programming
    Replies: 11
    Last Post: 04-29-2003, 04:18 PM
  4. IF Statements ?
    By survivor in forum C++ Programming
    Replies: 3
    Last Post: 04-28-2003, 11:32 AM
  5. for statements
    By Lyanette in forum C++ Programming
    Replies: 9
    Last Post: 03-29-2003, 07:15 PM