Decision Making Structures in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to build decision-making structures in C programming. You will start by understanding the fundamental concept of the if statement, which allows your program to make decisions based on specific conditions. You will then explore inequality operators, chain if-else statements, combine expressions with logical operators, and practice conditional logic. By the end of this lab, you will have a solid understanding of how to create decision-making structures in your C programs, enabling you to write more sophisticated and intelligent code.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/UserInteractionGroup -.-> c/user_input("`User Input`") subgraph Lab Skills c/output -.-> lab-438255{{"`Decision Making Structures in C`"}} c/operators -.-> lab-438255{{"`Decision Making Structures in C`"}} c/if_else -.-> lab-438255{{"`Decision Making Structures in C`"}} c/user_input -.-> lab-438255{{"`Decision Making Structures in C`"}} end

Understand the If Statement

In this step, you'll learn about the fundamental concept of if statements in C programming, which are crucial for creating decision-making structures in your code. If statements allow your program to make decisions and execute different code blocks based on specific conditions.

Let's start by creating a simple C program that demonstrates the basic if statement syntax. Open the VSCode editor and create a new file called if_statement.c in the ~/project directory:

cd ~/project
touch if_statement.c
#include <stdio.h>

int main() {
    int temperature = 25;

    if (temperature > 30) {
        printf("It's a hot day!\n");
    }

    if (temperature <= 30) {
        printf("The temperature is comfortable.\n");
    }

    return 0;
}

Compile and run the program:

gcc if_statement.c -o if_statement
./if_statement

Example output:

The temperature is comfortable.

Let's break down the if statement:

  • The if keyword is followed by a condition in parentheses ()
  • The condition is a logical expression that evaluates to true or false
  • If the condition is true, the code block inside the curly braces {} is executed
  • If the condition is false, the code block is skipped

Now, let's create a more interactive example that demonstrates how if statements can make decisions based on user input:

#include <stdio.h>

int main() {
    int age;

    printf("Enter your age: ");
    scanf("%d", &age);

    if (age >= 18) {
        printf("You are eligible to vote.\n");
    }

    if (age < 18) {
        printf("You are not old enough to vote.\n");
    }

    return 0;
}

Compile and run the program:

gcc voting_eligibility.c -o voting_eligibility
./voting_eligibility

Example output:

Enter your age: 20
You are eligible to vote.

Key points to remember:

  • If statements allow your program to make decisions
  • The condition is evaluated as true or false
  • Only the code block for the true condition will be executed
  • You can use comparison operators like >, <, >=, <=, ==, !=

Explore Inequality Operators

In this step, you'll dive deeper into C programming by exploring inequality operators, which are essential for creating more complex conditional statements. Inequality operators allow you to compare values and make decisions based on their relationships.

Let's create a new file called inequality_operators.c in the ~/project directory to demonstrate different inequality operators:

cd ~/project
touch inequality_operators.c
#include <stdio.h>

int main() {
    int x = 10;
    int y = 20;

    // Equal to (==) operator
    if (x == y) {
        printf("x is equal to y\n");
    } else {
        printf("x is not equal to y\n");
    }

    // Not equal to (!=) operator
    if (x != y) {
        printf("x is different from y\n");
    }

    // Greater than (>) operator
    if (y > x) {
        printf("y is greater than x\n");
    }

    // Less than (<) operator
    if (x < y) {
        printf("x is less than y\n");
    }

    // Greater than or equal to (>=) operator
    if (y >= x) {
        printf("y is greater than or equal to x\n");
    }

    // Less than or equal to (<=) operator
    if (x <= y) {
        printf("x is less than or equal to y\n");
    }

    return 0;
}

Compile and run the program:

gcc inequality_operators.c -o inequality_operators
./inequality_operators

Example output:

x is not equal to y
x is different from y
y is greater than x
x is less than y
y is greater than or equal to x
x is less than or equal to y

Let's create another example that demonstrates inequality operators with user input:

#include <stdio.h>

