Control Statement

In C programming, control statements are used to control the flow of execution in a program. They allow you to make decisions, repeat a block of code multiple times, and alter the sequential order of code execution. Control statements help you write programs that can respond dynamically to different situations.

There are three main types of control statements in C and Conditional Statements one of them.

Conditional Statements

Conditional statements in C are used to execute different blocks of code based on specified conditions. There are two main types of conditional statements in C: the if statement and the switch statement.

1. if statement:

The if statement allows you to execute a block of code if a specified condition is true. It can be followed by an optional else statement to execute a different block of code when the condition is false.

Syntax

if (condition) {
    // code to be executed if the condition is true
} else {
    // code to be executed if the condition is false
}

Example

int num = 10;
if (num > 5) {
    printf("The number is greater than 5.\n");
} else {
    printf("The number is less than or equal to 5.\n");
}

2. switch statement

The switch statement allows you to select one of many code blocks to execute based on the value of an expression. It provides an alternative to multiple if statements.

switch (expression) {
    case constant1:
        // code to be executed if expression equals constant1
        break;
    case constant2:
        // code to be executed if expression equals constant2
        break;
    // more cases...
    default:
        // code to be executed if expression doesn't match any case
}

Example

char grade = 'B';
switch (grade) {
    case 'A':
        printf("Excellent!\n");
        break;
    case 'B':
        printf("Good!\n");
        break;
    case 'C':
        printf("Fair!\n");
        break;
    default:
        printf("Invalid grade!\n");
}

In the switch statement, the expression is evaluated, and the code block corresponding to the matching case is executed. If no case matches, the code block under default is executed (optional).

Both if and switch statements provide a way to make decisions and control the flow of execution in a program based on specific conditions. They are fundamental constructs in C programming and enable you to create flexible and responsive programs.