if else in C program

We can use decision making statement if else inside our c code. For this we will start with some simple if else statement and write complex programs in our c language.
If( test expression ) 
Statement block if TRUE
If( test expression ) 
{
Statement block if condition TRUE
}else{
Statement block if condition  False 	
}

Nested if else

Similarly we can add else part to our if condition so if the test expression fails then this part gets executed. We will start with an example. We will ask users to enter one digit , then we will check if it is greater than 10 or not. But to display a message if the condition checking fails we have to use one else block also. Here is the code.
#include <stdio.h>
int main(void){
int num1;
	printf("Enter the  number ");
scanf("%d",&num1);  // Enter  numbers
if(num1 <= 10)
{
printf(" Your number is less than or equal to ten");
}
else
{
printf(" Your number is more than ten"); // printng outputs
 }
return 0;
}

Example of nested if else

Enter number up to 100 and check the division. Here we have used multiple if else conditions to arrive at deciding the division of the student.
The sequence of checking starts from highest division to lowest division.

If mark is equal to or more than 80 then first division
If mark is equal to or more than 60 then second division
If mark is equal to or more than 40 then third division
If mark is NOT equal to or more than 40 then fail.
#include <stdio.h>
int main(void){
int num;
	printf("Enter a number less then or equal to 100 :  ");
	scanf("%d",&num);
	
	if(num >= 80)
        printf(" First Division  " );
	else {
		if(num>= 60){
		printf(" Second Division ");
		}else{
		  if( num>=40){
		  printf(" Third Division ");
		  }else{
		  printf(" Fail ");
		  }
		}
	}
return 0;
}

Using else if

if(expression is true){
 // statement to execute	
}
else if ( expression is true){
 // statement to execute	
}else if ( expression is true){
 // statement to execute	
}
else {
// final statement to execute if nothing is ture	
}
Example
int main()
{
int x=20;

if(x>=30){
  printf(" I am greater than or equal to 30  \n");
}else if(x<20){
  printf(" I am less than 20 \n");
}else 
  printf("I am greate than or equal to 20  but less than 30 \n");
}
Check the grade of the student by using else if condition Highest of three user input numbers Different tariff plan for different range of consumption (Example of if else )

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    18-08-2023

    Write an if-else statement to check if the grade is above or equal to 60

    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer