Scala - IF ELSE Statements Example

1. Introduction

Control flow statements, such as if, else if, and else, are fundamental constructs in any programming language, allowing developers to dictate the flow of program execution based on conditions. In Scala, these statements work similarly to other languages but are also expressions that return a value. In this blog post, we will explore how to use these conditional statements in Scala through various examples.

Scala - if else Statement

The if statement is the simplest form of control flow, executing a block of code only if a specified condition is true.

The if-else statement extends this by providing an alternative path of execution when the condition is false.

Scala also allows chaining multiple conditions using else if, and nesting conditions within each other, known as nested if-else statements.

2. Program Steps

1. Define variables for condition checking.

2. Write an if statement to check a condition.

3. Write an if-else statement to handle two branches of execution.

4. Use an if-else-if-else statement to check multiple conditions.

5. Demonstrate a nested if-else statement.

6. Print the outcomes for each case.

7. Execute the program.

3. Code Program

object IfElseDemo extends App {
  val number: Int = 15

  // Simple if statement
  if (number > 0) println(s"$number is positive")

  // If-else statement
  if (number % 2 == 0) println(s"$number is even")
  else println(s"$number is odd")

  // If-else-if-else statement
  if (number < 0) println(s"$number is negative")
  else if (number % 2 == 0) println(s"$number is even")
  else println(s"$number is odd or positive")

  // Nested if-else statement
  if (number > 0) {
    if (number % 2 == 0) println(s"$number is positive and even")
    else println(s"$number is positive and odd")
  } else println(s"$number is not positive")
}

Output:

15 is positive
15 is odd
15 is odd or positive
15 is positive and odd

Explanation:

1. We define a variable number with the value 15.

2. The first if statement checks if number is greater than 0 and prints that it's positive.

3. The if-else statement checks if number is even. Since 15 is odd, the else block is executed, printing that 15 is odd.

4. In the if-else-if-else structure, the number is first checked to be less than 0. As it's not, the else if checks if it's even. Since 15 is neither, the final else is executed, indicating that 15 is either odd or positive.

5. The nested if-else is used to print more specific information about number. As 15 is positive but not even, it prints that 15 is positive and odd.


Comments