What is if-else Statement in C?
The if-else statement in C programming is a decision-making structure that allows a program to execute one block of code when a condition is true and another block when the condition is false. It ensures that the program can handle two possible outcomes for a given condition, providing flexibility to respond to different scenarios.
Real-Life Example:
Imagine deciding what to wear based on the weather. If it’s sunny, you wear sunglasses; otherwise, you carry an umbrella. The decision depends on the condition (weather), and you choose one option or the other.
C If-Else Statement Syntax
The syntax of if-else in C programming is:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}Components:
if Keyword: Indicates the start of the decision-making structure.
Condition: A logical or relational expression placed inside parentheses () that evaluates to either true (non-zero) or false (zero).
If Block: The code block inside the curly braces {} following the if keyword, which executes if the condition is true.
else Keyword: Provides an alternative code block to execute when the condition is false.
Else Block: The code block inside the curly braces {} following the else keyword, which executes if the condition is false.
How If-Else Works in C
The if-else statement works by checking a condition and choosing one of two possible paths.
Here’s how it works step by step:
Start: The program begins execution.
Condition Check: The if condition is evaluated (for example, marks >= 50).
If Condition is True:
The program executes the if body (the code inside the if block).
If Condition is False:
The program executes the else body (the code inside the else block).
Continue Execution:
After executing either block, the program continues with the statements written after the if-else.
- Exit: The program finishes execution.
Examples of If-Else Statement in C Programming
Following are some examples of if-else statement in C:
1. Check if a Number is Positive or Negative
Following is a C program to check number is positive or negative:
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number >= 0) {
printf("The number is non-negative.\n");
} else {
printf("The number is negative.\n");
}
return 0;
}Output:
Input: 5 → Output: The number is non-negative.
Input: -3 → Output: The number is negative.2. Check if a Number is Even or Odd
Following is the odd-even program in 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;
}Output:
Input: 4 → Output: The number is even.
Input: 7 → Output: The number is odd.3. Find the Largest of Two Numbers
Following is the largest number program in C:
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
if (a > b) {
printf("%d is larger.\n", a);
} else {
printf("%d is larger.\n", b);
}
return 0;
}Output:
Input: 10 20 → Output: 20 is larger.
Input: 25 15 → Output: 25 is larger.4. Check Voting Eligibility
The program below check the voting eligibility based on the age of the candidate:
#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;
}Output:
Input: 20 → Output: You are eligible to vote.
Input: 16 → Output: You are not eligible to vote.5. Determine Grade Based on Marks
The following C program checks whether a student has passed or failed based on the entered marks:
#include <stdio.h>
int main() {
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
if (marks >= 50) {
printf("You passed the exam.\n");
} else {
printf("You failed the exam.\n");
}
return 0;
}Output:
Input: 60 → Output: You passed the exam.
Input: 40 → Output: You failed the exam.6. Validate Login Credentials
The following C program checks whether the entered username and password are correct:
#include <stdio.h>
#include <string.h>
int main() {
char username[20], password[20];
printf("Enter username: ");
scanf("%s", username);
printf("Enter password: ");
scanf("%s", password);
if (strcmp(username, "admin") == 0 && strcmp(password, "1234") == 0) {
printf("Login successful.\n");
} else {
printf("Invalid username or password.\n");
}
return 0;
}Output:
Input: admin, 1234 → Output: Login successful.
Input: user, pass → Output: Invalid username or password.7. Check Whether a Year is a Leap Year
The following is leap year program in C:
#include <stdio.h>
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
printf("%d is a leap year.\n", year);
} else {
printf("%d is not a leap year.\n", year);
}
return 0;
}Output:
Input: 2020 → Output: 2020 is a leap year.
Input: 1900 → Output: 1900 is not a leap year.8. E-Commerce Discount Check
The following C program checks whether a customer is eligible for a discount based on the purchase amount:
#include <stdio.h>
int main() {
int purchaseAmount;
printf("Enter the purchase amount: ");
scanf("%d", &purchaseAmount);
if (purchaseAmount >= 1000) {
printf("You get a 10%% discount!\n");
} else {
printf("No discount available.\n");
}
return 0;
}Output:
Input: 1200 → Output: You get a 10% discount!
Input: 800 → Output: No discount available.Nested If-Else Statement in C
A nested if-else statement in C occurs when an if-else statement is placed inside another if or else block. It allows handling of multiple conditions in a hierarchical manner. Each inner if or else is evaluated only if the condition of the outer if statement is true. This structure is useful for complex decision-making scenarios with multiple outcomes.
Real-Life Example:
Imagine entering a university:
Outer Condition: Check if the student has passed the entrance exam.
Inner Conditions: If the student has passed, check their score to decide if they are eligible for a scholarship.
This layered approach reflects how nested if-else statements work.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if condition2 is false
}
} else {
// Code to execute if condition1 is false
}Example
Program: Check Exam Result and Scholarship Eligibility
#include <stdio.h>
int main() {
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
if (marks >= 50) { // Outer condition
printf("You passed the exam.\n");
if (marks >= 90) { // Inner condition
printf("You are eligible for a scholarship.\n");
} else {
printf("You are not eligible for a scholarship.\n");
}
} else {
printf("You failed the exam.\n");
}
return 0;
}Explanation of the Program:
The outer if (marks >= 50) checks if the student passed the exam.
If true:
The inner if (marks >= 90) checks if they qualify for a scholarship.
If they don’t score 90 or more, the else block prints they are not eligible for a scholarship.
If the outer condition is false, the program prints that the student failed the exam.
Output:
Input: 95
You passed the exam.
You are eligible for a scholarship.Common Mistakes with If-Else Statements in C
Below are some common mistakes to avoid when using if-else statements in C:
Using Assignment Instead of Comparison: Writing = instead of == in the condition.
Missing Curly Braces: Omitting {} for multiple statements, leading to unintended execution.
Ambiguous Conditions: Writing overly complex or unclear conditions.
Unnecessary Nesting: Using deeply nested if-else statements instead of simplifying logic.
Forgetting the else Block: Not handling the false case when it is needed.
Ignoring Edge Cases: Failing to account for boundary conditions or special inputs.
Poor Indentation: Making the code hard to read and debug.
Redundant Conditions: Checking conditions already covered in previous if-else blocks.
Infinite Loops: Incorrectly placing if-else within loops without proper termination conditions.
Misusing Logical Operators: Using incorrect operators (&& instead of ||, or vice versa).
Uses and Applications of If-Else in C Programming
Here are some common uses and applications of the if-else statement in C:
Age Verification: Checking eligibility for voting, driving, or accessing age-restricted content.
Input Validation: Ensuring user inputs are valid, such as non-negative numbers or correct formats.
Login Authentication: Validating username and password for user login.
E-Commerce Discounts: Applying discounts based on purchase amount or coupon codes.
Exam Results: Determining pass/fail status based on marks.
Tax Calculation: Applying different tax rates based on income brackets.
Grade Assignment: Assigning grades to students based on their marks.
Weather Alerts: Displaying alerts based on temperature or weather conditions.
Banking Systems: Checking sufficient balance before allowing withdrawals.
Traffic Light Control: Managing actions based on traffic signal conditions.
Ticket Pricing: Offering different prices based on age groups (child, adult, senior).
Gaming Logic: Determining actions based on player input or game state.
Access Control: Granting or denying access to restricted areas or systems.
Restaurant Menu: Displaying options based on the time of day (e.g., breakfast or dinner menu).
Parking Systems: Charging different fees based on the duration of parking.
No comments:
Post a Comment