C - If

In C, the if statement is a conditional statement used for decision-making in a program. It allows you to execute a block of code only if a specified condition or expression evaluates to true (non-zero). If the condition is false (zero), the code block is skipped, and program execution continues after the if statement.

The basic syntax of the if statement is as follows:


if (condition) {
    // Code to execute if the condition is true
}
  • The 'condition' is an expression or a test that evaluates to either true (non-zero) or false (zero).
  • If the 'condition' is true, the code inside the curly braces {} is executed. If it's false, the code block is skipped.

Here's an example of how the if statement is used in C:


#include <stdio.h>

int main() {
    int num = 10;

    // Check if num is greater than 5
    if (num > 5) {
        printf("The number is greater than 5.\n");
    }

    printf("This statement is always executed.\n");

    return 0;
}

Output:


The number is greater than 5.
This statement is always executed.

In this example:

  1. We declare a variable num and initialize it with the value 10.
  2. We use an if statement to check if numm is greater than 5. Since 10 is indeed greater than 5, the code block inside the if statement is executed, which prints "The number is greater than 5."
  3. The code outside the if statement (after the if block) is always executed, and it prints "This statement is always executed."

The if statement is essential for controlling the flow of your program based on conditions, allowing you to create decision branches and execute specific code when certain conditions are met.