Conditional Statements in R Programming

Conditional Statements in R Programming

Conditional Statements in R Programming | If Else Tutorial

Conditional Statements Study Material – Complete Guide

Mastering Conditional Statements in Programming

Conditional statements are fundamental building blocks in programming that allow your code to make decisions. Think of them as the “if-then” logic that enables programs to respond differently based on varying inputs or conditions. This comprehensive guide will help you understand, implement, and master conditional statements with practical examples and exercises.

1. Understanding Conditional Statements

Conditional statements control the flow of execution in a program by evaluating whether specific conditions are true or false. They enable your code to adapt and respond to different situations, making programs dynamic and intelligent.

Key Concept: Conditions are Boolean expressions that evaluate to either true or false. The code inside the conditional block only executes when the condition is true.

Real-World Analogy: Imagine you’re deciding whether to carry an umbrella. Your thought process might be: “If it’s raining, then I’ll take an umbrella.” This is exactly how conditional statements work in programming.

Example Explained: Let’s break down the exam score example to understand each component:

// Variable declaration - stores the student's score
let score = 75;

// The if statement checks if the condition (score >= 50) is true
if (score >= 50) {
    // This block executes only if the condition is true
    console.log("Pass");
} else {
    // This block executes only if the condition is false
    console.log("Fail");
}
            
Note: The else part is optional. If omitted, nothing happens when the condition is false.
Exercise 1.1: Write a program to check if a number is positive, negative, or zero.

Hint: Remember that:
  • A number is positive if it’s greater than 0
  • A number is negative if it’s less than 0
  • A number is zero if it’s equal to 0
Solution 1.1:
let number = 10;

if (number > 0) {
    console.log("Positive");
} else if (number < 0) {
    console.log("Negative");
} else {
    console.log("Zero");
}
            

Explanation: The program checks each condition in sequence. If number > 0 is true, it prints "Positive" and skips the rest. If false, it checks number < 0, and so on.

2. Using if-else Statements for Decision Making

The if-else statement provides a clear way to handle two possible outcomes. It's perfect for binary decisions where there are exactly two options.

Syntax Pattern:
if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}
            

Example Explained: Let's examine the voting eligibility example in detail:

let age = 20;

if (age >= 18) {
    console.log("Eligible to vote");
} else {
    console.log("Not eligible to vote");
}
            

How it works: The condition age >= 18 checks if the age variable contains a value of 18 or more. If true, the first message is displayed. If false (age is less than 18), the second message is displayed.

Exercise 2.1: Write a program to determine if a year is a leap year or not.

Leap Year Rules:
  • A year is a leap year if it is divisible by 4
  • But if it's divisible by 100, it must also be divisible by 400 to be a leap year
  • Example: 2000 was a leap year, but 1900 was not
Solution 2.1:
let year = 2024;

if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
    console.log("Leap year");
} else {
    console.log("Not a leap year");
}
            

Explanation: This condition uses logical operators:

  • && (AND) - both conditions must be true
  • || (OR) - at least one condition must be true
  • The condition checks if either:
    • The year is divisible by 4 BUT NOT by 100, OR
    • The year is divisible by 400

3. Creating Nested Conditional Logic

Nested conditionals allow you to check multiple related conditions by placing one conditional statement inside another. This is useful when decisions depend on multiple factors.

When to Use Nested Conditionals:
  • When you need to make decisions based on multiple criteria
  • When conditions are hierarchical (one condition depends on another)
  • When you need to check additional conditions only if a primary condition is met

Example Explained: The number classification example with nested conditions:

let num = 12;

if (num > 0) {
    // This inner condition only checks if the number is positive
    if (num % 2 === 0) {
        console.log("Positive and Even");
    } else {
        console.log("Positive and Odd");
    }
} else if (num < 0) {
    console.log("Negative");
} else {
    console.log("Zero");
}
            

Flow Explanation: The program first checks if the number is positive. Only if it is positive does it then check whether it's even or odd. If the number isn't positive, it checks if it's negative, and if not, defaults to zero.

Exercise 3.1: Write a program to find the largest of three numbers using nested if-else statements.

Approach:
  1. Compare the first two numbers to find which is larger
  2. Then compare the larger of those two with the third number
Solution 3.1:
let a = 10, b = 20, c = 15;

