Article

Control Statements in C


In C, control statements are used to control the flow of program execution based on certain conditions or loops. These statements allow you to make decisions and repeat actions in your code.Here are some of the key control statements in C:

1.Conditional Statements:
  • if Statement: It is used to execute a block of code if a specified condition is true.
    
    if (condition) {
        // Code to be executed if the condition is true
    }
    
    
    
  • if-else Statement: It allows you to execute one block of code if the condition is true and another block if it's false.
    
    if (condition) {
        // Code to be executed if the condition is true
    } else {
        // Code to be executed if the condition is false
    }
    
    
    
  • else-if Ladder: You can use multiple else if conditions to handle multiple possibilities
    
    if (condition1) {
        // Code to be executed if condition1 is true
    } else if (condition2) {
        // Code to be executed if condition2 is true
    } else {
        // Code to be executed if no condition is true
    }
    
    
    
2.Switch Statement: The switch statement allows you to select one of many code blocks to be executed.

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
}


3.Looping Statements:
  • for Loop: It is used for executing a block of code a specific number of times.
    
    for (initialization; condition; increment/decrement) {
        // Code to be executed in each iteration
    }
    
    
    
  • while Loop: It executes a block of code as long as a specified condition is true.
    
    while (condition) {
        // Code to be executed while the condition is true
    }
    
    
    
    
  • do-while Loop: Similar to the while loop but ensures that the code block is executed at least once, as the condition is checked after the code block.
    
    do {
        // Code to be executed at least once
    } while (condition);
    
    
    
Jump Statements:
  • break: Used to exit a loop prematurely.
  • continue: Used to skip the current iteration of a loop and continue to the next iteration.
  • return: Used to exit a function and return a value.