int main() {
    int score;

    printf("Enter your exam score: ");
    scanf("%d", &score);

    if (score >= 90) {
        printf("Excellent! You got an A.\n");
    } else if (score >= 80) {
        printf("Good job! You got a B.\n");
    } else if (score >= 70) {
        printf("Not bad. You got a C.\n");
    } else if (score >= 60) {
        printf("You passed. You got a D.\n");
    } else {
        printf("Sorry, you failed the exam.\n");
    }

    return 0;
}

Compile and run the program:

gcc grade_calculator.c -o grade_calculator
./grade_calculator

Example output:

Enter your exam score: 85
Good job! You got a B.

Key points to remember:

  • Inequality operators help compare values
  • == checks if values are equal
  • != checks if values are not equal
  • > checks if the left value is greater than the right value
  • < checks if the left value is less than the right value
  • >= checks if the left value is greater than or equal to the right value
  • <= checks if the left value is less than or equal to the right value

Chain If-Else Statements

In this step, you'll learn how to chain if-else statements to create more complex decision-making structures in C programming. Chaining if-else statements allows you to handle multiple conditions and provide alternative code paths when previous conditions are not met.

Let's create a file called weather_advisor.c in the ~/project directory to demonstrate chained if-else statements:

cd ~/project
touch weather_advisor.c
#include <stdio.h>

int main() {
    int temperature;
    char weather_type;

    printf("Enter the temperature: ");
    scanf("%d", &temperature);

    printf("Enter the weather type (S for sunny, R for rainy, C for cloudy): ");
    scanf(" %c", &weather_type);

    if (temperature > 30 && weather_type == 'S') {
        printf("It's a hot and sunny day. Stay hydrated and use sunscreen!\n");
    } else if (temperature > 30 && weather_type == 'R') {
        printf("It's hot and rainy. Be careful of potential thunderstorms.\n");
    } else if (temperature > 30 && weather_type == 'C') {
        printf("It's hot and cloudy. Wear light clothing.\n");
    } else if (temperature >= 20 && temperature <= 30) {
        printf("The temperature is comfortable.\n");
    } else if (temperature < 20) {
        printf("It's a bit cool today. Consider wearing a light jacket.\n");
    } else {
        printf("Invalid input. Please check your temperature and weather type.\n");
    }

    return 0;
}

Compile and run the program:

gcc weather_advisor.c -o weather_advisor
./weather_advisor

Example output:

Enter the temperature: 35
Enter the weather type (S for sunny, R for rainy, C for cloudy): S
It's a hot and sunny day. Stay hydrated and use sunscreen!

Let's create another example that demonstrates a more practical use of chained if-else statements:

#include <stdio.h>

int main() {
    char category;
    double price, discount = 0.0;

    printf("Enter product category (A/B/C): ");
    scanf(" %c", &category);

    printf("Enter product price: ");
    scanf("%lf", &price);

    if (category == 'A') {
        if (price > 1000) {
            discount = 0.2;  // 20% discount for high-value A category
        } else {
            discount = 0.1;  // 10% discount for A category
        }
    } else if (category == 'B') {
        if (price > 500) {
            discount = 0.15;  // 15% discount for high-value B category
        } else {
            discount = 0.05;  // 5% discount for B category
        }
    } else if (category == 'C') {
        if (price > 200) {
            discount = 0.1;  // 10% discount for high-value C category
        } else {
            discount = 0.0;  // No discount for low-value C category
        }
    } else {
        printf("Invalid category!\n");
        return 1;
    }

    double discounted_price = price * (1 - discount);
    printf("Original price: $%.2f\n", price);
    printf("Discount: %.0f%%\n", discount * 100);
    printf("Discounted price: $%.2f\n", discounted_price);

    return 0;
}

Compile and run the program:

gcc discount_calculator.c -o discount_calculator
./discount_calculator

Example output:

Enter product category (A/B/C): B
Enter product price: 600
Original price: $600.00
Discount: 15%
Discounted price: $510.00

Key points to remember:

  • Chained if-else statements allow you to handle multiple conditions
  • Each condition is checked in order from top to bottom
  • Only the first matching condition's code block is executed
  • The else block provides a default action if no previous conditions are met
  • You can nest if-else statements to create more complex decision structures

Combine Expressions with Logical Operators

