If – else Statement in C Language

 

If – else Statement in C Language


else is the optional statement followed by if statement which is executed when test condition is false. In C language if else statement is used for decision making purpose. If the test condition is true then the code inside the if block is executed, otherwise code inside the else block is executed.

Syntax of if else statement:

if (test condition)

{

// statement to be executed if test condition result is true

}

else

{

//statement to be executed if test condition result is false

}


if test condition becomes true then statements written in if block get executed but if test condition result is false then statements in if block is skipped and the statements written in else block is executed.

Following example shows the demonstration of if else statement to find number is greater or not.

int a=20;

intb=10;

if(a>b)

{

printf(“%d is greater\n”,a)

}

else

{

printf(“%d is is smaller\n”,a);

}

In above example the values of a and b are assigned with assignment operator 20 and 10 respectively. Variable a is compare with variable b with comparison operator greater than. If test condition becomes true then if block statement will execute otherwise statement in else block will execute. As the a value is 20. So condition becomes true and the statement in if block is executed.

Click below to see the flowchart for if else statement

👉👉👉if else statement flowchart


C program to compare two variables and then make decision which number is greater or smaller.


/*****************************************
C program to check which number is greater or smaller
************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5;
int b=10;
printf("\t\t***Output***\n");
if(a>b)
{
printf("The value of a i.e., %d is greater\n",a);

}
else
{
printf("The value of a i.e.,%d is smaller\n",a);
}
printf("End of program");
}


***Output***

The value of a i.e.,5 is smaller

End of program



In above program the value of a is 5 and value of b is 10. The test condition is given to compare a is greater or not. 5 is smaller than 10 so given condition becomes false. So else block and the statement written in else block is executed.



C program to check which number is greater or smaller. Take user input

/*****************************************
C program to check which number is greater or smaller. Take user input
************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("\t\t***Output***\n");
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
if(a>b)
{
printf("The value of a i.e., %d is greater\n",a);

}
else
{
printf("The value of a i.e.,%d is smaller\n",a);
}
printf("End of program");
}


***Output***

Enter two numbers

90

80

The value of a i.e., 90 is greater

End of program



टिप्पणी पोस्ट करा

0 टिप्पण्या