Welcome to our deep dive into the world of C Programming! Today, we're going to explore the if statement, a fundamental control structure that will help you make decisions in your programs.
The if statement is used to execute a block of code only if a specific condition is met. It's like a gatekeeper, allowing certain code to run only when certain conditions are true.
Here's the basic syntax of the if statement in C:
if (condition) {
// Code to be executed if the condition is true
}Let's break it down:
if: This is the keyword that starts the if statement.(condition): This is where you write the condition that, if true, will make the code inside the braces execute.{}: These are the braces that enclose the code to be executed if the condition is true.In C, we use the == operator to test for equality. For example:
if (x == y) {
// Code to be executed if x is equal to y
}You can also use the else keyword to specify a block of code to be executed if the condition is false. This is known as an if-else statement:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}You can also use a series of if-else statements to test multiple conditions in sequence. This is called an if-else if ladder:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition1 is false and condition2 is true
} else if (condition3) {
// Code to be executed if condition1 and condition2 are false and condition3 is true
} ...Let's create a simple program that checks if a number is even or odd:
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}
return 0;
}In this example, we're using the modulus operator (%) to find the remainder of number divided by 2. If the remainder is 0, the number is even; otherwise, it's odd.
What does the `if` statement do in C?
That's it for today! By now, you should have a good understanding of the if statement in C. In the next lesson, we'll dive deeper into C control structures with the switch statement. Until then, happy coding! 💻💻💻