In this step, you'll learn how to combine multiple conditions using logical operators in C programming. Logical operators allow you to create more complex conditional statements by connecting multiple expressions.

Let's create a file called logical_operators.c in the ~/project directory to demonstrate the three main logical operators: AND (&&), OR (||), and NOT (!):

cd ~/project
touch logical_operators.c
#include <stdio.h>

int main() {
    int age, income;
    char is_student;

    printf("Enter your age: ");
    scanf("%d", &age);

    printf("Enter your annual income: ");
    scanf("%d", &income);

    printf("Are you a student? (Y/N): ");
    scanf(" %c", &is_student);

    // AND (&&) operator: Both conditions must be true
    if (age >= 18 && income < 30000) {
        printf("You qualify for a basic credit card.\n");
    }

    // OR (||) operator: At least one condition must be true
    if (age < 25 || is_student == 'Y') {
        printf("You may be eligible for a student discount.\n");
    }

    // Combining multiple conditions
    if ((age >= 18 && income >= 30000) || (is_student == 'Y')) {
        printf("You qualify for a premium credit card.\n");
    }

    // NOT (!) operator: Negates the condition
    if (!(age < 18)) {
        printf("You are an adult.\n");
    }

    return 0;
}

Compile and run the program:

gcc logical_operators.c -o logical_operators
./logical_operators

Example output:

Enter your age: 22
Enter your annual income: 25000
Are you a student? (Y/N): Y
You qualify for a basic credit card.
You may be eligible for a student discount.
You qualify for a premium credit card.
You are an adult.

Let's create another example that demonstrates more complex logical conditions:

#include <stdio.h>

int main() {
    char membership_type;
    int visits_per_month, total_spending;

    printf("Enter your membership type (B for Bronze, S for Silver, G for Gold): ");
    scanf(" %c", &membership_type);

    printf("Enter number of visits per month: ");
    scanf("%d", &visits_per_month);

    printf("Enter total monthly spending: ");
    scanf("%d", &total_spending);

    // Complex condition using multiple logical operators
    if ((membership_type == 'G') ||
        (membership_type == 'S' && visits_per_month >= 10) ||
        (membership_type == 'B' && total_spending > 500)) {
        printf("You are eligible for a special promotion!\n");
    }

    // Demonstrating NOT operator with complex conditions
    if (!(membership_type == 'B' && visits_per_month < 5)) {
        printf("You can access additional membership benefits.\n");
    }

    return 0;
}

Compile and run the program:

gcc membership_conditions.c -o membership_conditions
./membership_conditions

Example output:

Enter your membership type (B for Bronze, S for Silver, G for Gold): S
Enter number of visits per month: 12
Enter total monthly spending: 300
You are eligible for a special promotion!
You can access additional membership benefits.

Key points to remember:

  • && (AND) operator: Both conditions must be true
  • || (OR) operator: At least one condition must be true
  • ! (NOT) operator: Negates the condition
  • You can combine multiple conditions to create complex logic
  • Parentheses can help clarify the order of evaluation

Practice Conditional Logic

In this final step, you'll apply everything you've learned about decision-making structures in C by creating a comprehensive program that demonstrates multiple conditional logic techniques.

Let's create a multi-purpose program called personal_finance_advisor.c in the ~/project directory that will help users make financial decisions:

cd ~/project
touch personal_finance_advisor.c
#include <stdio.h>

