Yandex

Decision Making in Code
Conditional Statements



Understanding Conditional Statements

Conditional statements are used to make decisions in programming. They allow the program to choose different paths of execution based on whether certain conditions are true or false.

Why Do We Need Conditional Statements?

Imagine writing a program to check if someone is eligible to vote. You need to check their age. This is a decision-making scenario — and that's exactly what conditional statements help with.

Types of Conditional Statements

  • if — runs a block of code only if a condition is true
  • else — runs a block of code if the condition in if is false
  • else if — tests multiple conditions sequentially
  • nested if — an if inside another if

Example 1: Simple if Statement

Let’s check if a number is positive.

set number to 10

if number > 0 then
    print "Number is positive"
Number is positive

What happens if the condition is false?

If the condition is not met, nothing happens unless you provide an else block.

Example 2: if...else Statement

Let’s extend the previous logic to also say when the number is not positive.

set number to -5

if number > 0 then
    print "Number is positive"
else
    print "Number is not positive"
Number is not positive

Question:

What if you want to check for more than two conditions?

Answer:

You can use else if to test additional conditions.

Example 3: if...else if...else

Check if a number is positive, negative, or zero.

set number to 0

if number > 0 then
    print "Positive"
else if number < 0 then
    print "Negative"
else
    print "Zero"
Zero

Nested if Statements

Sometimes, one decision depends on another. This is where nested conditions are useful.

Example 4: Nested if

Check if a person is eligible to vote and if they have a voter ID.

set age to 22
set hasVoterID to true

if age >= 18 then
    if hasVoterID is true then
        print "Eligible to vote"
    else
        print "Get a voter ID first"
else
    print "Not eligible to vote"
  
end
Eligible to vote

Things to Remember

  • Conditions are evaluated top-down. The first true condition runs.
  • Use logical operators like AND, OR for combining multiple conditions.
  • Always handle the default case with else.


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M