Menu
Coddy logo textTech

If - Else

Part of the Fundamentals section of Coddy's C journey — lesson 26 of 63.

The if-else statement allows your program to make decisions based on conditions. If a condition is true, one block of code executes; otherwise, a different block executes.

Let's see how to use an if-else statement:

First, we define a variable:

int age = 17;

Now let's check if the person is an adult:

if (age >= 18) {
    printf("You are an adult.\n");
} else {
    printf("You are a minor.\n");
}

Since age is 17, which is less than 18, the output will be:

You are a minor.

The if part checks the condition. When the condition is false, the code in the else block executes.

challenge icon

Challenge

Easy

Write a program that:

  1. Reads an integer representing a student's score from the user
  2. If the score is greater than or equal to 60, prints "Pass"
  3. Otherwise, prints "Fail"

Cheat sheet

The if-else statement allows your program to make decisions based on conditions. If a condition is true, one block of code executes; otherwise, a different block executes.

Basic syntax:

if (condition) {
    // code to execute if condition is true
} else {
    // code to execute if condition is false
}

Example:

int age = 17;
if (age >= 18) {
    printf("You are an adult.\n");
} else {
    printf("You are a minor.\n");
}

Since age is 17, which is less than 18, the output will be You are a minor.

Try it yourself

#include <stdio.h>

int main() {
    int score;
    scanf("%d", &score);
    // Don't change above this line
    
    // Write your code here
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals