What"s a Conditional Statement
What's a Conditional Statement?
In order for a computer program to have any meaningful effect, it must be able to react differently to changing conditions. To do this, a program uses statements that do different things depending on the value of a variable or statement. These statements are called conditional statements. The most simple form of a conditional statement is the if statement. Simply put, an if statement will do one thing if a condition is true and another thing (or nothing) if the condition is false.
"If" Statements
In this example Ruby program, someone wants to see a movie that's rated R. To see the movie, you must be 17 or older. The conditional statement begins with the if statement and the expression age < 17. This is what's called a boolean expression, an expression that will either be true or false. This boolean expression will be true if the value of the age variable is less than 17 and false for all other values greater than or equal to 17. The boolean expression tells the if statement which of the next two statements to execute.
If the boolean expression is true, the first statement would be executed and display the message "I'm sorry, you're not old enough." If the express is false, the second statement would execute and display the message "OK, you're old enough."
Programming Notes
Note that in the program the lines of information or questions following the # symbol are not part of the code, but rather a note to the programmer explaining what's going on. # Read age and convert to a number merely reminds the programmer (or any future programmers) of what will happen with the next line of code.
Similarly, # Should we let you into the movie? is an explanation of what the program's if statement will have to determine in order to print the correct message.
#!/usr/bin/env rubyputs "This movie is rated R," puts "you must be 17 or older to see it." print "How old are you? "# Read age and convert to a number age = gets.chomp.to_i# Should we let you into the movie? if age < 17 puts "I'm sorry, you're not old enough." else puts "OK, you're old enough." end
Excluding Statements
If statements can also exclude the second statement to be executed if the boolean expression is false. More than one statement can also be executed inside the if statement as well. In this example, the program will exit if you're not old enough to get into the movie. Since the statements within the if statement are not executed if the boolean expression is false, the final line which prints the message "OK, you're old enough" will be executed and the program will not exit.
#!/usr/bin/env rubyputs "This movie is rated R," puts "you must be 17 or older to see it." print "How old are you? "# Read age and convert to a number age = gets.chomp.to_i# Should we let you into the movie? if age < 17 puts "I'm sorry, you're not old enough." exit endputs "OK, you're old enough."