All about if else statement in C Programming | conditional statements in c

 if-else conditional Statement in C Programming



Here, we will learn if else conditional statements in C programming with examples and we will learn if-elseif-else.

If-else is a basic conditional statement and the use of if-else statement is to check to check whether the given condition is true of false. if it is true then u perform some computation or if it false u perform some other computation.



First lets see the syntax:-

if(expression)
{
    //If the expression is true execute
}

Working:-

If the boolean expression is true is true then then it will execute the body of the if statements. If the expression is false then it won't execute.

Syntax of if-else:-
if(expression)
{
    //If the expression is true execute
}
else
{
    //else executes this statement
}

Working of if-else:-

If the expression is true then it will execute the body of the if statements and if the expression is false then it will execute the body of the else statement.

conditional statements in c
conditional statements in c


Syntax of if-else-if:- 
if(expression1)
{
    //If expression1 is true execute
}
else if(expresiion2)
{
    //if expression2 is true executes this statement
}
else if(expresion3)
{
    //if expression3 is true executes this statement 
}
else if(expresiion4)
{
    //if expression4 is true executes this statement
}
else
{
//if none of the expression is true then execute this
}

Examples:-

1. Using If statements

 In this example first we initialize the value 10 and 20 to the variable a and b respectively and then we are checking that the variable a is equal to 10 or not using if statement and its true then it prints a contains 10.
#include <stdio.h>

int main()
{
    int a=10;
    if(a == 10){
        printf("a contains 10");
    }
    return 0;
}

output:-

a contains 10 

2. Using if else statements

This example is using the if  else statements, first we initialize the variable a with the value of 9 and then checks the condition if a equals 10 if true then prints  a contains 10 otherwise it prints a does not contain 10.
#include <stdio.h>

int main()

{
    int a=9;
    if(a == 10){
        printf("a contains 10");
    }else{
        printf("a does not contain 10");
    }
return 0;

}

output:-

a does not contain 10 

3. Using if-else-if statements

This example is using if else if statements, we first initialize the variable a with the value 10 and checks if its less than 10 if yes it prints a is less than 10, if not then it checks if a is greater than 10 if yes then it prints a is greater than 10 and if both the conditions evaluates to false then it prints a is equal to 10.
#include <stdio.h>

int main()

{
    int a=10;
    if(a < 10){
        printf("a is less than 10");
    }else if(a > 10){
        printf("a is greater than 10");
    }else{
        printf("a is equal to 10");
    }
    return 0;

}

output:-

a is equal to 10 

Post a Comment

0 Comments