Welcome to the world of C Programming! Today, we're going to dive into Conditional Statements, a powerful tool that helps your program make decisions based on certain conditions. Let's get started! 📝
Conditional statements in C are used to perform different actions based on a specific condition. They help your program to execute code selectively, making your code more dynamic and efficient. 💡
The if...else statement is the most common conditional statement in C. It tests a condition and executes different code blocks based on whether the condition is true (if) or false (else).
if (condition) {
// Code block executed if condition is true
} else {
// Code block executed if condition is false
}#include <stdio.h>
int main() {
int age = 18;
if (age >= 18) {
printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n");
}
return 0;
}In this example, we check if the age is 18 or more. If it is, we print "You are eligible to vote." If not, we print "You are not eligible to vote."
What does the `if...else` statement do in C?
Nested if...else statements are used when a condition depends on the result of another condition. In simpler terms, you can have multiple if...else statements inside another if...else statement.
if (condition1) {
// Code block executed if condition1 is true
} else if (condition2) {
// Code block executed if condition1 is false and condition2 is true
} else if (condition3) {
// Code block executed if condition1 and condition2 are false and condition3 is true
} else {
// Code block executed if all conditions are false
}#include <stdio.h>
int main() {
int grade = 75;
if (grade >= 90) {
printf("You got an A.\n");
} else if (grade >= 80) {
printf("You got a B.\n");
} else if (grade >= 70) {
printf("You got a C.\n");
} else {
printf("You need to study more.\n");
}
return 0;
}In this example, we check the grade. If it's 90 or more, we print "You got an A." If it's between 80 and 90, we print "You got a B." If it's between 70 and 80, we print "You got a C." If it's less than 70, we print "You need to study more."
What is a nested `if...else` statement in C?
That's it for today! I hope you found this lesson on C Conditional Statements useful. Conditional statements are a fundamental part of programming, and mastering them will help you create more dynamic and efficient code. Keep practicing, and remember, coding is all about solving problems, so keep solving! 🎉
Stay tuned for more lessons on C Programming, and happy coding! 🚀