Home

AAP-2.G Express an algorithm that uses selection

Understanding Selection in Programming

What is an Algorithm?

An algorithm is a step-by-step procedure or formula for solving a problem. In programming, an algorithm is a set of instructions that tells the computer what to do.

What is Selection?

Selection is a programming concept where you make decisions in your code. It allows your program to choose different paths based on certain conditions. Think of it as a fork in the road: depending on the condition, the program will take one path or another.

How Does Selection Work?

In Java, selection is done using if, else if, and else statements. These statements let your program check if certain conditions are true or false and then execute different code based on the result.

Basic Example of Selection

Here's a simple example to illustrate selection. Let's say we want to check if a number is positive, negative, or zero.

int number = 10;

if (number > 0) {
    System.out.println("The number is positive.");
} else if (number < 0) {
    System.out.println("The number is negative.");
} else {
    System.out.println("The number is zero.");
}

In this example:

Real-World Example: Checking Temperature

Imagine you have a thermostat that checks the temperature and turns on the heater if it's too cold.

int temperature = 65;

if (temperature < 68) {
    System.out.println("The heater is on.");
} else {
    System.out.println("The heater is off.");
}

In this real-world example:

Full Program Demonstrating Selection

Here's a full program that demonstrates the concept of selection. This program checks if a person is eligible to vote based on their age.

public class VotingEligibility {
    public static void main(String[] args) {
        // Declare and initialize an age variable
        int age = 17;

        // Use selection to check if the person is eligible to vote
        if (age >= 18) {
            System.out.println("You are eligible to vote.");
        } else {
            System.out.println("You are not eligible to vote.");
        }
    }
}

In this program:

Programming Problem

Now it's your turn! Write a program that checks if a student has passed or failed an exam. A student passes if their score is 50 or above.

I hope this helps you understand the concept of selection in programming! Happy coding!