c > constructs > conditional constructs > conditional constructs

Conditional Constructs

In solving a problem, we sometimes want to execute a block of code if one or more conditions are met. We use conditional constructs in order to specify actions and the criteria required for those actions to be executed. In C, we have two (2) main conditional constructs:

If-else

These are used to create multiple branching paths in our code. Only one branch is executed if its condition is satisfied. All branches following it are ignored.


#include <stdio.h>

int main()
{
    int age;
    printf("Please enter your age: ");
    scanf("%d",&age);
    if(age>=18){
        printf("You are an adult\n");
    }else{
        printf("You are not an adult as yet\n");
    }
    return 0;
}

↗ Open 📋 Copy c/constructs/conditional_constructs/if_else.c

Switch-case

In this statement, it is possible for all branches to run if we do not place the break statement at the end of each case:


#include <stdio.h>

int main(){
    char grade;
    printf("Please enter your grade: ");
    scanf("%c",&grade);

    switch(grade){
        case 'A':
            printf("You did great work\n");
            break;
        case 'B':
            printf("You did good work\n");
            break;
        case 'C':
            printf("You can do better\n");
            break;
        default:
            printf("You need to work harder\n");
    }
}

↗ Open 📋 Copy c/constructs/conditional_constructs/switch_case.c