Welcome back to our C programming series! Today we'll be diving deep into If Statements, one of the most fundamental building blocks in C programming. This concept will empower you to create more complex and dynamic programs, allowing your code to make decisions based on certain conditions. By the end of this lesson, you'll be able to create your own conditional statements, making your programs smarter and more adaptable!
If Statements are used to evaluate an expression, and if it is true, a block of code will execute. The basic syntax for an If Statement looks like this:
if (condition) {
// Code that runs if the condition is true
}
Let's take a look at an example:
int age = 20;
if (age >= 18) {
printf("You are eligible to vote.");
}
In this code snippet, we have declared an integer variable called age
with the value of 20. We then check if the condition (age >= 18)
is true. If it is, the message "You are eligible to vote." will be printed out.
true
or false
.Let's look at some real-world examples where If Statements come in handy:
int num1 = 5;
int num2 = 7;
if (num1 > num2) {
printf("num1 is greater than num2.");
} else {
printf("num2 is greater than or equal to num1.");
}
In this example, we're comparing two numbers and printing out which one is greater. If the condition (num1 > num2)
is true, it will print "num1 is greater than num2." If not, it will print "num2 is greater than or equal to num1."
char choice;
printf("Enter 'y' to continue or 'n' to quit: ");
scanf("%c", &choice);
if (choice == 'y') {
printf("Continuing...\n");
} else if (choice == 'n') {
printf("Quitting...\n");
} else {
printf("Invalid input. Please enter 'y' to continue or 'n' to quit.\n");
}
In this example, we ask the user for input and use If Statements to check if they entered either 'y'
or 'n'
. Depending on their input, we print out an appropriate message.
What causes it: Missing parentheses around the condition expression.
if condition expression;
Error message:
SyntaxError: unexpected identifier
Solution:
if (condition) { ... }
Why it happens: The parentheses are essential for correctly defining the condition expression.
How to prevent it: Always include parentheses around your condition expressions.
What causes it: Using a variable that has not been declared yet.
if (var_name > 10) { ... }
Error message:
NameError: name 'var_name' is not defined
Solution:
int var_name;
if (var_name > 10) { ... }
Why it happens: The variable var_name
has not been declared before being used in the If Statement.
How to prevent it: Always declare your variables before using them in conditional statements or any other code.
Next up, we'll dive deeper into Else if Statements and Switch Statements, which will further expand your conditional programming skills in C!