Make yourself comfortable as we delve into the world of structured decision making in C programming—If-Else Statements. This topic is essential to understand conditional logic and write efficient code. You'll learn how to compare values, make decisions based on those comparisons, and structure your code accordingly. Let's get started!
An If Statement in C allows you to test a condition and execute a block of code if that condition is true. Here's the basic syntax:
if (condition) {
// Code to be executed if condition is true
}
To handle multiple possibilities, we can use Else-If Statements. The structure looks like this:
if (condition1) {
// Code for condition 1
} else if (condition2) {
// Code for condition 2
} ... else if (conditionN) {
// Code for condition N
} else {
// Default code when all conditions are false
}
Note: The conditions are tested from top to bottom, and the first one that evaluates to true will be executed. If none of the conditions is true, the default code in the else clause will run.
Let's consider a simple example where we check if an age is eligible for voting:
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) {
printf("You are eligible to vote.\n");
} else {
printf("Sorry, you're not old enough to vote.\n");
}
return 0;
}
In this example, we ask the user for their age and check if it is equal to or greater than 18. If so, we inform them they can vote. Otherwise, we let them know that they are not old enough.
What causes it: Typographical errors in syntax
# Bad code example that triggers the error
if(age >= 18)
printf("You are eligible to vote.\n");
Error message:
example.c: In function 'main':
example.c:7:5: error: expected ';' before 'printf'
printf("You are eligible to vote.\n");
^
Solution: Make sure to include semicolons at the end of each statement, even inside if-else blocks.
# Corrected code
if (age >= 18) {
printf("You are eligible to vote.\n");
}
Why it happens: The compiler expects a semicolon at the end of every statement, and omitting it leads to an error.
How to prevent it: Always include a semicolon at the end of each C statement.
What causes it: Mixing up if and else-if conditions
# Bad code example that triggers the logic error
if (age >= 18) {
printf("You are not eligible to vote.\n");
} else if (age < 18) {
printf("You are eligible to vote.\n");
}
Solution: Swap the conditions in the if and else-if statements.
# Corrected code
if (age >= 18) {
printf("You are eligible to vote.\n");
} else if (age < 18) {
printf("You are not old enough to vote.\n");
}
Why it happens: The conditions were tested in reverse order, leading to the wrong result.
How to prevent it: Always test the easiest or most likely condition first, followed by less probable ones.
Next steps: Learn about Switch Statements and Loops to further enhance your understanding of control structures in C programming! Happy coding!