For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
In every program, the ability to make decisions is paramount. Whether it's determining if a user is logged in or figuring out which action to take based on user input, decision-making structures guide the flow of the program. One of the most powerful and commonly used decision-making structures is the if-else statement in C, which is also taught in top-rated software development courses.
This blog will help you understand not just the basics, but also the nuances of the if-else statement in C. Whether you're a budding C developer or an intermediate programmer looking to sharpen your skills, this guide will give you a deeper understanding of conditionals, practical tips, and how to apply them effectively in your code.
Unlock your potential with online DBA programs or enroll in the first-of-its-kind Generative AI Doctorate program from Golden Gate University!
If-else statement in C is a control flow structure that allows your program to make decisions based on certain conditions. It’s one of the building blocks of programming logic, enabling you to execute a particular block of code if a condition is true, and a different block if the condition is false.
This decision-making mechanism is used across many applications, from simple conditional checks like validating input to complex scenarios like determining whether a user should have access to specific resources.
if (condition) {
// Executes if the condition is true
} else {
// Executes if the condition is false
}
`condition` is a boolean expression (true or false) that determines which block of code runs.
`if` handles the case when the condition is true, while **`else`** handles the case when it’s false.
Must Read: 29 C Programming Projects in 2025 for All Levels [Source Code Included]
Here’s an example of if-else statement in C:
#include <stdio.h>
int main() {
int x = 10;
if (x > 5) {
printf("x is greater than 5\n");
} else {
printf("x is 5 or less\n");
}
return 0;
}
Output: x is greater than 5
Explanation:
The if-else statement in C allows your program to choose between two possible paths — a fundamental building block for handling logic based on dynamic input.
A flowchart is a visual representation of the logic behind a C program. By understanding the flow of an if-else statement in C, you can make better decisions while writing complex logic. Let’s break down how the if-else statement in C works visually.
Here’s a simple flowchart for the if-else statement:
1. Condition Evaluation: The condition is evaluated. If it’s true, the program enters the `if` block. If false, it enters the `else` block.
2. Execution Flow: Based on the condition, only one block of code will run, and the program will continue after that.
The if-else statement in C is simple but incredibly powerful because it allows dynamic decisions at runtime.
Also explore Masters of Business Administration Course
The if-else statement in C is straightforward but powerful when you break it down. It evaluates a condition (boolean expression) and executes one block of code if true, and another if false. Let’s explore a simple example to see how it works in practice.
Here’s the code for a program in C that checks whether a number is positive or negative:
#include <stdio.h>
int main() {
int number = -2;
if (number >= 0) {
printf("The number is positive.\n");
} else {
printf("The number is negative.\n");
}
return 0;
}
Output: The number is negative.
Explanation:
This example illustrates how the if-else statement in C can be used for branching decisions in your code. If the condition is true, one block of code runs; if it’s false, another block runs.
Must Explore: Introduction to C Tutorial
What happens when you need to evaluate multiple conditions in sequence? For this, C provides the if-else ladder, or else-if chain, allowing you to check more than two possible conditions.
Here’s an example of if-else statement in C grading system program:
#include <stdio.h>
int main() {
int score = 76;
if (score >= 90) {
printf("Grade A\n");
} else if (score >= 75) {
printf("Grade B\n");
} else if (score >= 60) {
printf("Grade C\n");
} else {
printf("Grade F\n");
}
return 0;
}
Output: Grade B
Explanation:
Using an if-else ladder, you can execute multiple distinct blocks of code depending on which condition is true.
One of the most common examples in programming is checking if a number is even or odd. This scenario perfectly demonstrates how if-else statements in C are used in everyday applications.
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num % 2 == 0) {
printf("Even number\n");
} else {
printf("Odd number\n");
}
return 0;
}
Input: 11
Output: Odd number
Explanation:
This example highlights the simplicity and power of the if-else statement in C to classify numbers based on conditions.
Here are some of the practical examples of if-else statement in C:
This is a basic example of how you can use if-else statements to check whether a given number is positive, negative, or zero. This type of program is useful when processing numerical data where different actions might need to be taken based on the value.
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number > 0) {
printf("The number is positive.\n");
} else if (number < 0) {
printf("The number is negative.\n");
} else {
printf("The number is zero.\n");
}
return 0;
}
Input: -5
Output: The number is negative.
Explanation:
This example shows how if-else statements can be used for multiple decision-making steps, where more than two outcomes are possible.
A leap year is a year that is divisible by 4, but century years (years divisible by 100) are only leap years if they are also divisible by 400. This logic can be easily implemented using if-else statements.
#include <stdio.h>
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
printf("%d is a leap year.\n", year);
} else {
printf("%d is not a leap year.\n", year);
}
return 0;
}
Input: 2024
Output: 2024 is a leap year.
Explanation:
This example shows how if-else statements can handle more complex conditions and allow you to build decision logic that mimics real-world rules.
Pursue Business Analytics Certification
A BMI calculator is a great example of using if-else statements to classify an individual’s health based on their weight and height. The BMI is calculated using the formula:
BMI = weight (kg) / height (m)^2
Here’s how we can use if-else statements to classify the BMI:
#include <stdio.h>
int main() {
float weight, height, bmi;
// Taking input for weight and height
printf("Enter your weight in kg: ");
scanf("%f", &weight);
printf("Enter your height in meters: ");
scanf("%f", &height);
// BMI calculation
bmi = weight / (height * height);
// BMI classification using if-else
if (bmi < 18.5) {
printf("Underweight (BMI: %.2f)\n", bmi);
} else if (bmi >= 18.5 && bmi < 24.9) {
printf("Normal weight (BMI: %.2f)\n", bmi);
} else if (bmi >= 25 && bmi < 29.9) {
printf("Overweight (BMI: %.2f)\n", bmi);
} else {
printf("Obesity (BMI: %.2f)\n", bmi);
}
return 0;
}
Input:
Output: Normal weight (BMI: 22.86)
Explanation:
This example shows how to categorize a continuous range of values into discrete categories using if-else statements.
In many applications, it's useful to categorize individuals into different age groups. For example, a program might classify users as children, teenagers, adults, and seniors based on their age. Here’s how we can implement it using if-else statements.
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 0 && age <= 12) {
printf("You are a Child.\n");
} else if (age >= 13 && age <= 19) {
printf("You are a Teenager.\n");
} else if (age >= 20 && age <= 59) {
printf("You are an Adult.\n");
} else if (age >= 60) {
printf("You are a Senior.\n");
} else {
printf("Invalid age.\n");
}
return 0;
}
Input: Age: 25
Output: You are an Adult.
Explanation:
This demonstrates how you can handle multiple branches for classification tasks in your program.
An application might need to verify whether a user has entered the correct credentials for login. Here’s a simple if-else statement usage to simulate the authentication process, comparing the entered username and password with predefined values.
#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, "password123") == 0) {
printf("Login successful.\n");
} else {
printf("Invalid username or password.\n");
}
return 0;
}
Input:
Output: Login successful.
Explanation:
This example shows how if-else statements in C can be used to validate user input and manage login functionality.
Like any programming construct, the if-else statement in C has its strengths and weaknesses. While it’s an essential decision-making tool, it’s important to know when to use it and when not to.
Let’s explore the advantages and disadvantages of this powerful control flow tool.
The if-else statement in C has a straightforward syntax, making it incredibly easy for new programmers to understand. This simplicity is often key to quick problem-solving and prototyping.
The if-else statement in C is best suited for binary decisions, where you have two clear outcomes based on the condition. For example, checking if a number is positive or negative.
Using `if-else` makes the code easy to read and trace. Each decision point is clearly expressed, which helps with debugging and future maintenance.
You can nest `if-else` statements, create multi-branch `else-if` ladders, and combine them with logical operators to handle complex decision-making processes.
In long chains of `else-if` or `if-else ladders`, the program must evaluate each condition sequentially. If the conditions are complex, this can result in performance degradation, especially with large datasets.
While simple for two conditions, `if-else` chains can quickly become complex and harder to maintain for more than three or four conditions.
The if-else statement in C struggles when you need to make decisions based on multiple conditions with numerous outcomes. For such cases, constructs like `switch` statements may be more appropriate.
Although the if-else statement in C is versatile and useful, there are times when it’s not the best choice. Let's look at situations where you might want to avoid using `if-else`.
If you need to check several conditions with many possible outcomes, using a switch statement or a lookup table may be more efficient and readable.
If your program handles large datasets or requires optimal performance, you should avoid long chains of `if-else` statements. Instead, consider algorithms with better time complexity.
For complicated conditions, the if-else statement in C can quickly lead to unreadable and hard-to-maintain code. In such cases, breaking down the logic into functions might be a better approach.
The if-else statement in C is an essential tool for any developer's toolkit. It enables conditional branching, allowing your program to execute different paths based on dynamic conditions. However, as with all tools, it's important to know when and how to use it effectively.
By understanding its syntax, advantages, disadvantages, and when to avoid it, you can make better programming decisions and write more efficient, maintainable code.
If you omit the `else` block, the program will simply **do nothing** when the condition is false.
if (x > 10) {
printf("x is greater than 10\n");
}
// No else part
In this case, if `x` is not greater than 10, the program continues executing the next statement without performing any action related to that condition. This is useful when you only need to handle one case.
Yes, you can. Nested if-else statements allow you to evaluate secondary conditions inside a primary condition.
if (x > 0) {
if (x % 2 == 0) {
printf("Positive even number\n");
} else {
printf("Positive odd number\n");
}
}
This is particularly useful when the second condition is only relevant if the first one is true. Be careful with indentation and readability when nesting multiple levels deep.
An if-else if ladder evaluates conditions sequentially and stops checking once a true condition is found. In contrast, multiple `if` statements evaluate all conditions independently.
// if-else if
if (x > 0) {
// Executes only if x > 0
} else if (x == 0) {
// Executes only if x == 0
}
// multiple if
if (x > 0) {
// Executes if x > 0
}
if (x == 0) {
// This is checked regardless of the first if
}
Use `if-else if` when only one condition should match, and use multiple `if` blocks when conditions can be true simultaneously.
Absolutely. The if-else statement in C supports logical operators like `&&` (AND), `||` (OR), and `!` (NOT), which help combine multiple conditions.
if (age > 18 && income > 30000) {
printf("Eligible for loan\n");
}
This makes your conditional logic more powerful and expressive.
Variables declared inside the `if` or `else` blocks are **local to those blocks** and cannot be accessed outside.
if (x > 5) {
int y = 10;
printf("%d", y); // Works
}
// printf("%d", y); // Error: y is not declared here
To use a variable across blocks, declare it before the `if-else` structure.
Yes. The if-else statement in C can be used inside functions, loops, or even other `if-else` statements.
void checkNumber(int x) {
if (x < 0) {
printf("Negative\n");
} else {
printf("Non-negative\n");
}
}
You can even use `if-else` statements inside a `for` or `while` loop to perform conditional actions during iteration.
This is a common bug in C programs. Always double-check your comparison operators. You can also enable compiler warnings to catch such mistakes.
Yes. When checking multiple discrete constant values (e.g., menu options, status codes), a `switch` can be more efficient and readable than a long `if-else if` ladder.
// Better for discrete cases
switch (choice) {
case 1: printf("One"); break;
case 2: printf("Two"); break;
}
Use the if-else statement in C when you're evaluating **ranges or expressions**, and `switch` when comparing fixed values.
Yes, the ternary operator `? :` is a shorthand for simple `if-else` expressions.
int x = 10;
char *result = (x > 5) ? "Greater" : "Not Greater";
It is useful for **simple assignments or inline decisions**, but avoid it for more complex logic as it can hurt readability.
If you skip braces, only the **immediate next statement** is considered part of the `if` or `else`.
if (x > 5)
printf("x is greater\n");
printf("This will always print\n"); // Not part of the if!
This often leads to **logical bugs**. Always use braces `{}` even for single statements to avoid ambiguity and future issues.
Yes. You can write any number of statements inside an `if` or `else` block as long as you wrap them in curly braces.
if (score >= 90) {
printf("Excellent!\n");
bonus += 100;
grade = 'A';
}
If you skip braces, only the first line is considered part of the condition, which might not be what you intended.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.