Basic Programming Constructs

As part of this topic lets get into Basic Programming Constructs in Scala.

  • Declaring Variables
  • Invoking Functions
  • Conditional
  • While loop
  • For loop

Declaring Variables in Scala

We will use Scala REPL to explore variables in scala.

  • Each and every variable in scala must be declared with either val or var
  • val is immutable and var is mutable
val i = 2 or var i=2

Invoking Functions

A function is a group of statements that perform a task.

  • prinlln is a function in scala
  • To invoke a function in scala we use its object name and function name

Example

val s = "Hello World"
s.toUpperCase

For Loop

For loop is a repetitive structure which allows us to execute a block of code multiple times.

Example

for (i <- (1 to 100)) {
  println(i)
}

Task – Sum of all the given numbers

var total = 0
for (element <- (1 to 100))
  total += element

Task – Sum of even numbers from 1 to 100

var total = 0 
for (element <- (1 to 100))
  if(element % 2 ==0)
    total += element

While Loop

A while loop statement is executed repeatedly until the condition is false.

syntax

while(condition) { statement }

Example

Display Sum of even numbers and Sum of odd numbers

var lb = 1
val ub = 100
var totalEven = 0
var totalOdd = 0
while(lb <= ub) {
  if(lb % 2 == 0)
    totalEven += lb
  else
    totalOdd += lb
  lb += 1
}

Share this post