C if Statement 🎯

beginner
17 min

C if Statement 🎯

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.

What is an if Statement? 📝

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.

Syntax 💡

Here's the basic syntax of the if statement in C:

c
if (condition) { // Code to be executed if the condition is true }

Let's break it down:

  1. if: This is the keyword that starts the if statement.
  2. (condition): This is where you write the condition that, if true, will make the code inside the braces execute.
  3. {}: These are the braces that enclose the code to be executed if the condition is true.

Conditional Operator 💡

In C, we use the == operator to test for equality. For example:

c
if (x == y) { // Code to be executed if x is equal to y }

if-else Statement 💡

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:

c
if (condition) { // Code to be executed if the condition is true } else { // Code to be executed if the condition is false }

if-else if Ladder 💡

You can also use a series of if-else statements to test multiple conditions in sequence. This is called an if-else if ladder:

c
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 } ...

Practical Example 💡

Let's create a simple program that checks if a number is even or odd:

c
#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.

Quiz 💡

Quick Quiz
Question 1 of 1

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! 💻💻💻