C if else Statement
The if statement in C language is used to perform operation on the basis of condition. By using if-else statement, you can perform operation either condition is true or false.There are many ways to use if statement in C language:
- If statement
- If-else statement
- If else-if ladder
- Nested if
If Statement
The single if statement in C language is used to execute the code if condition is true. The syntax of if statement is given below:- if(expression){
- //code to be executed
- }
If-else Statement
The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:- if(expression){
- //code to be executed if condition is true
- }else{
- //code to be executed if condition is false
- }
If else-if ladder Statement
The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:- 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
- }
C Switch Statement
The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.The syntax of switch statement in c language is given below:
- 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;
- }
Rules for switch statement in C language
1) The switch expression must be of integer or character type.2) The case value must be integer or character constant.
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.
Let's try to understand it by the examples. We are assuming there are following variables.
- int x,y,z;
- char a,b;
- float f;
| Valid Switch | Invalid Switch | Valid Case | Invalid Case |
|---|---|---|---|
| switch(x) | switch(f) | case 3; | case 2.5; |
| switch(x>y) | switch(x+2.5) | case 'a'; | case x; |
| switch(a+b-2) | case 1+2; | case x+2; | |
| switch(func(x,y)) | case 'x'>'y'; | case 1,2,3; |
Source : javatpoind.com