C programming supports following conditional statement and operators.
Statement | Description |
if () { } | An if statement consist of a condition statement followed by one or more statement. Statements can be exexuted when condition is true. |
If() { } else { } | An if statement can be followed by an else statement which can be executed when condion is false. |
If (){ } else if () { } … else { } | An if else ladder . this can will execute only that statement whose condition is true otherwise else condition will be executed default. |
Switch () { case .. : … .. } | A switch statement is used to check for equality of variable again set of case values. |
? : | Conditional operator |
Example 1:
1 2 3 4 5 6 7 8 |
#include<stdio.h> int main(){ int a=10; if(a==10){ printf(" a has value as 10 "); } return 0; } |
Output:
a has value as 10
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include<stdio.h> int main(){ int a=10,b=20; if(a==b) { printf(" a and b are equal "); } else { printf(" a and b are not equal "); } return 0; } |
output :
a and b are not equal
Example 3:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include<stdio.h> int main(){ int a=1; if(a==1) printf(" Monday "); else if(a==2) printf(" Tuesday "); else if(a==3) printf(" Wednesday "); else if(a==4) printf(" Thursday "); else if(a==5) printf(" Friday"); else if(a==6) printf(" Saturday "); else if(a==7) printf(" Sunday "); else printf(" Invalid No "); return 0; } |
output :
Monday
Example 4:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include<stdio.h> int main(){ int a=5; switch(a){ case 1: printf(" Monday"); break; case 2: printf(" Tuesday"); break; case 3: printf(" Wednesday"); break; case 4: printf(" Thursday"); break; case 5: printf(" Friday"); break; case 6: printf(" Saturday"); break; case 7: printf(" Sunday"); break: default: printf(" Invalid Key"); } return 0; } |
Output:
Friday
Default statement will be executed then only when no case is matched.