Fundamentals of Programming: Part 6 – Conditions

by
Inf

Welcome again! In this series, we go on to the first of the essential building blocks of programming: conditions. This is the first part of the series that starts to deal with blocks of code, as opposed to just independent lines. So without delay, let’s start.

In this long series, we’ll cover condition blocks using if-else and if-else if-else. We cover checks using AND, or and NOT (! symbol). We finally end with the switch statement. I doubt you’ll be able to grasp everything in one go as a beginner, so go slow, maybe a section at a time, try to understand how it works before moving on.

What are conditions?

It happens that you need your program to take decisions based on checks and conditions. That is, you want your program to perform a set of actions in case A, but perform another set of actions in case B. That’s where conditions come in. It allows you to implement decision points in your programs.

Associated with a condition is a check. Usually, you will be checking what the value of a variable is. Then based on this value, you will branch out and do different things.

Conditions start with the keyword if, followed by a check. There may be another section, called else which gets executed if the condition check turns out to be false. Within these two sections, there can be other conditions too. These are called nested conditions.

Let’s see a blank, simple condition block:

if (condition){
	do this
}
else{
	do that
}

This is perhaps, your first serious encounter with a block of code, so let’s devote some time to how it is structured.

First notice the { and } braces. These indicate where a block starts and ends. I.e. they tell which statements are part of which blocks. Think of those as boundaries. Everything within the first set of { } is for the if-block and everything in the second { } is for the else-block. Not all languages use braces to separate blocks like these; Python for e.g. uses indentation to indicate blocks. So you just indent lines under an if and these lines are considered under the control of the if-block. Other languages use keywords, such as  “end if”. It’s all programming-language dependent, so when programming, you will use the method your language imposes.

Just for clarity, here is this same example, but in those different ways I just mentioned:


if (condition):
	do this
else:
	do that
	

if (condition)
	do this
else
	do that
end if

So that’s structure. Let’s focus on the if line: if (condition). The condition is the check which will determine which block gets executed. You will normally decide what to do based on a variables’ values. This is an actual example:


if (x > 0){
	output "X is positive"
}
else (x < 0){
	output "X is negative"
}

Here, we want to check if x is positive or negative, and tell the user what it is. Let’s consider three cases:

  • x is 2: The if statement’s condition will see what value x has. It sees 2. Is 2 greater than 0? True, so we go into the if-block and execute the output line. The user sees “X is positive”. After executing that, we DO NOT execute the else part. The else-block is only executed if the condition was not matched. So after outputting the line, we finish.
  • x is -1: The if statement’s condition checks the value of x. It sees -1. Is -1 greater than 0? False. We skip over to the else part since we didn’t get a match. The if-block is NOT executed. We go inside the else-block and execute the output line. The user sees “X is negative”. After this, we finish.
  • x is 0: The if statement’s condition is checked. Is 0 > 0? False! (It’s not greater! It’s greater or equal, but we’re only checking greater here). Since the if-block condition failed, we go to the else part and output “X is negative”. That’s probably not what we wanted. Did we really want to tell the user that zero is negative? (Oh by the way, in computing, you can have positive-zero and negative-zero!)

You can see that we’re missing a condition here, for the case where x is zero. There are multiple ways to do that, one is not available in all languages. Let’s see 3 ways:

First:


if (x > 0){
	output "X is positive"
}

if (x < 0){
	output "X is negative"
}

if (x == 0){
	output "X is zero"
}

This works, but normally, you don’t want to do that because it increases the number of lines of code unnecessarily. Programmers like compact code and you may get a few stares if you do that while working as a programmer. Do note that you can have if-blocks on their own too. You don’t always need an else-part.

Second, nested blocks or if-ception if you want. If inside if:


if (x > 0){
	output "X is positive"
}
else{
	
	if (x < 0){
		output "X is negative"
	}
	else{
		output "X is zero"
	}
	
}

Can you understand what we did here? We check if x is positive. If it is not, we do the else-block. In there, we find another condition check, so we again check the if part. This time, is x negative? If not, we do the else. Well, if the number is not positive (first if) and not negative (first if in else-block), we guess that it has to be zero (else in else-block).

Third, else if:


if (x > 0){
	output "X is positive"
}
else if (x < 0){
	output "X is negative"
}
else{
	output "X is zero"
}

This way is similar to the nested-block one (second) but it’s just shorter to write. Programmers like shorter-to-write. It just has an “else if” keyword which is additional condition checks if the first if fails. So here, we check the first if to see if X is positive. Nope? Check the second if (else if). Is x negative? Nope. We go to the else block then and output “X is zero”.

There is a short way for checking the values of booleans:


if (isSunny)
	go out
else
	stay indoors

isSunny is a boolean variable. For boolean variables. you don’t need to write if (isSunny == true) or if (isSunny == false). You just write if (isSunny) and it’s sufficient to get the condition block working. It’s just a short, recommended way to check for boolean variables’ values.

Oh to check if it’s false? if (!isSunny). ! operator reverses the value, so true becomes false, false becomes true. This check is frankly, weird but heavily used once you understand it. Prepare for weirdness!

Two cases happen. We want to execute the if statements only if isSunny is TRUE!

For simplicity, read !isSunny as NOT-is-sunny or is-NOT-sunny if you wish.

  • isSunny is true: So if (!isSunny) will reverse the value, hence we get if (false). The if-block is skipped.
  • isSunny is false: if (!isSunny) will flip the value again, and we get if (true) this time. The if-block is now executed. That’s what we wanted. Execute only when the boolean is false.

