Table of Contents
C programming if else if else statements
first, The if statement evaluates the Boolean Expression inside the parenthesis. when the expression is evaluated to true(1), enter the body part and statements inside the body part of if are executed.
if the test expression is evaluated to false(0), The control is skipped the inside the body of statements from execution and exit from the if part
already we are learned the concept of the relational operator in the operator in C language to about understand boolean expression (test expression)
Syntex for if….. else
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
else {
/* statement(s) will execute if the boolean expression is false */
}
Flow diagram of if statement
/* if(expression) { statement }else{ statement; } */
#include <stdio.h> #include <stdlib.h> int main() int age=20; if(age>=18) { printf("you are a minor"); } else{ printf("you are a adultn"); } return 0; }
When the code is executed, it produces the following result
#include <stdio.h> #include <stdlib.h> int main() { /*local veriable definition*/ int a=17; /*check the boolean condition*/ if(a<20) { /*if condition is true then print the following*/ printf("a is less than 20!n"); } else{ /*if condition is false then print the following*/ printf("a is not less than 20!n"); } printf("value of a is:%dn",a); return 0; }
Syntex for if….. else if ……else
if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */ } else if( boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } else if( boolean_expression 3) { /* Executes when the boolean expression 3 is true */ } else { /* executes when the none of the above condition is true */ }
#include <stdio.h> #include <stdlib.h> int main() { /*local variable definition*/ int a=25; /*local variable definition*/ if(a==10){ /*if condition is true then printing following*/ printf("valeu of a is 10!n"); } else if(a==20) { /*if condition is true then printing following*/ printf("valeu of a is 20!n"); } else if(a==30) { /*if condition is true then printing following*/ printf("valeu of a is 30!n"); } else { /*if condition is false then printing following*/ printf("value is not matching!n"); } printf("Exact value of a is:%d!n",a); return 0; }
When the code is executed, it produces the following result
finally, it will be displayed given number is even or odd
#include <stdio.h> #include <stdlib.h> int main() { int number; printf("Enter an integer:"); scanf("%d",&number); if(number%2==0) { printf("%d is an even integer.",number); } else { printf("%d is an odd integer.",number); } return 0; }
When the code is executed, it produces the following result