C if-else Statement

Every coin has two faces and this is also true for our problems. Till now we have learnt about if statement in which we can execute a set of statements by giving some condition or expression.But most of time we need to execute one set of statements if the condition is true, and an entirely different set of statements if the condition is false. This task can be accomplished easily in C language by using if-else statement.

 

Syntax of if-else statement

if(condition)
{
Statement 1
Statement 2 and so on
}
else
{
Statement 1
Statement 2 and so on
}

 

C if-else Statement Flowchart
if-else Statement Flowchart – Source

 

Few points about if-else block

  • The statements inside if keyword is collectively called if block.
  • The statements inside else keyword is collectively called else block.
  • The parenthesis inside if-else block can be dropped, if there is only one statement in it. As the default scope of these keywords is only one statement.
  • No condition is used with else keyword. The statements under else will be executed only if the condition with if statement is turn out false. So it is treated as default choice.

The best way to understand a topic is through a program. Let’s make one program using if-else statement.

 

Program to check a negative number

 

Output

Output

Explanation

Statements in beginning are self-explainable. I hope till now you are also familiar with them.

  • The main logic of the program lies inside if-else block. In the if block i have written a condition which is checking, if the number is negative. If it turns out to be true then the message “Number is negative” is printed, otherwise compiler will skip this block.
  • In the next else block I have written only one printf() function which will print the message “Number is positive”.
  • Checkout I have written no condition with else keyword. As I said earlier else block is used as the default block.
  • In our test run I have entered the number 7 which is positive. So after taking the input, compiler checked the condition. It turns out false so it executed the statements under else block.

Leave a Comment

Your email address will not be published. Required fields are marked *