Conditional Statements in C Language
Introduction
Conditional statements are used to perform different actions based on different conditions. These statements control the flow of the program by executing certain blocks of code based on whether a condition is true or false. In the C language, conditional statements include if
, else if
, else
, and switch
statements.
If Statement
The if
statement is used to execute a block of code only if a specified condition is true.
Example:
if (condition) { // code to be executed if condition is true }
Let's look at a practical example:
#include <stdio.h> int main() { int number = 10; if (number > 0) { printf("The number is positive.\n"); } return 0; }
Output:
If-Else Statement
The if-else
statement is used to execute one block of code if a condition is true, and another block of code if the condition is false.
Example:
if (condition) { // code to be executed if condition is true } else { // code to be executed if condition is false }
Let's look at a practical example:
#include <stdio.h> int main() { int number = -5; if (number > 0) { printf("The number is positive.\n"); } else { printf("The number is not positive.\n"); } return 0; }
Output:
If-Else If-Else Statement
The if-else if-else
statement is used to check multiple conditions. If one of the conditions is true, the corresponding block of code is executed. If none of the conditions is true, the else
block is executed.
Example:
if (condition1) { // code to be executed if condition1 is true } else if (condition2) { // code to be executed if condition2 is true } else { // code to be executed if both condition1 and condition2 are false }
Let's look at a practical example:
#include <stdio.h> int main() { int number = 0; if (number > 0) { printf("The number is positive.\n"); } else if (number < 0) { printf("The number is negative.\n"); } else { printf("The number is zero.\n"); } return 0; }
Output:
Switch Statement
The switch
statement allows a variable to be tested for equality against a list of values. Each value is called a case
, and the variable being switched on is checked for each case
.
Example:
switch (variable) { case value1: // code to be executed if variable == value1 break; case value2: // code to be executed if variable == value2 break; default: // code to be executed if variable doesn't match any case }
Let's look at a practical example:
#include <stdio.h> int main() { int day = 4; switch (day) { case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; case 3: printf("Wednesday\n"); break; case 4: printf("Thursday\n"); break; case 5: printf("Friday\n"); break; case 6: printf("Saturday\n"); break; case 7: printf("Sunday\n"); break; default: printf("Invalid day\n"); } return 0; }
Output: