Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Control Statements in C

In C programming, control statements are used to alter the flow of execution in a program based on certain conditions or to repeat a set of statements.

The commonly used control statements in C are:

If-else statement:

  • The if-else statement is used to make a decision based on a condition.
  • If the condition is true, the statements within the if block are executed; otherwise, the statements within the else block (optional) are executed.
C
if (condition) {
    // code to execute if condition is true
} else {
    // code to execute if condition is false
}

Switch statement:

  • The switch statement is used to select one of many code blocks to be executed based on the value of an expression.
  • It provides an alternative to a long sequence of if-else if-else statements.
C
switch (expression) {
    case constant1:
        // code to execute if expression matches constant1
        break;
    case constant2:
        // code to execute if expression matches constant2
        break;
    // ...
    default:
        // code to execute if no case matches the expression
}

Loops:

Loops are used to repeat a set of statements until a specific condition is met.

The commonly used loops in C are:

for loop:

Executes a block of code repeatedly based on an initialization, condition, and increment/decrement.

C
for (initialization; condition; increment/decrement) {
    // code to execute repeatedly
}

while loop:

Repeats a block of code as long as the condition is true.

C
while (condition) {
    // code to execute repeatedly
}

do-while loop:

Executes a block of code first and then repeats it as long as the condition is true.

C
do {
    // code to execute repeatedly
} while (condition);

Jump statements:

Jump statements are used to transfer control within a program to a different section of code.

The commonly used jump statements in C are:

break statement:

Terminates the current loop or switch statement and transfers control to the statement immediately following the loop or switch.

continue statement:

Skips the remaining code within the loop for the current iteration and proceeds to the next iteration.

goto statement:

Transfers control to a labeled statement within the same function. (Note: goto should be used with caution as it can make code harder to read and maintain.)