if statement
In a real life example, a person performs different task in different situations. Same in the programming world, we have to execute some code lines in specific coditions. This is possible in C language if we use the if statements. If statement is used to control the flow of program based on some conditions. The block of codes specified in the if block are executed, if the expression is evaluated to true. Otherwise, it will get skipped.
According to the requirements, there are four ways to use of if-statement.
- if statement
- if-else statement
- if else-if ladder
- nested if
Before execution of if block codes, it checks the given condition. On the basis of given condition the controller takes decision that what operation is to be performed. Here is the syntax of if-statement.
{
// codes to be executed
.....
.....
}
Let's see a simple program to find weather an integer is positive or negative.
16
Sorry! you are not eligible
25
Congrats! you are eligible
if-else statement
The if-else statement is the next version of if statement. It is used in the program when we have two conditions. In the if-else statement, the block code is defined in the if block are executed, if the condition is evaluated to true. Otherwise, it will execute the codes defined in the else block. This concept provides an optional feature in the program.
Let's see the syntax of if-else statement.
{
/*if block codes
to be executed*/
}
else
{
/*else block codes
to be executed*/
}
Here, we are using a program to check whether an integer is positive or negative.
-5
-5 is negative integer.
8
8 is positive integer.