Progress: 5 of 16 topics31%

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 an if 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

c
1if (condition) {
2 // Code to execute if condition is true
3}

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

c
1#include <stdio.h>
2
3int main() {
4 int age = 20;
5
6 if (age >= 18) {
7 printf("You are eligible to vote.\n");
8 }
9
10 return 0;
11}

In this example:

  1. We declare an integer variable age and assign it the value 20.
  2. The condition age >= 18 checks if the age is greater than or equal to 18.
  3. Since 20 is indeed greater than 18, the condition evaluates to true.
  4. 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

c
1if (condition) {
2 // Code to execute if condition is true
3} else {
4 // Code to execute if condition is false
5}

Example

c
1#include <stdio.h>
2
3int main() {
4 int number = 7;
5
6 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 }
11
12 return 0;
13}

Let's break down this example:

  1. We declare an integer variable number and assign it the value 7.
  2. The expression number % 2 == 0 checks if the remainder when number is divided by 2 equals 0 (which would mean it's even).
  3. Since 7 divided by 2 has a remainder of 1, the condition evaluates to false.
  4. 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

c
1if (condition1) {
2 // Code to execute if condition1 is true
3} else if (condition2) {
4 // Code to execute if condition1 is false and condition2 is true
5} else if (condition3) {
6 // Code to execute if condition1 and condition2 are false and condition3 is true
7} else {
8 // Code to execute if all conditions are false
9}

Example: Grading System

c
1#include <stdio.h>
2
3int main() {
4 int score = 85;
5
6 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 }
17
18 return 0;
19}

In this example:

  1. We declare a variable score with the value 85.
  2. The first condition score >= 90 evaluates to false (85 is not ≥ 90).
  3. The second condition score >= 80 evaluates to true (85 is ≥ 80).
  4. Since the second condition is true, "Grade: B" is printed.
  5. 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

c
1#include <stdio.h>
2
3int main() {
4 int age = 25;
5 char student = 'Y'; // 'Y' for Yes, 'N' for No
6
7 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 }
17
18 return 0;
19}

Let's analyze this example step by step:

  1. We have two variables: age (25) and student ('Y').
  2. The outer if statement checks if age is less than 18.
  3. Since 25 is not less than 18, the condition is false, so we move to the else block.
  4. Inside the else block, there's a nested if that checks if student is 'Y'.
  5. 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.

OperatorNameDescriptionExample
&&Logical ANDTrue if both operands are trueif (age > 18 && hasID)
||Logical ORTrue if at least one operand is trueif (isMember || hasDiscount)
!Logical NOTTrue if the operand is falseif (!isExpired)

Rewriting the Ticket Pricing Example

c
1#include <stdio.h>
2
3int main() {
4 int age = 25;
5 char student = 'Y'; // 'Y' for Yes, 'N' for No
6
7 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 }
14
15 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:

c
1#include <stdio.h>
2
3int main() {
4 int x = 5;
5
6 // The second part is evaluated only if x > 0
7 if (x > 0 && printf("x is positive\n")) {
8 // The body still executes because printf returns a non-zero value
9 printf("This will also print\n");
10 }
11
12 x = 0;
13
14 // The second part is NOT evaluated because x <= 0
15 if (x > 0 && printf("This won't print\n")) {
16 printf("This won't print either\n");
17 }
18
19 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

c
1condition ? expression_if_true : expression_if_false

Example

c
1#include <stdio.h>
2
3int main() {
4 int age = 20;
5
6 // Using if-else
7 if (age >= 18) {
8 printf("Using if-else: Adult\n");
9 } else {
10 printf("Using if-else: Minor\n");
11 }
12
13 // Using ternary operator
14 printf("Using ternary: %s\n", age >= 18 ? "Adult" : "Minor");
15
16 // Assigning value based on condition
17 int ticketPrice = (age < 12) ? 5 : (age < 65 ? 10 : 7);
18 printf("Ticket price: $%d\n", ticketPrice);
19
20 return 0;
21}

In this example:

  1. The first printf uses a traditional if-else structure.
  2. The second printf uses the ternary operator to achieve the same result more concisely.
  3. The third example shows how to assign different values to a variable based on a condition.
  4. 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

c
1// INCORRECT - Assignment instead of comparison
2if (x = 5) {
3 // This will always execute because x is assigned 5 (non-zero is true)
4}
5
6// CORRECT - Comparison
7if (x == 5) {
8 // Executes only if x equals 5
9}

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

c
1// Misleading indentation
2if (condition)
3 printf("First statement\n");
4 printf("This always executes regardless of condition\n"); // Not part of the if block!
5
6// Correct usage
7if (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

c
1// PROBLEMATIC - Direct equality comparison with floating-point
2float a = 0.1 + 0.2;
3if (a == 0.3) {
4 printf("Equal\n"); // This might not execute due to floating-point precision!
5}
6
7// BETTER - Use a small epsilon value
8float 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

c
1#include <stdio.h>
2#include <string.h>
3
4int main() {
5 char email[100];
6 int containsAtSymbol = 0;
7
8 printf("Enter your email address: ");
9 scanf("%99s", email);
10
11 // Check if email contains @ symbol
12 int length = strlen(email);
13 for (int i = 0; i < length; i++) {
14 if (email[i] == '@') {
15 containsAtSymbol = 1;
16 break;
17 }
18 }
19
20 // Validate email format
21 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 }
28
29 return 0;
30}

Simple Login System

c
1#include <stdio.h>
2#include <string.h>
3
4int main() {
5 // Predefined credentials (in a real system, these would be securely stored)
6 const char correctUsername[] = "admin";
7 const char correctPassword[] = "secure123";
8
9 char username[50];
10 char password[50];
11
12 printf("Username: ");
13 scanf("%49s", username);
14
15 printf("Password: ");
16 scanf("%49s", password);
17
18 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 }
27
28 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

Switch Statements in C

Multi-way decision making in C with switch statements.

Continue learning

Loops in C

Learn how to create repetitive tasks in your C programs using loops.

Continue learning