C if-else Statement 🎯

beginner
16 min

C if-else Statement 🎯

Welcome to the exciting world of C Programming! Today, we're going to dive deep into one of the most fundamental control structures - the if-else statement.

Understanding the Basics 📝

The if-else statement in C is used to perform different actions based on a condition. Here's a simple structure of an if-else statement:

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

Let's break it down:

  • if (condition) : This is where you write your condition. If the condition is true, the code inside the if block will be executed.
  • else : This keyword is used to specify the code that will be executed when the condition is false.

Example 1: Age Verification 💡

Let's write a simple program to verify if a person is eligible to vote. In India, the minimum age to vote is 18 years.

c
#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("You are not eligible to vote.\n"); } return 0; }

In this example, we first ask the user to input their age. We then check if the age is greater than or equal to 18 using the if statement. If the condition is true, the user is eligible to vote, and the message is displayed. Otherwise, the user is not eligible to vote.

Nesting if-else Statements 📝

Sometimes, you might need to check multiple conditions. In such cases, you can nest if-else statements. Here's an example:

c
#include <stdio.h> int main() { int marks; printf("Enter your marks: "); scanf("%d", &marks); if (marks >= 90) { printf("Grade A\n"); } else if (marks >= 80) { printf("Grade B\n"); } else if (marks >= 70) { printf("Grade C\n"); } else { printf("Sorry, you failed.\n"); } return 0; }

In this example, we check the marks obtained by a student. If the marks are greater than or equal to 90, the student gets Grade A. If the marks are between 80 and 90, the student gets Grade B, and so on. If the marks are less than 70, the student fails.

Quiz 💡

Quick Quiz
Question 1 of 1

What will be the output for the following code?

Stay tuned for more on C Programming! In our next lesson, we'll explore switch-case statements. Until then, happy coding! 🎉