What is a Conditional Statement in C?
Conditional Statements in C programming are used to make decisions based on the
conditions. Conditional statements execute sequentially when there is no condition
around the statements. If you put some condition for a block of statements, the
execution flow may change based on the result evaluated by the condition. This process
is called decision making in ‘C.’
In ‘C’ programming conditional statements are possible with the help of the following
constructs:
1. If statement
2. If-else statement
3. If-else if statement
4. Switch statement
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
You have already learned that C supports the usual logical conditions from
mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
If statement Syntax:
if (condition) {
// block of code to be executed if the condition is true
}
Example: Write a c program to print the greater value among two entered numbers.
Assume int a = 20 and int b = 16;
If else statement Syntax:
Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
If else if statement Syntax:
Use the else if statement to specify a new condition if the first condition is false.
if (condition1){
// block of code to be executed if condition1 is true
} else if (condition2){
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
Example: Write a c program to check the number is positive or negative.
Switch Statement
Instead of writing many if..else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed:
Switch Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The switch expression is evaluated once
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
The break statement breaks out of the switch block and stops the execution
The default statement is optional, and specifies some code to run if there is no
case match
The break Keyword
When C reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
The default Keyword
The default keyword specifies some code to run if there is no case match.