HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI
HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

C If ... Else


Condation and C If ... Else statement

conditional statements and the if...else statement are fundamental tools for making decisions and controlling the flow of your program.

Less than: a < b

Less than or equal to: a <= b

Greater than: a > b

Greater than or equal to: a >= b

Equal to a == b

Not Equal to: a != b



C offers a range of conditional statements to control the flow of your program based on specific conditions.

C has the following conditional statements:

  • if statement: This a most basic conditional statement, used to execute a block of code if a specified condition is true.

  • if-else statement: Provides an alternative block of code to execute if the condition in the if statement is false.

  • if-else if ladder: Allows you to chain multiple conditions and execute different code blocks based on which one is true.

  • switch statement: Evaluates an expression and executes a block of code associated with a matching case label.


  • The if Statement

    Use the if statement to specify a block of code to be executed if a condition is true.

    Syntax

    if (condition) {

    // block of code to be executed if the condition is true


    Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.


    In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text:

    Example

    #include <stdbool.h>

    int main() {

    if (20 > 18) {

    printf("20 is greater than 18");

    }

    return 0;

    }

    Output

    20 is greater than 18


    We can also test variables:
    Example

    #include <stdbool.h>

    int main() {

    int x = 20;

    int y = 18;

    if (x > y) {

    printf("x is greater than y");

    }

    return 0;

    }

    Output

    x is greater than y


    Example explained

    In the above example we use two variables, x and y, to test whether x is greater than y using the (>) operator. Since x is 20, and y is 18, and we know that 20 is greater than 18, we print on the screen "x is greater than y".