Conditional Statements in C
Introduction
Conditional statements in C allow you to make decisions and control the flow of your program. They enable you to execute specific code blocks based on conditions. In this tutorial, we will explore three primary types of conditional statements in C: if
, else
, and switch
. We'll cover their usage with sample code to illustrate their functionality.
if Statement
The if
statement allows you to execute a block of code if a specified condition is true:
#include <stdio.h>
int main() {
int age = 25;
if (age >= 18) {
printf("You are an adult.\\n");
}
return 0;
}
In this example, the if
statement checks if the age
is greater than or equal to 18. If the condition is true, it prints "You are an adult."
if-else Statement
The if-else
statement allows you to execute one block of code if a condition is true and another block if it is false:
#include <stdio.h>
int main() {
int score = 75;
if (score >= 70) {
printf("You passed the exam.\\n");
} else {
printf("You failed the exam.\\n");
}
return 0;
}
In this example, the if
condition checks if the score
is greater than or equal to 70. If true, it prints "You passed the exam." If false, it prints "You failed the exam."
switch Statement
The switch
statement allows you to select one of many code blocks to be executed based on the value of an expression:
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\\n");
break;
case 2:
printf("Tuesday\\n");
break;
case 3:
printf("Wednesday\\n");
break;
default:
printf("Unknown day\\n");
}
return 0;
}
In this example, the switch
statement evaluates the value of day
and executes the corresponding code block. In this case, it prints "Wednesday" because day
is 3. The default
case is executed if none of the other cases match.
Conclusion
Conditional statements are fundamental in C programming for making decisions and controlling the program's flow. You've learned how to use if
, if-else
, and switch
statements with sample code. These statements are powerful tools for building complex logic in your programs.