Welcome to the exciting world of C programming! Today, we'll delve into one of the most fundamental concepts: Conditional Statements. These statements allow your code to make decisions and react differently to various input scenarios, making your programs more versatile and intelligent.
Conditional statements in C are used to test the conditions and execute different blocks of code based on the test results. The primary conditional statement in C is the if statement.
The if statement tests a condition and executes a block of code if the condition is true.
Here's a simple example:
#include <stdio.h>
int main() {
int age = 18;
if (age >= 18) {
printf("You are an adult.\n");
}
return 0;
}In this example, we check if the age is 18 or more. If it is, we print "You are an adult."
The if-else statement tests a condition and executes one block of code if the condition is true and another block if it's false.
#include <stdio.h>
int main() {
int age = 17;
if (age >= 18) {
printf("You are an adult.\n");
} else {
printf("You are a minor.\n");
}
return 0;
}In this example, if the age is 18 or more, we print "You are an adult.", otherwise we print "You are a minor."
The if-else if ladder allows you to test multiple conditions in sequence. If the first condition is false, it moves to the next one until it finds a condition that is true.
#include <stdio.h>
int main() {
int age = 16;
if (age >= 18) {
printf("You are an adult.\n");
} else if (age >= 16) {
printf("You are a minor but can drive a car.\n");
} else {
printf("You are too young to drive.\n");
}
return 0;
}In this example, we first check if the age is 18 or more, if not, we check if the age is 16 or more, and if not, we print "You are too young to drive."
What will the following code print?
Remember, practice makes perfect! Keep coding and exploring the fascinating world of C programming. Stay tuned for more lessons on C programming at CodeYourCraft. Happy coding! 🎉