Did you notice the lack of { and } in this example? It’s not a mistake. If your condition blocks if and else have only a single line within, you can leave out the brackets, again for making programs shorter. Personally, I just put them in, single-line or not. Just makes things clearer for me. But what you do is your decision! 😀

Multiple condition checks

What happens if you want to check for multiple conditions at once before deciding whether to go into a block? For that, there is AND and OR operators. They are usually represented using symbols && for AND and || for OR. Those are two ampersands and two “pipe” symbols. Look for it on your keyboard. It’s usually to the left of “Enter” or the Z key.

Quick recap: For AND, all conditions must be true for the whole check to be true. If any condition fails, we have false. For OR, at least one condition has to be true for the whole check to be true.

Here you have 2 examples:


if ( isSunny && (day == "Saturday") ){
	go out
	buy groceries
	meet friends
}
else{
	stay indoors
}

The if-condition now has the && (AND) symbol, so we’re checking for 2 conditions here. First, isSunny has to be true AND it has to be saturday. If it’s not sunny or it’s not saturday, we go to else. If it’s both sunny and saturday, then we go to the if-block.

You will also notice that the different conditions can be put in their own brackets. These brackets help with ordering which operations are performed first. You’ve seen that at work in the previous post. The second example shows this:

if ( isFree || (day == "Saturday" && isSunny) ){
	go out
	buy groceries
	meet friends
}
else{
	stay indoors
}

Here we see the OR and AND both at work. Due to brackets being used, we consider the second check as a compound check. So if I’m free OR if it’s both saturday AND it’s sunny, then I go out, buy groceries and meet friends.

If isFree alone is true, it’s sufficient to do the if-block i.e. go out. But if I’m not free, the second part has to be true. Thus if I’m not free, but it’s both saturday AND sunny, then I go out.

Those AND and OR conditions take some getting used to, so don’t worry too much if you don’t completely understand them here. You will, with practice.

To summarize:

Conditions allow you to take decisions in your programs. You will check values of variables and if these are true or false, you take different actions. There are multiple ways to write conditional blocks and the one you choose depends on the programming language you’re writing in. You can have if checks nested in other if or else blocks for extended checks or you can use else if constructs if the language supports it. If you want to check for multiple conditions, use AND and OR.

Just before we end, what happens if you have lots of checks to perform. Well, you can use lots of if-blocks and face the anger of other programmers! Or you can use the switch statement, also known as the select statement.

Switch statement

The switch statement (or select statement) is really language-dependent. Some languages allow you to do comparisons, others just pure equality. Others vary the way the blocks are ordered. It’s just varied. Java for example, has only introduced switch equality checks for strings recently (Java 7) 15 years after the feature was requested. I’ll stick to one language-independent version here just to illustrate how it works. This one only supports equality check on numbers.

Here goes:

switch (dayOfWeek){

	case 1:
		output "Monday"
		break
	case 2:
		output "Tuesday"
		break
	case 3:
		output "Wednesday"
		break
	case 4:
		output "Thursday"
		break
	case 5:
		output "Friday"
		break
	case 6:
		output "Saturday"
		break
	case 7:
		output "Sunday"
		break
	default:
		output "Wrong day!"
		break
}

Ooooh that was long! Basically, we tell the switch statement which variable we want to examine, so here “dayOfWeek”. The various “case” lines represent possible values for the dayOfWeek variable.

Notice, it only supports equality checks! You can’t for example check if dayOfWeek > 6 in the switch statement!

So we check the value of dayOfWeek. Then jump to the appropriate “case” line and execute its statements. Say dayOfWeek is 3. We check case 1, which is equivalent to if (dayOfWeek == 1). Nope. Case 2, if (dayOfWeek == 2). Nope. Case 3, if (dayOfWeek == 3)? Yes. We then go into it and execute output “Wednesday”. Then break? What is break?!

“break” is a keyword you will use in the future series on looping. It tells your program to “break out” of the block it’s currently in. Hence, when we hit the “break” statement, we go directly to the closing bracket and we finish.

That “break” keyword in all those case statements is critically important. If you don’t have them, you will “fall through” the other case statements and execute everything, irrespective of the cases’ values being checked, until a “break” is encountered. I.e. you may get unexpected results! Try it for fun and see someday.

You can use that as “feature” too if you wish:

switch (x){

	case 0:
		do something
	case 1:
	case 2:
	case 3:
		do that too
		break
	case 5:
		do other
		break
	default:
		do something else
		break
}

In this case, if a zero is encountered, the switch statement will “do something”. Since there is no break, it’ll also “fall through” 1,2,3 and “do that too” and finally break. This could be useful in situations where you want zero to execute one statement in addition to what 1,2,3 normally do. Maybe zero is a slightly special case or something.

If either 1, 2 or 3 is encountered, they all lead to “do that too” and break”. I.e. 1,2,3 are the same thing and lead to the same action being performed.

Finally “default” represents a case where nothing was matched. Think of it as a last-resort case that’s useful to handle errors like invalid inputs from users.

Phew! That was a long part, eh! You now know how to make your program take decisions! I recommend that you re-read this part if you don’t understand it at one go. It’s quite a mouthful to chew at once. I hope you got something out of it. As usual, post your questions and suggestions in the comment section, and see you in the next part.

Note: Technically, you don’t compare strings’ values directly like day == “Saturday”. You would use a function or method such as equals(), like day.equals(“Saturday”). I left those out for simplicity here as these come in a future part. Also, I tried to keep using pseudo-code here, so there are no semi-colons on statements. Just so you know! 😀

[seriesposts title=”In the same series:” titletag=”h3″ listtype=ul show_date=0]