Thursday, March 06, 2025

The Guide to Control Structures If, If-Else, and Switch-Case in C Programming

In the C programming language, control structures such as if, if-else, and else allow programmers to make decisions during program execution. These structures are used to branch the flow of execution based on specific conditions. In programming, control structures enable the management of program execution flow. They determine which parts of the code will be executed and under what conditions. By using if, if-else, and if-else if-else structures, programmers can write flexible programs that make decisions based on various conditions. Proper use of these control structures enables efficient management of the program execution flow and increases code readability.

if statement

The if statement is used to check a specific condition. If the condition is true, the block of code within the if statement is executed. If the condition is not true, that block of code is skipped, and the program continues. if statements can be nested, meaning you can have another if within one if block.

if (condition) {

    // Executes if condition is true

}

Decision statements determine the flow of the program

Decision statements determine the flow of the program

if-else statement

The if-else statement extends if by adding an alternative block of code that is executed if the condition is not met. This allows the program to choose between two possibilities.

if (condition1) {

    // Executes if condition is true

} else {

    // Executes if none of the conditions are true

}

if-else if- else statement

When it is necessary to check multiple conditions, a combination of if with one or more else if parts, with an optional final else, is used. This allows the program to branch into multiple possible outcomes.

 

if (condition1) {

    // Executes if condition1 is true

} else if (condition2) {

    // Executes if condition1 is false and condition2 is true

} else {

    // Executes if none of the conditions are true

}

What Are the Differences in If Statements Between the C Programming Language and Others?

Although the basic idea of if, else if, else is the same in all languages – condition checking and branching – the differences lie in syntax, the way code blocks are defined, and condition evaluation. C programming language is specific for its strictness and numerical logic, while languages like Python offer simpler syntax, and JavaScript and PHP offer flexibility with types. If you program in multiple languages, it's important to adapt to these subtle differences.

Key differences between if statements in different programming languages

Key differences between if statements in different programming languages

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir if_else_statement

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd if_else_statement

manuel@manuel-virtual-machine:/tutorials/c_tutorial/if_else_statement$ code .

Create a file and name it ifstatement.c, then type the following code.

#include <stdio.h>

int main() {

    int age;


    // Prompt the user to enter their age

    printf("Please enter your age: ");

    scanf("%d", &age);

 

    // Check multiple conditions about the age

    if (age >= 18) {

        printf("You are eligible to vote!\n");

    } else if (age >= 16) {

    printf("You can’t vote yet, but you can get a driver’s license!\n");

    } else {

        printf("Sorry, you’re too young for voting or driving.\n");

    }

    return 0;

}

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/if_else_statement

$ gcc ifstatement.c -o ifstatement

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/if_else_statement

$ ./ifstatement

Please enter your age: 21

You are eligible to vote!

You can also watch a video of how the program is coded.


C Tutorial – 16. How to Use the If-Else Statement in the C Programming Language

A Practical Example of Using the Switch-Case Statement

The switch-case statement allows checking the value of an expression and executing the corresponding block of code based on that value. It is used when there are multiple possible values for a single variable. It is often used as an alternative to multiple if-else if-else statements when checking the same variable against different constant values. With switch, the keywords case are used to define possible values, and default as the default case when no value matches.

switch-case statement

A characteristic of the switch-case statement is that switch can use int and char values, but does not support float and string. The break statement is used to exit the switch-case block after executing the corresponding case expression, while the default statement is executed if no case is satisfied. Although it has limitations because it only uses integer types, switch is a powerful tool when used correctly, especially in situations such as menus, character processing, or enumerations. The basic syntax of the switch statement looks like this:

switch (expression) {

    case value1:

        // Code block for value1

        break;

    case value2:

        // Code block for value2

        break;

    // There can be more case statements

    default:

        // Code block if no value matches

}

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir switch_case_statement

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd switch_case_statement

manuel@manuel-virtual-machine:/tutorials/c_tutorial/switch_case_statement$ code .

Create a file and name it switchstatement.c, then type the following code.

#include <stdio.h>

int main() {

    char operator;

    float num1, num2, result;

 

    // Prompt user for input

    printf("Enter first number: ");

    scanf("%f", &num1);

 

    printf("Enter an operator (+, -, *, /): ");

    scanf(" %c", &operator); // Space before %c to consume any leftover newline

 

    printf("Enter second number: ");

    scanf("%f", &num2);

 

    // Use switch to perform the operation based on the operator

    switch (operator) {

        case '+':

            result = num1 + num2;

            printf("%.2f + %.2f = %.2f\n", num1, num2, result);

            break; 

        case '-':

            result = num1 - num2;

            printf("%.2f - %.2f = %.2f\n", num1, num2, result);

            break;

        case '*':

            result = num1 * num2;

            printf("%.2f * %.2f = %.2f\n", num1, num2, result);

            break;

        case '/':

            if (num2 != 0) { // Check for division by zero

                result = num1 / num2;

                printf("%.2f / %.2f = %.2f\n", num1, num2, result);

            } else {

                printf("Error: Division by zero is not allowed!\n");

            }

            break;

        default:

            printf("Error: Invalid operator! Please use +, -, *, or /\n");

    }

    return 0;

}

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/swich_case_statement

$ gcc switchstatement.c -o switchstatement

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/swich_case_statement

$ ./switchstatement

Enter first number: 18

Enter an operator (+, -, *, /): *

Enter second number: 13

18.00 * 13.00 = 234.00

You can also watch a video of how the program is coded.


C Tutorial – 17. How to Use the Switch-Case Statement in the C Programming Language


 

 

 

 

 

 

 

No comments:

Post a Comment