If and Else Statements | Learning Programming

Mark Bailey
2 min readOct 26, 2020

This series will not focus on any particular programming language, it will mostly be in pseudo code. This will just cover the core concepts; however my first language was java, so it will most likely look very java like.

‘If’ statements

understanding an if statement is very simple. The thought process becomes very natural. if x then do this. ‘if’ statements are normally started with the word ‘if’ and then typically parentheses. Within the parentheses is what you want to test:

if(5 > 3) {

print(“5 is greater than 3”);

}

Here we are testing whether 5 is greater than 3. if this is true than the code within the curly braces is then executed. If this was false then nothing happens. Now what if we wanted to do something else if this fail? Well putting something after the if would make it always execute even if it was true which is not what we want. This is where ‘else’ comes in.

‘else’ statements

‘else’ statements only occur when the first condition wasn’t true. Similarly then will execute only the things within there brackets. Let’s see how this works:

if(3 > 5) {

print(“what kind of math are you doing?”);

} else {

print(“3 is not greater than 5”);

}

Here “3 is not greater than 5” will print because 3>5 is false. It is common practice to put ‘else’ after the ending curly brace of the if statement (if the language has curly braces [looking at you python]). The ‘else’ statement does not get it’s only parentheses because it’s purpose is to only execute the code if the ‘if’ statement was false.

‘else if’ statements

‘else if’ statements are just chained together if statements. however once one is executed none of the others are checked. Let’s see how this works:

if(5 > 3) {

print(“5 is greater than 3”);

} else if(2 > 1) {

print(“I will never get to run :(”);

} else {

print(“5 is not greater than 3”);

}

Here we use an ‘else if’ as you can see it also has parentheses because it checks it’s own condition; however in this example our ‘else if’ will never run as the first if statement is true and once the code inside those curly braces is executed the computer will start reading right after the closing curly brace of the ‘else’ statement.

You can also chain as many ‘else if’s as you want into an ‘else if’ chain. Just make sure that if you have an ‘else’ statement it is always last and the ‘if’ statement is always first.

--

--