Enrollments closing soon for Post Graduate Certificate Program in Applied Data Science & AI By IIT Roorkee | 3 Seats Left

  Apply Now

Scala

22 / 53

Scala - Quick Introduction - Conditions and Loops




Not able to play video? Try with youtube

In programming, the first step of logic is a conditional statement such as if-else.

Let's redefine our function and put a conditional check in our method of simple interest. If someone enters negative principal that is less than 0, we print "Wrong principal" and return 0 as result.

Everything between curly brackets will be executed if the condition "principal less than 0" is true. If the condition is false, the statement outside the if block will be executed and our interest is calculated and returned as usual.

Let's check by calling our method with principal amount as negative 100. You can see that it has printed "Wrong principal" and the interest is 0.

Sometimes you may need to operate on the list of things. For that Scala provide a List data type.

Let define our list having number 4 9 8. var a equals List(4, 9, 8)

We can operate on a list in a variety of ways. One most common way is to go through every element using a for loop.

For x in a where a is a list and x is the current element, we are printing x i.e. each value of a. Notice the arrow which is basically angle bracket followed by -.

So, you can see that it has called println method for each value of the list.

This is called a definite because it definitely ends.

There is another way of executing a logic multiple times - A while loop.

A while loop has two parts - one condition and another body. The body keeps getting executed as long as the condition is true. If the condition remains true forever, it would keep executing the body forever.

Let's print all numbers less than 15. var x = 15; So, we define a variable x with value 15.

'''while( x > 0){ We define a while loop which will execute if the condition x > 0 is true.

'''println(x) '''x = x - 1 '''}

Inside while loop we have two statements - one for printing value of x and another decreases the value of x by 1.

This loop will stop as soon as the value of x is zero.

As you can see we have printed all the number less than 15 but greater than 0.


Loading comments...