Implement Conditionals In C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to implement conditional statements in C programming. You will start by introducing the basic syntax of if, else if, and else statements, and then write a simple if statement for comparing two numbers. You will also explore using else if for multiple conditions and learn how to compile and test your programs with various inputs.

The lab covers the fundamental concepts of conditional logic, which are essential for building decision-making functionality in your C programs. By the end of this lab, you will have a solid understanding of how to use conditional statements to control the flow of your code based on different conditions.


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`") c/BasicsGroup -.-> c/variables("`Variables`") subgraph Lab Skills c/output -.-> lab-438331{{"`Implement Conditionals In C`"}} c/operators -.-> lab-438331{{"`Implement Conditionals In C`"}} c/if_else -.-> lab-438331{{"`Implement Conditionals In C`"}} c/user_input -.-> lab-438331{{"`Implement Conditionals In C`"}} c/variables -.-> lab-438331{{"`Implement Conditionals In C`"}} end

Understanding If Syntax (if, else if, else)

In the world of programming, making decisions is a crucial skill, and conditional statements are the key to achieving this. In this step, we'll dive deep into the fundamental concept of conditional statements in C programming using if, else if, and else syntax. These powerful tools allow your program to dynamically respond to different situations, much like a decision-making flowchart.

What is an If Statement?

An if statement is essentially a logical checkpoint in your code. It evaluates a condition inside parentheses (). Think of it as a gatekeeper that decides whether a specific block of code should be executed. If the condition is true, the code block inside the curly braces {} will run; if the condition is false, the entire block is skipped, allowing the program to move to the next set of instructions.

Basic If Syntax

Here's the basic syntax of an if statement:

if (condition) {
    // code to execute if condition is true
}

This simple structure forms the foundation of decision-making in programming. The condition can be any expression that evaluates to true or false, such as comparisons, logical operations, or boolean checks.

Adding Else If and Else

As programs become more complex, you'll often need to handle multiple possible scenarios. This is where else if and else come into play, allowing you to create more sophisticated decision trees.

if (condition1) {
    // code to execute if condition1 is true
} else if (condition2) {
    // code to execute if condition2 is true
} else {
    // code to execute if none of the above conditions are true
}

This structure lets you chain multiple conditions, with the else serving as a catch-all for any scenarios not covered by previous conditions.

Example Program

Let's create a simple program to demonstrate conditional logic. Create a new file called conditions.c and add the following code:

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

int main() {
    int score = 75;

    if (score >= 90) {
        printf("Grade: A\n");
    } else if (score >= 80) {
        printf("Grade: B\n");
    } else if (score >= 70) {
        printf("Grade: C\n");
    } else if (score >= 60) {
        printf("Grade: D\n");
    } else {
        printf("Grade: F\n");
    }

    return 0;
}

Explanation

This program demonstrates a classic grading system scenario. Let's break down what's happening:

  • int score = 75; creates a variable to store a student's numeric score.
  • Each if and else if statement checks the score against different grade thresholds.
  • The conditions are evaluated in order, from highest to lowest.
  • The first true condition determines the grade that will be printed.
  • If no conditions are true, the else block ensures a default grade is assigned.

Compiling and Running the Program

To compile and run the program, use the following commands in your terminal:

gcc conditions.c -o conditions
./conditions

Example output:

Grade: C

Experiment by changing the score value to explore how the output changes:

  • Set score = 95 to get an "A".
  • Set score = 85 to get a "B".
  • Set score = 55 to get an "F".

This hands-on approach will help you understand how conditional statements control program flow and make decisions based on different input values.

Write A Simple If Statement For Comparison

In this step, we'll explore how to create a simple comparison program using if statements in C. We'll write a program that compares two numbers and provides different outputs based on their relationship.

Programming is all about logic and decision-making. Just like in real life, where we make choices based on certain conditions, in programming, we use conditional statements to guide the flow of our code.

Open the WebIDE and create a new file called number_compare.c in the ~/project directory. Here's a program that demonstrates number comparison:

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

int main() {
    int a = 10;
    int b = 20;

    if (a < b) {
        printf("%d is less than %d\n", a, b);
    }

    if (a == b) {
        printf("%d is equal to %d\n", a, b);
    }

    if (a > b) {
        printf("%d is greater than %d\n", a, b);
    }

    return 0;
}

When writing conditional statements, we use comparison operators to evaluate relationships between values. These operators are the language of comparison in programming, allowing us to make logical decisions.

Let's break down the comparison operators:

  • < means "less than"
  • == means "equal to"
  • > means "greater than"

These operators act like logical judges, comparing two values and determining their relationship. When the condition inside the if statement is true, the code block is executed.

Compile and run the program:

gcc number_compare.c -o number_compare
./number_compare

Example output:

10 is less than 20

Understanding how comparisons work is crucial in programming. By changing the values and experimenting with different conditions, you'll develop a deeper insight into how programs make decisions.

Try modifying the values of a and b to see different comparison results:

  • Change a = 20 and b = 10 to see when a > b
  • Set a = b to see the equal comparison
  • Experiment with different numbers to understand how comparisons work

As you become more comfortable with basic comparisons, you'll discover more complex comparison operators that provide even more flexibility:

  • <= (less than or equal to)
  • >= (greater than or equal to)
  • != (not equal to)

These operators expand your ability to create more nuanced and sophisticated decision-making logic in your programs. Each comparison is like a small test that determines which path your code will take, making your programs more dynamic and responsive.

Add Else Clause For Alternate Flow

The else statement provides a powerful way to handle cases that don't match the primary condition, essentially creating a fallback or default behavior for your program. This mechanism ensures that your code can respond intelligently to various scenarios.

Create a new file called age_check.c in the WebIDE. Here's a program that demonstrates the use of if-else:

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

int main() {
    int age = 16;

    if (age >= 18) {
        printf("You are an adult and can vote.\n");
    } else {
        printf("You are a minor and cannot vote yet.\n");
    }

    return 0;
}

Let's break down the code in detail:

  • if (age >= 18) checks if the age is 18 or older
  • If the condition is true, it prints the first message
  • else catches all cases where the condition is false
  • In this example, it prints a message for people under 18

When working with conditional statements, think of them as decision points in your program. The if statement checks a condition, and the else clause provides an alternative path when that condition is not met.

Compile and run the program:

gcc age_check.c -o age_check
./age_check

Example output:

You are a minor and cannot vote yet.

Try changing the age value:

  • Set age = 20 to see the "adult" message
  • Set age = 16 to see the "minor" message

Experimenting with different values helps you understand how conditional logic works in practice.

You can also create more complex conditions with else if, which allows multiple condition checks:

#include <stdio.h>

int main() {
    int temperature = 25;

    if (temperature < 0) {
        printf("It's freezing outside!\n");
    } else if (temperature < 10) {
        printf("It's cold today.\n");
    } else if (temperature < 20) {
        printf("The weather is mild.\n");
    } else {
        printf("It's warm outside.\n");
    }

    return 0;
}

This example demonstrates how else if can create multiple condition checks with a final else as a catch-all. Each condition is evaluated in order, and the first true condition's block of code is executed. The final else serves as a default case when no previous conditions are met.

Use Else If For Multiple Conditions

In this step, we'll explore how to use else if to handle multiple conditions in a more sophisticated scenario. This approach allows you to create more nuanced decision-making logic in your programs, moving beyond simple binary choices.

Create a new file called grade_calculator.c in the WebIDE. Here's a program that demonstrates multiple conditions using else if:

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

int main() {
    int score = 85;

    if (score >= 90) {
        printf("Excellent! Your grade is A.\n");
    } else if (score >= 80) {
        printf("Great job! Your grade is B.\n");
    } else if (score >= 70) {
        printf("Good work. Your grade is C.\n");
    } else if (score >= 60) {
        printf("You passed. Your grade is D.\n");
    } else {
        printf("Sorry, you failed. Your grade is F.\n");
    }

    return 0;
}

Let's break down the code and understand how else if works:

  • Each else if creates an additional condition to check
  • Conditions are evaluated from top to bottom in a sequential manner
  • The first true condition's block will be executed, and subsequent conditions are skipped
  • The final else serves as a catch-all for any value that doesn't meet the previous conditions

This approach is similar to how we make decisions in real life, checking multiple possibilities until we find the right match. In this example, the grade calculation demonstrates a typical use of nested conditional logic.

Compile and run the program:

gcc grade_calculator.c -o grade_calculator
./grade_calculator

Example output:

Great job! Your grade is B.

You can experiment with different scenarios by changing the score value:

  • Set score = 95 to get an "A"
  • Set score = 75 to get a "C"
  • Set score = 55 to get an "F"

Here's another example that shows how else if can be used for more complex logical scenarios:

#include <stdio.h>

int main() {
    int temperature = 25;

    if (temperature < 0) {
        printf("Freezing cold!\n");
    } else if (temperature < 10) {
        printf("Very cold\n");
    } else if (temperature < 20) {
        printf("Cool\n");
    } else if (temperature < 30) {
        printf("Warm\n");
    } else {
        printf("Hot!\n");
    }

    return 0;
}

This second example illustrates how you can create precise ranges using else if statements, breaking down a continuous scale into discrete categories. By using carefully defined conditions, you can create sophisticated decision-making structures that respond intelligently to different input values.

Nested If Statements

When writing programs that need to evaluate multiple conditions, you'll often find that a single if statement isn't enough to capture the full complexity of your decision-making process. This is where nested if statements become incredibly useful, allowing you to create layers of conditional logic that can handle intricate scenarios.

What is a Nested If Statement?

A nested if statement is essentially an if statement placed inside another if or else block. Think of it like a series of decision-making checkpoints, where each subsequent condition is only evaluated if the previous condition is true. This approach allows for more granular and precise control over your program's flow.

Example Program

Let's create a program that uses nested if statements to determine the category of a person based on their age and whether they are a student. Create a new file called nested_conditions.c and add the following code:

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

int main() {
    int age;
    char is_student;

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

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

    if (age < 18) {
        if (is_student == 'y') {
            printf("You are a minor and a student.\n");
        } else {
            printf("You are a minor and not a student.\n");
        }
    } else {
        if (is_student == 'y') {
            printf("You are an adult and a student.\n");
        } else {
            printf("You are an adult and not a student.\n");
        }
    }

    return 0;
}

Explanation

In this program, we're demonstrating how nested if statements can help us create more sophisticated decision trees. Let's break down the key components:

  • int age; and char is_student; declare variables to store the user's age and student status.
  • scanf("%d", &age); prompts the user to input their age and stores it in the age variable.
  • scanf(" %c", &is_student); reads the user's student status. The space before %c is a crucial detail that prevents input buffer issues.
  • The outer if statement first checks whether the user is under 18, creating our primary decision branch.
  • The inner if statements then further refine the categorization based on student status within each age group.

Compiling and Running the Program

To compile and run the program, use the following commands in your terminal:

gcc nested_conditions.c -o nested_conditions
./nested_conditions

Example output:

Enter your age: 17
Are you a student? (y/n): y
You are a minor and a student.

This program demonstrates the power of nested if statements. By experimenting with different inputs, you'll see how the program dynamically adjusts its output:

  • Enter age 20 and student status 'y' to see the "adult and a student" message.
  • Enter age 15 and student status 'n' to see the "minor and not a student" message.

Each combination of inputs triggers a different path through the nested conditional structure, showcasing the flexibility and precision of this programming technique.

Summary

In this lab, you learned about conditional statements in C programming using the if, else if, and else syntax. You started by introducing the basic structure of conditional statements, which allow your program to make decisions and execute different code blocks based on specific conditions. You then wrote a simple if statement to compare two numbers and provide different outputs based on their relationship. Finally, you explored using else if to handle multiple conditions in sequence and the else block to catch any values that don't meet previous conditions. The key concepts covered in this lab include understanding the syntax of conditional statements, writing simple comparisons, and using else if and else to create more complex decision-making logic in your C programs.

Other C Tutorials you may like