In: Computer Science
Analysis and Discussion about if, if else, else if statement and Switch C programming write on your computer font
IF Statement
If statement is always used with a condition. The condition is evaluated first before executing any statement inside the body of If. The syntax for if statement is as follows:
if (condition) statements;
Example Program #include<stdio.h> int main() { int n=1; int m=2; if(n<m) //test-condition { printf("n is smaller than m"); } return 0; }
Output
n is smaller than m
IF Else Statement
Syntax is as follows.
if (test-expression) { True block of statements } Else { False block of statements } Statements;
If test-expression is true, if block is executed. Otherwise else block is executed.
Example Program
#include<stdio.h>
int main()
{ int n=1;
int m=2;
if(n<m) //test-condition
{
printf("n is smaller than m");
}
else
{
printf("m is smaller than n");
}
return 0;
}
Output
n is smaller than m
IF ELSE IF Statement
The syntax is as follows.
if (test - expression 1) { statement1; } else if (test - expression 2) { Statement2; } else if (test - expression 3) { Statement3; } else if (test - expression n) { Statement n; } else { default; }
The test-expressions are evaluated from top to bottom. Whenever a true test-expression if found, statement associated with it is executed. When all the n test-expressions becomes false, then the default else statement is executed.
Example Program
#include<stdio.h> int main() { int marks=40; if(marks>75){ printf("First class"); } else if(marks>65){ printf("Second class"); } else if(marks>55){ printf("Third class"); } else{ printf("Failed"); } return 0; }
Output
Failed
Switch Statement
The switch statement in C is an alternate to if-else-if statement which allows us to execute multiple operations for the different possible values of a single variable called switch variable.
Syntax is as follows.
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Example Program
#include<stdio.h>
int main(){
int number=40;
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
Output
number is not equal to 10, 50 or 100
Since number is 40 and does not match with any case of the switch statement, the default value of the case will be printed.