The if-else statement in C is used to perform the operations based on some specific condition. The operations specified in if block are executed if and only if the given condition is true.
There are the following variants of if statement in C language.
If statement
An if statement consists of a Boolean expression followed by one or more statements
Syntax:-
if(expression){
//code to be executed
}
Exercises:-
- Write a C program to find maximum between two numbers.
- Write a C program to check whether a number is negative, positive or zero.
If-else Statement
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition.
Syntax:-
if(expression){
//code to be executed if condition is true
}else{
//code to be executed if condition is false
}
Exercises:-
- Write a C program to check whether a number is divisible by 5 and 11 or not.
- Write a C program to check whether a number is even or odd.
- Write a C program to check whether a year is leap year or not.
If else-if ladder Statement
In if-else-if ladder statement, if a condition is true then the statements defined in the if block will be executed, otherwise if some other condition is true then the statements defined in the else-if block will be executed, at the last if none of the condition is true then the statements defined in the else block will be executed.
Syntax:-
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Exercises:-
- Write a C program to input any character and check whether it is alphabet, digit or special character.
- Write a C program to check whether the triangle is equilateral, isosceles or scalene triangle.
- Write a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and Computer. Calculate percentage and grade according to following:
- Write a C program to input electricity unit charges and calculate total electricity bill according to the given condition:
Comments
Post a Comment