Conditional Statements in C
Conditional statements are fundamental building blocks in programming that allow your programs to make decisions based on specific conditions. They enable your code to execute different blocks based on whether certain conditions are true or false.
Key Takeaways
- Conditional statements enable decision-making in C programs
- The
if
statement is the most basic form of conditional logic - The
else
clause provides an alternative when anif
condition is false - Multiple conditions can be tested using
else if
statements - Nested conditionals allow for complex decision trees
- The ternary operator provides a concise alternative for simple conditions
Why Do We Need Conditional Statements?
In real-world applications, programs need to make decisions based on different conditions. For instance:
- A banking application needs to check if a user has sufficient funds before processing a withdrawal
- A game needs to determine if a player has won, lost, or should continue playing
- A form validation system needs to verify if user input meets specific criteria
- A temperature control system needs to turn heating on or off based on current temperature readings
Conditional statements provide the logical structure that makes these decisions possible.
The if Statement
The if
statement is the most fundamental conditional statement in C. It evaluates a condition and executes a block of code only if that condition is true.
Basic Syntax
1if (condition) {2 // Code to execute if condition is true3}
The condition inside the parentheses is evaluated as a Boolean expression. In C, any non-zero value is considered true, while 0 is considered false.
Simple Example
1#include <stdio.h>23int main() {4 int age = 20;56 if (age >= 18) {7 printf("You are eligible to vote.\n");8 }910 return 0;11}
In this example:
- We declare an integer variable
age
and assign it the value 20. - The condition
age >= 18
checks if the age is greater than or equal to 18. - Since 20 is indeed greater than 18, the condition evaluates to true.
- Therefore, the code block inside the
if
statement executes, printing "You are eligible to vote."
Common Mistake: Missing Braces
If you omit the curly braces {}
, only the first statement after the if
condition will be part of the conditional block. Always use braces, even for single statements, to avoid logical errors.
The if-else Statement
The if-else
statement extends the if
statement by providing an alternative code block to execute when the condition is false.
Basic Syntax
1if (condition) {2 // Code to execute if condition is true3} else {4 // Code to execute if condition is false5}
Example
1#include <stdio.h>23int main() {4 int number = 7;56 if (number % 2 == 0) {7 printf("%d is an even number.\n", number);8 } else {9 printf("%d is an odd number.\n", number);10 }1112 return 0;13}
Let's break down this example:
- We declare an integer variable
number
and assign it the value 7. - The expression
number % 2 == 0
checks if the remainder whennumber
is divided by 2 equals 0 (which would mean it's even). - Since 7 divided by 2 has a remainder of 1, the condition evaluates to false.
- Therefore, the code block inside the
else
statement executes, printing "7 is an odd number."
Understanding the Modulo Operator (%)
The modulo operator %
returns the remainder when one integer is divided by another. It's commonly used to:
- Check if a number is even or odd (
num % 2 == 0
for even) - Cycle through a range of values (like in a circular buffer)
- Distribute items evenly across buckets (like in hash tables)
In our example, 7 % 2
equals 1, which means 7 is odd.
The else if Statement
When you need to check multiple conditions, you can use the else if
construct. It allows you to test several conditions in sequence.
Basic Syntax
1if (condition1) {2 // Code to execute if condition1 is true3} else if (condition2) {4 // Code to execute if condition1 is false and condition2 is true5} else if (condition3) {6 // Code to execute if condition1 and condition2 are false and condition3 is true7} else {8 // Code to execute if all conditions are false9}
Example: Grading System
1#include <stdio.h>23int main() {4 int score = 85;56 if (score >= 90) {7 printf("Grade: A\n");8 } else if (score >= 80) {9 printf("Grade: B\n");10 } else if (score >= 70) {11 printf("Grade: C\n");12 } else if (score >= 60) {13 printf("Grade: D\n");14 } else {15 printf("Grade: F\n");16 }1718 return 0;19}
In this example:
- We declare a variable
score
with the value 85. - The first condition
score >= 90
evaluates to false (85 is not ≥ 90). - The second condition
score >= 80
evaluates to true (85 is ≥ 80). - Since the second condition is true, "Grade: B" is printed.
- The rest of the conditions are not evaluated since the program already found a true condition.
Best Practice: Order Matters
In else if
chains, conditions are evaluated sequentially. Always arrange your conditions from most specific to most general to ensure the correct branch is selected. In the example above, reversing the order would produce incorrect results.
Nested if Statements
For more complex decision-making, you can nest if
statements inside other if
or else
statements. This creates a hierarchical decision tree.
Example: Ticket Pricing
1#include <stdio.h>23int main() {4 int age = 25;5 char student = 'Y'; // 'Y' for Yes, 'N' for No67 if (age < 18) {8 printf("Child ticket: $8.00\n");9 } else {10 // Nested if for adults (age >= 18)11 if (student == 'Y') {12 printf("Student ticket: $10.00\n");13 } else {14 printf("Adult ticket: $12.00\n");15 }16 }1718 return 0;19}
Let's analyze this example step by step:
- We have two variables:
age
(25) andstudent
('Y'). - The outer
if
statement checks ifage
is less than 18. - Since 25 is not less than 18, the condition is false, so we move to the
else
block. - Inside the
else
block, there's a nestedif
that checks ifstudent
is 'Y'. - Since
student
is 'Y', the condition is true, so "Student ticket: $10.00" is printed.
Caution: While nested if
statements can be powerful, excessive nesting can make your code hard to read and maintain. If you find yourself using many levels of nesting, consider restructuring your logic or using switch statements.
This ticket pricing example could be rewritten more clearly using logical operators, which we'll explore next.
Logical Operators in Conditions
C provides logical operators that allow you to combine or negate conditions, making your code more concise and readable.
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical AND | True if both operands are true | if (age > 18 && hasID) |
|| | Logical OR | True if at least one operand is true | if (isMember || hasDiscount) |
! | Logical NOT | True if the operand is false | if (!isExpired) |
Rewriting the Ticket Pricing Example
1#include <stdio.h>23int main() {4 int age = 25;5 char student = 'Y'; // 'Y' for Yes, 'N' for No67 if (age < 18) {8 printf("Child ticket: $8.00\n");9 } else if (age >= 18 && student == 'Y') {10 printf("Student ticket: $10.00\n");11 } else {12 printf("Adult ticket: $12.00\n");13 }1415 return 0;16}
This version is more readable and accomplishes the same task without nesting. The logical AND (&&
) operator ensures that both conditions must be true for the "Student ticket" message to be printed.
Short-Circuit Evaluation
C uses short-circuit evaluation for logical operators:
- For
&&
: If the first expression is false, the second is not evaluated (since the result will be false regardless). - For
||
: If the first expression is true, the second is not evaluated (since the result will be true regardless).
This behavior can be used to your advantage, as shown in the following example:
1#include <stdio.h>23int main() {4 int x = 5;56 // The second part is evaluated only if x > 07 if (x > 0 && printf("x is positive\n")) {8 // The body still executes because printf returns a non-zero value9 printf("This will also print\n");10 }1112 x = 0;1314 // The second part is NOT evaluated because x <= 015 if (x > 0 && printf("This won't print\n")) {16 printf("This won't print either\n");17 }1819 return 0;20}
Note: While printf()
returns a non-zero value (the number of characters printed) if successful, using function calls with side effects in conditions as demonstrated above is not recommended for production code. It's shown here merely to illustrate short-circuit evaluation.
The Ternary Operator
The ternary operator (? :
) is a concise way to express simple conditional expressions. It's essentially a one-line if-else statement.
Basic Syntax
1condition ? expression_if_true : expression_if_false
Example
1#include <stdio.h>23int main() {4 int age = 20;56 // Using if-else7 if (age >= 18) {8 printf("Using if-else: Adult\n");9 } else {10 printf("Using if-else: Minor\n");11 }1213 // Using ternary operator14 printf("Using ternary: %s\n", age >= 18 ? "Adult" : "Minor");1516 // Assigning value based on condition17 int ticketPrice = (age < 12) ? 5 : (age < 65 ? 10 : 7);18 printf("Ticket price: $%d\n", ticketPrice);1920 return 0;21}
In this example:
- The first
printf
uses a traditional if-else structure. - The second
printf
uses the ternary operator to achieve the same result more concisely. - The third example shows how to assign different values to a variable based on a condition.
- The fourth example shows a nested ternary expression (though these can quickly become hard to read).
Best Practice: Ternary Operator
Use the ternary operator for simple, straightforward conditional expressions. For complex logic, stick with traditional if-else statements for better readability. Avoid nesting multiple ternary operators, as they can quickly become difficult to understand.
Common Pitfalls and Best Practices
Assignment vs. Equality
1// INCORRECT - Assignment instead of comparison2if (x = 5) {3 // This will always execute because x is assigned 5 (non-zero is true)4}56// CORRECT - Comparison7if (x == 5) {8 // Executes only if x equals 59}
Using =
(assignment) instead of ==
(equality comparison) is one of the most common errors. The expression x = 5
assigns 5 to x and returns 5, which is evaluated as true.
Forgetting Braces
1// Misleading indentation2if (condition)3 printf("First statement\n");4 printf("This always executes regardless of condition\n"); // Not part of the if block!56// Correct usage7if (condition) {8 printf("First statement\n");9 printf("Second statement, also part of the if block\n");10}
Without braces, only the first statement after the condition is part of the conditional block. Always use braces, even for single-line conditional blocks, to avoid this common error.
Floating-Point Comparisons
1// PROBLEMATIC - Direct equality comparison with floating-point2float a = 0.1 + 0.2;3if (a == 0.3) {4 printf("Equal\n"); // This might not execute due to floating-point precision!5}67// BETTER - Use a small epsilon value8float epsilon = 0.0001;9if (fabs(a - 0.3) < epsilon) {10 printf("Approximately equal\n");11}
Due to how floating-point numbers are represented in binary, direct equality comparisons can lead to unexpected results. Always use an epsilon-based comparison for floating-point values.
Real-World Examples
Let's look at some practical examples of conditional statements in real-world applications:
Form Input Validation
1#include <stdio.h>2#include <string.h>34int main() {5 char email[100];6 int containsAtSymbol = 0;78 printf("Enter your email address: ");9 scanf("%99s", email);1011 // Check if email contains @ symbol12 int length = strlen(email);13 for (int i = 0; i < length; i++) {14 if (email[i] == '@') {15 containsAtSymbol = 1;16 break;17 }18 }1920 // Validate email format21 if (length < 5) {22 printf("Error: Email is too short\n");23 } else if (!containsAtSymbol) {24 printf("Error: Email must contain an @ symbol\n");25 } else {26 printf("Email format is valid!\n");27 }2829 return 0;30}
Simple Login System
1#include <stdio.h>2#include <string.h>34int main() {5 // Predefined credentials (in a real system, these would be securely stored)6 const char correctUsername[] = "admin";7 const char correctPassword[] = "secure123";89 char username[50];10 char password[50];1112 printf("Username: ");13 scanf("%49s", username);1415 printf("Password: ");16 scanf("%49s", password);1718 if (strcmp(username, correctUsername) == 0) {19 if (strcmp(password, correctPassword) == 0) {20 printf("Login successful!\n");21 } else {22 printf("Incorrect password.\n");23 }24 } else {25 printf("Username not found.\n");26 }2728 return 0;29}
Security Note: The login example above is for educational purposes only. In a real-world application, you should never store passwords in plaintext, and user input should be properly validated and sanitized to prevent buffer overflow attacks.
Practice Exercises
Exercise 1: Temperature Classifier
Write a program that takes a temperature in Celsius as input and classifies it as:
- "Freezing" if temperature is below 0°C
- "Cold" if temperature is between 0°C and 10°C
- "Cool" if temperature is between 10°C and 20°C
- "Warm" if temperature is between 20°C and 30°C
- "Hot" if temperature is 30°C or above
Hint: Use if-else if-else statements to check the temperature ranges.
Exercise 2: Calculator with Error Handling
Create a simple calculator that takes two numbers and an operation (+, -, *, /) as input. Use conditional statements to perform the appropriate operation and handle potential errors, such as division by zero.
Hint: Check for the division operation and validate that the divisor is not zero before performing the operation.
Exercise 3: Leap Year Checker
Write a program that determines whether a given year is a leap year. A leap year is:
- Divisible by 4
- But not divisible by 100 unless it is also divisible by 400
Hint: Use logical operators to combine multiple conditions.
Summary
Conditional statements are essential tools in programming that allow your code to make decisions based on specific conditions. In C, you have several options for implementing conditional logic:
- Use
if
statements for simple conditions - Add an
else
clause for alternative actions - Use
else if
statements for multiple conditions - Combine conditions with logical operators (
&&
,||
,!
) - Use the ternary operator
?:
for simple conditional expressions
By mastering conditional statements, you'll be able to create more dynamic and responsive programs that can adapt to different inputs and situations. The next tutorial will cover switch statements, which provide an elegant way to handle multiple conditions for a single variable.
Related Tutorials
Basic Input and Output in C
Learn how to handle input and output operations in C programming.
Continue learning