if statement

Statements under if executes only, if the given condition is true.

Otherwise those statements will not be part of program.




Syntax

Example

if(condition)
{
    //statements
}


Example

if(0) //always false
{
    //statements will not execute
}


Example

if(non-zero) //always true
{
    //statements will execute
}

Likewise, when we give some expression or logical combination of expression in if statement, the statements under if only work, if the expressions output is non-zero.




Sample Program

Dividing two numbers. We should restrict the execution, if the divisor value is 0.

Example

#include<stdio.h>
int main()
{
    int num1,num2;
 
    scanf("%d%d",&num1,&num2);
 
    // if num2 value not equal to zero, it will become if(1).
    // otherwise it will become if(0)
 
    if(num2 != 0) 
        printf("num1 / num2 = %d\n",num1/num2);
  
    return 0;
}

If we are going to place only one statement under if, then no need for parenthesis.

Example


if(condition)
    only one statement.

if(condition)
{
    //statement 1
    //statement 2
    //statement n
}