Advertisement

Responsive Advertisement

Conditional Statements in c

 Learning Sections          show

Conditional Statements in C

If Statement


#include<stdio.h>  // Include the standard input-output library

int main() {
    int a = 10;

    if (a > 5) {
        printf("a is greater than 5\n");
    }

    return 0;
}
        

Explanation: This program demonstrates the use of an if statement. It checks if a is greater than 5 and prints a message if the condition is true.

If-Else Statement


#include<stdio.h>  // Include the standard input-output library

int main() {
    int a = 3;

    if (a > 5) {
        printf("a is greater than 5\n");
    } else {
        printf("a is not greater than 5\n");
    }

    return 0;
}
        

Explanation: This program demonstrates the use of an if-else statement. It checks if a is greater than 5 and prints a message. If the condition is false, it prints a different message.

Else-If Ladder


#include<stdio.h>  // Include the standard input-output library

int main() {
    int a = 8;

    if (a == 1) {
        printf("a is 1\n");
    } else if (a == 2) {
        printf("a is 2\n");
    } else if (a == 3) {
        printf("a is 3\n");
    } else {
        printf("a is not 1, 2, or 3\n");
    }

    return 0;
}
        

Explanation: This program demonstrates the use of an else-if ladder. It checks if a equals 1, 2, or 3, and prints a corresponding message. If none of the conditions are true, it prints a default message.

Switch Statement


#include<stdio.h>  // Include the standard input-output library

int main() {
    int a = 2;

    switch (a) {
        case 1:
            printf("a is 1\n");
            break;
        case 2:
            printf("a is 2\n");
            break;
        case 3:
            printf("a is 3\n");
            break;
        default:
            printf("a is not 1, 2, or 3\n");
    }

    return 0;
}
        

Explanation: This program demonstrates the use of a switch statement. It checks the value of a and prints a corresponding message for the cases 1, 2, and 3. If a does not match any case, it prints a default message.