Apart from following step-by-step each instruction, using the if statement, a computer can also make decisions and change path under certain conditions.

This program has two possible outputs:

or

One of the biggest computers' potentials is the possibility of changing the behaviour of a program in some conditions.

In the next weeks we're going to see how to do that through cycles. switches and other statements, but today we're examining conditions.

Introduction to conditions

In C there are statements that allow the computer to choose different sets of instructions based on certain conditions.

They are if, else and else if.

This section is an introduction: for deeper explanation read the next chapters. You can use the table of contents above to jump to the one you're interested in.

The overall syntax of these three is:

Notice that // indicates a comment: in a program everything after it on the same line is ignored, but in this example I've used it as a way to better explain the syntax.

In the next parts of this post I may use the word chain: for this I mean a sequence of statements, not separated by external code, that are influenced by each other.

Different chains are not influenced by each other: if Chain 1 contains only an if, Chain 2 can't start with else if anyway. They're independent.

IF

if is the main condition statement.

Its syntax is:

The code is just the code that you want to be executed if the condition is true.

The condition is just a number: 0 for false and 1 for true.

Nevertheless, as for functions' parameters, you can use operations, variables and even other functions as condition.

Furthermore, there are other operators that can be used to compare two values and to perform any logical operation.

Here's a list of them. If you want, you can check the list of the arithmetic operators in the previous post: Learn C Programming: Variables | Step-by-Step Explanation

Operator Syntax Description
== A == B True if A and B are equal
!= A != B True if A and B are different
> A > B True if A is greater than B
A True if A is less than B
>= A >= B True if A is greater than or equal to B
A True if A is less than or equal to B
&& A && B True if A and B are both true
|| A || B True if A or B or both are true
! !A True if A is false

 

 

Example Code for all Logic Operators

 

Read the comments if you can't understand the code above.

Let's see one last example for if:

What do we want to do? 

We want the computer to accept only numbers between 0 and 10.

What does it do?

It checks if the number is NOT between 0 and 10: if it's true it prints an error.

How does it do it?

It checks if the number is less then zero or if it's greater than 10. The equivalent logic expression is num0 || num>10. If one of these two conditions is true the number can't be between 0 and 10.

 

ELSE

If you want a code to be run only when an if's condition is false, or in other words as an alternative to if, you can use else.

As the name suggests, the else statement tells the computer “Hey! If the previous conditions are all false, run this“.

Why have I said conditions (with an s)?

Because the else's code is an alternative not only to an if, but also to all else ifs in the same chain.

The syntax of else is:

Notice that else doesn't contain any conditions:

this is because it's a general alternative to the previous ones. Only if all of them are false, else's code is used. It's just a simple “otherwise“.

An else can only go after an if or an else if, but never after another else. Look at these pictures:

  Else statement Error  Else Statement used well

 

To use else correctly, you must put it after other conditional statements. There can't be any code between the end of the previous one and the else statement itself, but there can be as many spaces or empty lines as you want.

Since I talked so much about else if, let's see what is it.

 

ELSE IF

It's the fusion between if and else: it's an else statement that contains a condition.

It works like else:

  • It requires a previous if;
  • It's considered only if all previous conditions are false;

but:

  • It requires a condition and its code is run only when that condition is true;
  • It can't be after an else;
  • There can be more than one else if in one chain.

Its syntax is:

Here's an example:

How does it work?

As soon as we press the run button, the computer will check if the division between 20 and 3 doesn't have a remainder.

If it's true it will print “20 isn't divisible by 3” and it'll totally ignore else if. However, since we all know (don't you?) that 20/3 has a remainder of 2, the first condition is false, so now the computer will check the second one.

It is true, therefore the sentence “The remainder of 20/3 is 2” will be printed.

If the program was this…

… nothing would have appeared on the command prompt, because all conditions are false.

In this program instead…

… we would have obtained the same result as the first one, because there's an else at the end. In this last version isn't possible that nothing is printed: even if all conditions were (and they are) false, else would be used as final alternative.

