University of Petroleum and Energy Studies (UPES)

School of Computer Science | Cloud & Software Operations Cluster

Instructor: Dr. Mohsin Dar

C Programming - Lecture 8

Conditional Statements

Topics Covered:

  • ✓ if statement
  • ✓ if-else statement
  • ✓ if-else if-else statement
  • ✓ Nested if-else statements

Learning Objectives

By the end of this lecture, students will be able to:

What are Conditional Statements?

Conditional statements allow programs to make decisions based on certain conditions. They enable the program to execute different blocks of code depending on whether a condition is true or false.

Decision Making Flow

Condition → Evaluation → Action

Example: "If it's raining, take an umbrella; otherwise, don't."

Key Point: Conditional statements are fundamental to programming logic and enable programs to respond intelligently to different situations.

The if Statement

The simplest form of conditional statement. It executes a block of code only if a condition is true.

Syntax:

if (condition) {
    // Code to execute if condition is true
    statement1;
    statement2;
    // ...
}

Example: Checking Age for Voting

#include <stdio.h>

int main() {
    int age = 20;
    
    if (age >= 18) {
        printf("You are eligible to vote!\n");
    }
    
    printf("Program continues...\n");
    return 0;
}

Output: You are eligible to vote!
Program continues...

if Statement Flowchart

Execution Flow of if Statement

Start

Evaluate Condition

True

Execute if block
False

Skip if block

Continue with next statement

End

The if-else Statement

Provides an alternative path of execution when the condition is false.

Syntax:

if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}

Example: Even or Odd Number

#include <stdio.h>

int main() {
    int number = 15;
    
    if (number % 2 == 0) {
        printf("%d is an even number.\n", number);
    } else {
        printf("%d is an odd number.\n", number);
    }
    
    return 0;
}

Output: 15 is an odd number.

The if-else if-else Statement

Used when you need to check multiple conditions in sequence.

Syntax:

if (condition1) {
    // Code for condition1 = true
} else if (condition2) {
    // Code for condition2 = true
} else if (condition3) {
    // Code for condition3 = true
} else {
    // Code when all conditions are false
}

Example: Grade Classification

#include <stdio.h>

int main() {
    int marks = 85;
    
    if (marks >= 90) {
        printf("Grade: A+\n");
    } else if (marks >= 80) {
        printf("Grade: A\n");
    } else if (marks >= 70) {
        printf("Grade: B\n");
    } else if (marks >= 60) {
        printf("Grade: C\n");
    } else {
        printf("Grade: F\n");
    }
    
    return 0;
}

Output: Grade: A

Nested if-else Statements

An if-else statement inside another if-else statement. Useful for complex decision-making scenarios.

Syntax:

if (condition1) {
    if (condition2) {
        // Code when both condition1 and condition2 are true
    } else {
        // Code when condition1 is true but condition2 is false
    }
} else {
    // Code when condition1 is false
}

Example: Eligibility for Driving License

#include <stdio.h>

int main() {
    int age = 20;
    char hasLicense = 'N';
    
    if (age >= 18) {
        printf("Age requirement met.\n");
        if (hasLicense == 'Y') {
            printf("You can drive legally!\n");
        } else {
            printf("You need to get a license first.\n");
        }
    } else {
        printf("You are too young to drive.\n");
    }
    
    return 0;
}

Output: Age requirement met.
You need to get a license first.

Comparison of Conditional Statements

Statement Type Use Case Number of Conditions Example Scenario
if Single condition check 1 Check if student passed
if-else Binary decision 1 (with alternative) Pass or Fail
if-else if-else Multiple exclusive conditions Multiple Grade classification
Nested if-else Dependent conditions Hierarchical Age and license check

Comprehensive Example: Student Admission System

Problem: Determine admission eligibility based on multiple criteria

#include <stdio.h>