if (a > b) {
    if (a > c) {
        console.log("a is largest");
    } else {
        console.log("c is largest");
    }
} else if (b > c) {
    console.log("b is largest");
} else {
    console.log("c is largest");
}
            

Step-by-step:

  1. First, compare a and b
  2. If a is greater than b, then compare a with c
  3. If a is not greater than b, then compare b with c

4. Implementing switch Statements

The switch statement provides a cleaner alternative to long chains of if-else if statements when you need to check a variable against multiple specific values.

Situation Use if-else Use switch
Checking ranges of values ✓ Better ✗ Not suitable
Checking specific discrete values ✓ Possible ✓ Better
Complex conditions with multiple variables ✓ Better ✗ Not suitable

Example Explained: The day of the week example using switch:

let day = 3;

switch (day) {
    case 1: 
        console.log("Monday"); 
        break;
    case 2: 
        console.log("Tuesday"); 
        break;
    case 3: 
        console.log("Wednesday"); 
        break;
    // ... more cases ...
    default: 
        console.log("Invalid day");
}
            
Important: The break statement is crucial in switch cases. Without it, the code will "fall through" and execute all subsequent cases until it hits a break or the end of the switch block.
Exercise 4.1: Write a program to print the name of a month based on its number (1-12) using switch.

Requirements:
  • Handle numbers 1 through 12
  • Include a default case for invalid numbers
  • Don't forget the break statements!
Solution 4.1:
let month = 5;

switch (month) {
    case 1: console.log("January"); break;
    case 2: console.log("February"); break;
    case 3: console.log("March"); break;
    case 4: console.log("April"); break;
    case 5: console.log("May"); break;
    case 6: console.log("June"); break;
    case 7: console.log("July"); break;
    case 8: console.log("August"); break;
    case 9: console.log("September"); break;
    case 10: console.log("October"); break;
    case 11: console.log("November"); break;
    case 12: console.log("December"); break;
    default: console.log("Invalid month");
}
            

5. Best Practices for Conditional Programming

Writing clean, maintainable conditional code is essential for professional programming. Follow these guidelines to improve your code quality:

Best Practices:
  • Use meaningful variable names: isEligibleToVote is better than check
  • Avoid deep nesting: If you have more than 3 levels of nesting, consider refactoring
  • Use early returns: Exit functions early when conditions are met to reduce nesting
  • Keep conditions simple: Break complex conditions into smaller, named variables
  • Comment complex logic: Explain why you're checking certain conditions

Example: Using functions to simplify complex conditions.

// Instead of writing complex conditions repeatedly, create a function
function checkGrade(score) {
    if (score >= 90) return "A";
    else if (score >= 80) return "B";
    else if (score >= 70) return "C";
    else return "D";
}

// Now the code is much cleaner and reusable
console.log(checkGrade(85)); // Output: B
console.log(checkGrade(92)); // Output: A
            
Exercise 5.1: Refactor the following nested if-else into a switch statement:
let fruit = "apple";
if (fruit === "apple") {
    console.log("It's an apple");
} else if (fruit === "banana") {
    console.log("It's a banana");
} else {
    console.log("Unknown fruit");
}
            
Solution 5.1:
let fruit = "apple";
switch (fruit) {
    case "apple": 
        console.log("It's an apple"); 
        break;
    case "banana": 
        console.log("It's a banana"); 
        break;
    default: 
        console.log("Unknown fruit");
}
            

Why this is better: The switch statement is more readable when checking a variable against specific values, especially as you add more fruit types.

Additional Practice Problems

Challenge Problem 1: Write a program that categorizes a person's age:
  • 0-12: Child
  • 13-19: Teenager
  • 20-64: Adult
  • 65+: Senior
Challenge Problem 2: Create a simple calculator that takes two numbers and an operator (+, -, *, /) and returns the result. Handle division by zero appropriately.

Summary

Conditional statements are essential tools in programming that enable decision-making in your code. Remember:

  • Use if for simple conditions
  • Use if-else for binary decisions
  • Use if-else if-else for multiple conditions
  • Use switch when checking a variable against specific values
  • Avoid deep nesting and complex conditions when possible

Practice these concepts with the exercises provided, and try to apply them to real-world problems you encounter. The more you practice, the more intuitive conditional logic will become.

Educational Resources Footer