if statement is a basic control flow structure of C programming language. if statement is used when a unit of code need to be executed by a condition true or false. If the condition is true, the code in if block will execute otherwise it does nothing. The if statement syntax is simple as follows:
1 | if (condition){ |
2 | /* unit of code to be executed */ |
3 | } |
C programming language forces condition must be a boolean expression or value. if statement has it own scope which defines the range over which condition affects, for example:
1 | /* all code in bracket is affects by if condition*/ |
2 | if (x == y){ |
3 | x++; |
4 | y--; |
5 | } |
6 | /* only expression x++ is affected by if condition*/ |
7 | if (x == y) |
8 | x++; |
9 | y--; |
In case you want to use both condition of if statement, you can use if-else statement. If the condition of if statement is false the code block in else will be executed. Here is the syntax of if-else statement:
1 | if (condition){ |
2 | /* code block of if statement */ |
3 | } else { |
4 | /* code block of else statement */ |
5 | } |
If we want to use several conditions we can use if-else-if statement. Here are common syntax of if-else-ifstatement:
1 | if (condition-1){ |
2 | /* code block if condition-1 is true */ |
3 | } else if (condition-2){ |
4 | /* code block if condition-2 is true */ |
5 | } else if (condition-3){ |
6 | /* code block if condition-3 is true */ |
7 | } else { |
8 | /* code block all conditions above are false */ |
9 | } |
1 | if (x == y){ |
2 | printf ( "x is equal y" ); |
3 | } |
4 | else if (x > y){ |
5 | printf ( "x is greater than y" ); |
6 | } else if (x < y){ |
7 | printf ( "x is less than y" ); |
8 | } |
If you like this please Link Back to this article...
0 comments:
Post a Comment