All topics
5

Making choices: if / else

Free

1. The problem

You are leaving the house and look outside. If it is raining, you take an umbrella. If not, you leave it at home. Same you, same door. What you do depends on the one thing you checked first.

Programs make choices like this all the time. Without them, a program would always do the same thing.

2. Condition, then a branch

An if checks a question with a yes or no answer. When the answer is yes, one set of steps runs. The else part is optional. It runs when the answer is no.

is it raining? yes / no yes no take umbrella leave it

In words: "if raining: take umbrella. else: leave it at home." Exactly one branch runs, never both.

3. Only one path runs

The condition picks one path. Sometimes there are several cases: "if red… else if yellow… else…". Then the computer checks them top to bottom. It runs the first case whose condition is true and skips the rest.

So the order of the checks can change the answer. Put the narrowest checks first. For example, the check "bigger than 100" has to come before the check "bigger than 10". Otherwise the number 500 already passes the first check, "bigger than 10", and never reaches "bigger than 100".

4. Your turn (no code)

A rule: "if the number is bigger than 10, say BIG; else say small." What does it say for 10? For 11?

For 10 it says small, because 10 equals 10 and is not bigger. For 11 it says BIG. The boundary (exactly 10) is where bugs hide. "Bigger than" and "bigger than or equal to" are two different rules. They are easy to mix up, and that is one of the most common mistakes in programming.

5. Takeaway

An if/else checks a condition and runs one branch. A loop repeats a step many times, and an if/else chooses what to do. These are the two main parts of almost every algorithm, and you already have both. Next you will put them together in real code.

On LeetCode

No code yet, so nothing to submit. A choice like this decides problems such as Kids With the Greatest Number of Candies, which you can solve right after lesson 7 puts a loop and an if together.

Reading as a guest

Every free lesson is open to read and run. A free account marks lessons done and shows where you are in the course.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy