if Statement

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 ifstatement syntax is simple as follows:

if(condition){
/* unit of code to be executed */
}

C programming language forces condition must be a boolean expression or value. ifstatement has it own scope which defines the range over which condition affects, for example:

/* all code in bracket is affects by if condition*/
if(x == y){
x++;
y--;
}
/* only expression x++ is affected by if condition*/
if(x == y)
x++;
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:

if(condition){
/* code block of if statement */
}else{
/* code block of else statement */
}

If we want to use several conditions we can use if-else-if statement. Here are common syntax of if-else-if statement:

if(condition-1){
/* code block if condition-1 is true */
}else if (condition-2){
/* code block if condition-2 is true */
}else if (condition-3){
/* code block if condition-3 is true */
}else{
/* code block all conditions above are false */
}
if(x == y){
printf("x is equal y");
}
else if (x > y){
printf("x is greater than y");
}else if (x < y){
printf("x is less than y");
}

source:http://cprogramminglanguage.net/c-if-statement.aspx

No comments:

Post a Comment