int main() {
    double income, expenses, savings;
    char employment_status, age_group;

    // Input financial information
    printf("Enter your monthly income: $");
    scanf("%lf", &income);

    printf("Enter your monthly expenses: $");
    scanf("%lf", &expenses);

    printf("Enter your current savings: $");
    scanf("%lf", &savings);

    printf("Employment status (F for Full-time, P for Part-time, U for Unemployed): ");
    scanf(" %c", &employment_status);

    printf("Age group (Y for Young (18-35), M for Middle-aged (36-55), S for Senior (56+)): ");
    scanf(" %c", &age_group);

    // Calculate savings rate
    double savings_rate = (savings / income) * 100;
    double disposable_income = income - expenses;

    // Financial advice using complex conditional logic
    printf("\n--- Financial Analysis ---\n");

    // Savings advice
    if (savings_rate < 10) {
        printf("Warning: Your savings rate is low (%.2f%%).\n", savings_rate);
    } else if (savings_rate >= 10 && savings_rate < 20) {
        printf("Good start! Your savings rate is moderate (%.2f%%).\n", savings_rate);
    } else {
        printf("Excellent! Your savings rate is strong (%.2f%%).\n", savings_rate);
    }

    // Investment recommendations
    if ((employment_status == 'F' && disposable_income > 500) ||
        (age_group == 'Y' && savings > 5000)) {
        printf("Recommendation: Consider starting an investment portfolio.\n");
    }

    // Emergency fund advice
    if (savings < (expenses * 3)) {
        printf("Advice: Build an emergency fund covering at least 3 months of expenses.\n");
    }

    // Spending control
    if (expenses > (income * 0.7)) {
        printf("Alert: Your expenses are too high compared to your income.\n");
    }

    // Special conditions
    if ((age_group == 'Y' && employment_status == 'F') ||
        (savings > (income * 2))) {
        printf("You are in a good financial position!\n");
    }

    // Detailed financial health assessment
    if (!(disposable_income < 0)) {
        printf("Your disposable income is: $%.2f\n", disposable_income);
    } else {
        printf("Warning: Your expenses exceed your income.\n");
    }

    return 0;
}

Compile and run the program:

gcc personal_finance_advisor.c -o personal_finance_advisor
./personal_finance_advisor

Example output:

Enter your monthly income: $5000
Enter your monthly expenses: $3500
Enter your current savings: $10000
Employment status (F for Full-time, P for Part-time, U for Unemployed): F
Age group (Y for Young (18-35), M for Middle-aged (36-55), S for Senior (56+)): Y

--- Financial Analysis ---
Good start! Your savings rate is moderate (40.00%).
Recommendation: Consider starting an investment portfolio.
You are in a good financial position!
Your disposable income is: $1500.00

Let's create a bonus challenge program to further practice conditional logic:

#include <stdio.h>

int main() {
    int math_score, science_score, english_score;
    char extra_credit;

    printf("Enter Math score (0-100): ");
    scanf("%d", &math_score);

    printf("Enter Science score (0-100): ");
    scanf("%d", &science_score);

    printf("Enter English score (0-100): ");
    scanf("%d", &english_score);

    printf("Did you complete extra credit? (Y/N): ");
    scanf(" %c", &extra_credit);

    // Calculate average
    double average = (math_score + science_score + english_score) / 3.0;

    // Comprehensive grade determination
    if (average >= 90 ||
        (extra_credit == 'Y' && average >= 85)) {
        printf("Congratulations! You earned an A grade.\n");
    } else if (average >= 80 ||
               (extra_credit == 'Y' && average >= 75)) {
        printf("Great job! You earned a B grade.\n");
    } else if (average >= 70 ||
               (extra_credit == 'Y' && average >= 65)) {
        printf("You passed. You earned a C grade.\n");
    } else {
        printf("You need to improve. Consider retaking the courses.\n");
    }

    return 0;
}

Compile and run the program:

gcc grade_calculator.c -o grade_calculator
./grade_calculator

Example output:

Enter Math score (0-100): 85
Enter Science score (0-100): 88
Enter English score (0-100): 92
Did you complete extra credit? (Y/N): N
Great job! You earned a B grade.

Key points to remember:

  • Combine multiple conditions using logical operators
  • Use nested if-else statements for complex decision-making
  • Consider edge cases and provide comprehensive logic
  • Break down complex problems into smaller, manageable conditions

Summary

In this lab, you learned about the fundamental concept of if statements in C programming, which are crucial for creating decision-making structures in your code. You explored how if statements allow your program to make decisions and execute different code blocks based on specific conditions. You also learned about inequality operators, chaining if-else statements, combining expressions with logical operators, and practicing conditional logic to build more complex decision-making structures in your C programs.

The key points covered in this lab include understanding the basic syntax of if statements, evaluating logical expressions as true or false, and executing the appropriate code block based on the condition. You also learned how to use if statements to make decisions based on user input, which is an essential skill for building interactive applications.

Other C Tutorials you may like