In this tutorial, you'll learn how to use control flow statements like if
, else
, and switch
in C programming to make decisions in your programs.
C Control Flow (if, switch) Tutorial
1. Using the if
Statement
The if
statement allows your program to execute code conditionally:
#include <stdio.h>
int main() {
int number = 10;
if (number > 0) {
printf("The number is positive.\\n");
}
return 0;
}
This program checks if number
is greater than zero and prints a message if the condition is true.
2. Adding an else
Block
Use else
to specify an alternative block of code to execute if the condition is false:
#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;
}
3. Using the switch
Statement
The switch
statement is used for multiple conditions based on the value of a variable:
#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;
}
This program uses switch
to print the name of a day based on its number.
4. Tips and Best Practices
- Always include a
default
case inswitch
for unexpected values. - Use
break
inswitch
cases to avoid fall-through behavior. - Keep conditions simple and readable.
5. Conclusion
Control flow statements like if
, else
, and switch
are essential tools in C programming. Practice using them to make your programs dynamic and responsive.