Conditional statements, also known as Selection statements, are control statements that allows a program to make decisions and execute certain blocks of code only when specific conditions are met.
- Conditional statements evaluate expressions (conditions) that return either true or false and perform actions based on these evaluations.
Types of Conditional Statements in C:
- The if Statement
- The if-else statement
- if-else if-else ladder
- switch statement
- Ternary (Conditional) Operator ?:
a.) The if Statement:
- The if statement is used to execute a block of code if a condition is true. If the condition is false, it is skipped.
Syntax:
if (condition) {
// Code to execute if condition is true
}Example:
#include <stdio.h>
int main() {
int x = 10;
if (x > 0) {
printf("x is positive\n");
}
return 0;
}2.) The if-else statement:
- The if-else statement allows you to execute one block of code if the condition is true and another block if the condition is false.
Syntax:
if (condition) {
// True block
} else {
// False block
}Example:
#include <stdio.h>
int main() {
int x = -5;
if (x > 0) {
printf("x is positive\n");
} else {
printf("x is not positive\n");
}
return 0;
}3.) The if-else if-else Statement:
The if-else if-else statement is used when you have multiple conditions to check. It allows you to test multiple conditions and execute code based on the first true condition.
Syntax:
if (condition1) {
// Block for condition1
} else if (condition2) {
// Block for condition2Example:
#include <stdio.h>
int main() {
int x = 0;
if (x > 0) {
printf("x is positive\n");
} else if (x == 0) {
printf("x is zero\n");
} else {
printf("x is negative\n");
}
return 0;
}4.) The switch Statement
The switch statement is a pattern-matching feature that allows for cleaner and more readable code for scenarios where multiple conditions need to be checked.
Syntax:
switch (expression) {
case constant1:
// code block
break;
case constant2:
// code block
break;
default:
// code block
}Example:
#include <stdio.h>
int main() {
int day = 2;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Other day\n");
}
return 0;
}Using if- else as Ternary Operator
In C, you can use an if-else statement in a compact form known as a ternary operator (or conditional expression). The ternary operator allows you to write a single line of code to evaluate a condition and return a value based on whether the condition is True or False.
Syntax of Ternary Operator:
condition ? value_if_true : value_if_false;- condition: The expression to evaluate.
- value_if_true: The result if the condition is True.
- value_if_false: The result if the condition is False.
Example:
#include <stdio.h>
int main() {
int age = 20;
// Ternary operator
const char* status = (age >= 18) ? "Adult" : "Minor";
printf("%s\n", status);
return 0;
}