Hello. In this tutorial you will learn about the if, else and else if statements.
When are these statements used?
The if statement is used to check if certain conditions are true. For example, just like we would say in English, if the time of day is noon we should eat lunch, else we shouldn't.
So, what is else if?
Since the if statement is used to check if certain conditions are true and else is for the opposite, what else do we need? To be able to check multiple times if certain conditions are true, but not the same. Makes sense? Here's an (English) example:
If the time of day is noon we should eat lunch, else if the time of day is between 8am and 11am we should eat breakfast.
What's that? You don't eat breakfast at 11am? Neither to do I... It was an example.. ok?!
What is the syntax used in the statements?
We will need to use Equality and Relational Operators to check if our conditions are true. There are a few types of these but I will save those for the next tutorial and just teach you the basic and most commonly used one for now.
The most commonly used and most basic Equality and Relational Operator is the sign which checks if two variables are the same. This operator is used as "==" (without quotes, two (2) equal signs).
If, Else and ElseIf Example:
The below example has an if statement, followed by and if, else statement and ends with an if, else and else if statement.
If the conditions checked are true, it will run the code block directly encased with the braces following the statement conditions...
The above script sets a "time" int variable to 9 then checks whether it should output "Noon!" if the time is 12, "Breakfast!" if the time is 9 or "Snack!" if the time is NOT 9 or 12.
Of course, it outputs 9. Try it yourself and change the time value between running the program.
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.