int main() {
    int mathMarks = 85, scienceMarks = 78, englishMarks = 88;
    float percentage;
    char category = 'G'; // G = General, S = SC/ST
    
    percentage = (mathMarks + scienceMarks + englishMarks) / 3.0;
    
    printf("Student's Percentage: %.2f%%\n", percentage);
    
    if (percentage >= 60) {
        printf("Basic eligibility: MET\n");
        
        if (category == 'G') {
            if (percentage >= 85) {
                printf("Admission Status: CONFIRMED (General Category)\n");
            } else if (percentage >= 75) {
                printf("Admission Status: WAITLISTED (General Category)\n");
            } else {
                printf("Admission Status: REJECTED (General Category)\n");
            }
        } else if (category == 'S') {
            if (percentage >= 70) {
                printf("Admission Status: CONFIRMED (Reserved Category)\n");
            } else {
                printf("Admission Status: WAITLISTED (Reserved Category)\n");
            }
        }
    } else {
        printf("Basic eligibility: NOT MET\n");
        printf("Admission Status: REJECTED (Minimum criteria not satisfied)\n");
    }
    
    return 0;
}

Best Practices for Conditional Statements

1. Code Readability

// Good Practice - Clear and readable
if (temperature > 30) {
    printf("It's hot outside!\n");
}

// Avoid - Unclear condition
if (t > 30) {
    printf("It's hot outside!\n");
}

2. Proper Indentation

// Good Practice
if (score >= 90) {
    if (attendance >= 80) {
        printf("Excellent performance!\n");
    }
}

// Poor Practice
if(score>=90){
if(attendance>=80){
printf("Excellent performance!\n");
}
}

3. Use Braces Even for Single Statements

// Recommended
if (x > 0) {
    printf("Positive number\n");
}

// Can lead to errors later
if (x > 0)
    printf("Positive number\n");

Common Errors and How to Avoid Them

1. Assignment vs. Comparison

// WRONG - Assignment instead of comparison
if (x = 5) {  // This assigns 5 to x, doesn't compare!
    printf("x is 5\n");
}

// CORRECT - Comparison operator
if (x == 5) {
    printf("x is 5\n");
}

2. Missing Braces

// PROBLEMATIC - Only first statement is in if block
if (x > 0)
    printf("Positive\n");
    printf("This always executes!\n");

// CORRECT - Use braces
if (x > 0) {
    printf("Positive\n");
    printf("This is also in the if block\n");
}

3. Dangling else Problem

// AMBIGUOUS - Which if does the else belong to?
if (x > 0)
    if (y > 0)
        printf("Both positive\n");
else  // This belongs to inner if, not outer!
    printf("x is not positive\n");

// CLEAR - Use braces to clarify
if (x > 0) {
    if (y > 0) {
        printf("Both positive\n");
    }
} else {
    printf("x is not positive\n");
}

Practice Problems

Problem 1: Temperature Classification

Write a program to classify temperature as:

  • Freezing: below 0°C
  • Cold: 0-10°C
  • Cool: 11-20°C
  • Warm: 21-30°C
  • Hot: above 30°C

Problem 2: Leap Year Calculator

A year is a leap year if:

  • It's divisible by 4, AND
  • If it's divisible by 100, it must also be divisible by 400

Examples: 2000 (leap), 1900 (not leap), 2024 (leap)

Problem 3: Simple Calculator

Create a calculator that takes two numbers and an operator (+, -, *, /) and performs the corresponding operation using nested if-else statements.

Summary

Key Concepts Covered:

  • if statement: Execute code when condition is true
  • if-else statement: Choose between two alternatives
  • if-else if-else: Handle multiple exclusive conditions
  • Nested if-else: Handle complex, dependent conditions

Remember:

  • Use proper indentation and braces
  • Be careful with assignment (=) vs comparison (==)
  • Test all possible paths in your conditional logic
  • Choose the right conditional structure for your problem
Next Lecture: Looping Statements (for, while, do-while)

Thank You!

Questions & Discussion

Dr. Mohsin Dar

Assistant Professor

Cloud & Software Operations Cluster | SOCS | UPES

Office Hours: Available for doubts and clarifications

1 / 15