How does the computer read them?

Within a chain, the computer goes step-by-step through each statement: if its condition is true, it runs its code and it ignores anything next in the same chain; otherwise it goes to the next statement, until the chain ends or there's an else (that is run when all the previous conditions are false).

Having a look at this map can be helpful to understand the process:

Conditions Flow Chart

This flowchart shows you exactly how the computer ignores or considers other conditional statement inside a chain.

As you can see the latest elements are considered only if the previous ones have false conditions.

The blocks start and end can either being thought as the start and the end of a program or as other pieces of code or chains that are independent from this one.

 

Let's analyse today's program

This program has two possible outputs:

or

This is the program I wrote for today.

I'm not going to explain #include stdio.h>, int main() {, all printfs and all scanfs, because I've explained them in the previous two postsLearn C Programming: Variables | Step-by-Step Explanation and Make Your First C Program (+ Step-by-step explanation).

//This is a comment…

It's a comment as it says.

A comment is a text inside the program source file (the code), that is ignored by the compiler, therefore it won't become part of the final software.

There are two ways to create a comment:

  • Inline comment: if you type //, everything after it on the same line will become a comment;
  • Comment block: everything between /* and */ is a comment. It also works on different lines.

int num;

If you read my previous post, you would know that this is a declaration of a variable without an initialisation.

In other words, we are creating a place to store a value in the computer's memory, but we aren't giving it any initial values.

int means integer and it's the type of the value we want to store.

num is the name of the variable. It can be everything you want and it's used to manage the variable in the code.

The semicolon tells the computer that this instruction is ended.

if(num

We're setting a condition: the code inside { and } will be run only if the condition num is true.

We asked the user to enter a positive number and we assigned that value to a variable called num.

However, the user can type everything they wants, so we have to check if the typed number is positive or negative.

We set a condition to check if num is negative: if so, the code printf("The number you entered is negative :Pn"); will be executed

and the computer will print “The number you entered is negative 😛“.

else {

If the previous condition is false, the computer will go on to the else statement.

As we've just seen, else is run only when all previous conditions in the same chain are false.

So, if num is not negative, so num is false and the code inside if is ignored, the code inside else will be executed.

Pay attention to semicolons

Semicolons are very important in C, but it's a bit hard to explain where you must put them: you'll learn this through experience.

For now let's see some cases.

Put a semicolon after:

  • calling a function: e.g. printf(“something”);
  • declaring a variable: e.g, int variable; or int variable = 0;
  • assigning a new value to a variable: e.g. variable = 20; or variable += 20;

Don't put a semicolon after:

  • including a library: e.g. #include
  • defining (=creating) a function, even if it's main(): e.g. int main { … }
  • if, else, else if: e.g. if(variable>10) {…}

Let's translate the code

Let's give a possible translation of this program in human language:

Computer, this program uses the library stdio.h

The set of instructions starts here

Create a variable of type int called num

Print “Enter a positive number: ” on the command prompt

Read the value entered by the user and assign it to num

Check if num is less than 0

if so, print “The number you entered is negative :P”

Otherwise print the value of num followed by ” is the square root of ” followed by num times num

The end

C and C++ comparison

There's no much to compare:

if, else and else if work the same way, while we've already covered the rest in previous posts.

Tips and Tricks

If your if/else/else if contains only one line you can also omit curly brackets (don't do it for more than one line, it won't work).

Conclusion

Today we've seen an important topic in C programming and you've learnt how to use:

  • if to check if a condition is true;
  • else if to check a different condition when all the previous ones are false;
  • else to run a code only if all previous conditions are false

It was such a small topic, but we covered it in such detail that this post ended up being the longest so far.

I hoped it was all clear in the end. If so, why don't you share this to a friend that wants to learn programming with you?

Otherwise write a comment below and help me to improve this blog telling me what you didn't understand.

Anyway, the post is finished, have a good day and we will see the next week!

Zephyro, over!


Leave a Reply

%d bloggers like this: