Thursday, 10 October 2013

Conditional Statements are those which execute different blocks of code depending upon whether a Boolean expression provided by the programmer evaluates to a true condition or a false one. In this article, we will learn Conditional Statements, its different types, their syntax and example of each of them. We have already seen these statements in some of our previous articles on Basic Linux Shell Scripting Language. So, most of the part of this article is self explanatory.

Here we go!

Types of Conditional Statements

Simple If Statement

'If-else' Statement

'If-elif-else' Statement

'Nested If' Statement

1. Simple 'If' Statement

In simple 'if statements', the block of code is executed if and only if the condition evaluates to 'true'. Otherwise, the block of code is skipped.

2. 'If - else' Statement

In 'if-else statements', if the condition evaluates to 'true', the block of commands under 'if-then', i.e. 'Block of Commands 1', is executed while 'Block of Commands 2' is skipped. Otherwise, 'Block of Commands 1' is skipped and block of code under 'else', i.e. 'Block of Commands 2', is executed.

Enter a Natural Number :
7
Its Odd!
Enter a Natural Number :
12
Its Even!

3. 'If - elif - else' Statement

In case of 'if-elif-else' statements, 'condition 1' is checked and if 'true', 'Block of Commands 1' is executed. If condition 1 evaluates to be false, then condition 2 in 'elif' is checked, if it evaluates to be 'true', then 'Block of Commands 2' is executed. If both the conditions are evaluated to be 'false', then program jumps to the 'else' part and executes 'Block of Commands 3'.