Lab Manual AInDS Scala (Updated)
Lab Manual AInDS Scala (Updated)
TECHNOLOGY
Affiliated to VTU, Approved by AICTE, Accredited by
NBA and NAAC with “A++” Grade
ITPL MAIN ROAD, BROOKFIELD, BENGALURU-
560037, KARNATAKA, INDIA
BE - IV SEMESTER
SCALA
LABORATORY
MANUAL -BDSL456A
Write a Scala program to compute the sum of the two given integer values. If the two values are the
same, then return triples their sum.
Theory:
In this program we will define a function for Sum or Triple. Inputs a and b will be given to this
function. Then it will check the condition using if …. Else. Based on condition it will perform normal
Sum and then display its triplet
Program:
object SumCalculator {
def main(args: Array[String]): Unit = {
// Test cases
println(sumOrTriple(2, 3)) // Output should be 5
println(sumOrTriple(5, 5)) // Output should be 30
println(sumOrTriple(-1, -1)) // Output should be -6
}
def sumOrTriple(a: Int, b: Int): Int = {
if (a == b) {
3 * (a + b)
} else {
a+b
}
}
}
Output:
OR
import scala.io.StdIn
object SumCheck {
def main(args: Array[String]): Unit = {
// Prompt the user to enter a number
println("Enter a first number:")
if(a==b){
val c=3 * (a + b)
println("Result is:"+c)
}
else {
val d=a + b
println("Result is:"+d)
}
}
Conclusion:
In this Program we understood how to compute the sum of the two given integer values and if the two
values are the same, then how to return triples their sum.
Problem Statement:
Write a Scala program to check two given integers, and return true if one of them is 22 or if
their sum is 32.
Theory:
In this program we will define a function checkIntegers. We will give 2 values to the function.
Then it will check whether any one of the values is 22 or whether sum of those values is 32. If
any one of condition is satisfied then it will return True as an answer otherwise False
Program
object IntegerChecker {
def main(args: Array[String]): Unit = {
// Test cases
println(checkIntegers(10, 22)) // Output should be true
println(checkIntegers(20, 10)) // Output should be false
println(checkIntegers(15, 17)) // Output should be true
println(checkIntegers(15, 18)) // Output should be false
}
Output:
OR
import scala.io.StdIn
object IntegerCheck {
def main(args: Array[String]): Unit = {
// Prompt the user to enter a number
println("Enter a first number:")
println(result)
}
}
Conclusion:
In this Program we understood how to check two given integers, and return true or false
depending upon the condition.
Problem Statement
Write a Scala program to remove the character in a given position of a given string. The given position
will be in the range 0...string length -1 inclusive.
Theory:
Program:
object RemoveCharacter {
def main(args: Array[String]): Unit = {
// Sample string
val inputString = "Hello, World!"
OR
import scala.io.StdIn
object RemoChar {
def main(args: Array[String]): Unit = {
// Sample string
}
}
Conclusion:
In this Program we understood how to remove the character in a given position of a given string
Problem Statement
Write a Scala program to create a new string taking the first 5 characters of a given string and return
the string with the 5 characters added at both the front and back.
Theory:
Program:
object StringManipulation {
def main(args: Array[String]): Unit = {
// Test cases
println(addFirstFive("HelloWorld")) // Output should be "HelloHelloHelloWorldHelloHelloHello"
println(addFirstFive("Scala")) // Output should be "ScalaScalasca"
println(addFirstFive("12345")) // Output should be "123451234512345"
}
Conclusion:
In this Program we understood how to create a new string taking the first 5 characters of a given string
and return the string with the 5 characters added at both the front and back.
3 a) Write a Scala program to print the multiplication table of a given number using a for
loop.
Program:
object MultiplicationTable {
def main(args: Array[String]): Unit = {
val number: Int = 5 // Number for which you want to print the multiplication table
val tableSize: Int = 12 // Size of the multiplication table
Sample Output:
Multiplication Table of 5:
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
5 * 11 = 55
5 * 12 = 60
Explanation:
First we define a variable "number" and assign it a value (5 in this case) for which we want to
print the multiplication table. We also define a variable "tableSize" and assign it a value (12
in this case) which determines the size of the multiplication table.
We use a for loop to iterate from 1 to "tableSize". Inside the loop, we calculate the product of
"number" and the current iteration value i and store it in the variable product. We then use
println to display the multiplication expression and result.
3 b ) Write a Scala program to find the largest element in an array using pattern matching
Program:
object LargestElementFinder {
def main(args: Array[String]): Unit = {
// Array containing the numbers
val numbers: Array[Int] = Array(23, 36, 36, 55, 19, 8)
// Print all the array elements
println("Original Array elements:")
for ( x <- numbers ) {
print(s"${x}, ")
}
largestElement match {
case Some(largest) => println(s"\nThe largest element is: $largest")
case None => println("\nThe array is empty.")
}
}
Sample Output:
Original Array elements:
23, 36, 36, 55, 19, 8,
The largest element is: 55
Explanation:
At the end of the program, the largest element in the array will be displayed.
● x will be 23.
● y will be 36.
● rest will be the sequence containing the remaining elements: rest =
Seq(36, 55, 19, 8).
Then, the function recursively calls findLargestElement with y (36) and the
sequence rest (Seq(36, 55, 19, 8)).
OR
object LargestElement {
case Array(x, _*) => arr.foldLeft(x) { (max, elem) => if (elem > max) elem else max }
}
def main(args: Array[String]): Unit = {
try {
} catch {
Output:
findLargest that takes an array of integers as input. The method uses pattern
matching to handle different cases:
● If the array has more than one element, it uses foldLeft to iterate through
the elements and find the largest one.
The main method creates an array of integers, calls the findLargest method, and
prints out the largest element. It also includes exception handling for cases where
the array might be empty.
Program:
import scala.io.StdIn.{readInt,readBoolean}
object sum_digit {
def main(args: Array[String]): Unit = {
println("display sum of digits of a number")
var n:Int=readInt()
println("Enter number:"+n);
var mul=1;
while(n!=0)
{
mul=mul*n%10;
n=n/10;
}
println("Product of digits of a number:"+mul)
}
}
Sample Output:
STDIN
123
Output
Enter number:123
Program:
object SquareChecker {
def isPerfectSquare(number: Int): Boolean = {
val sqrt = math.sqrt(number).toInt
sqrt * sqrt == number
}
Sample Output:
5 a. Write a Scala program that creates a subclass Student that extends the Person
class. Add a property called grade and implement methods to get and set it
Program:
class Person(var name: String, var age: Int, var country: String) {
def getName: String = name
class Student(name: String, age: Int, country: String, var grade: String)
extends Person(name, age, country) {
object StudentApp {
def main(args: Array[String]): Unit = {
val student = new Student("Saturnino Nihad", 18, "USA", "A")
println("Original Student:")
println(s"Name: ${student.getName}")
println(s"Age: ${student.getAge}")
println(s"Country: ${student.getCountry}")
println(s"Grade: ${student.getGrade}")
student.setName("Albino Ellen")
student.setAge(20)
student.setCountry("Canada")
student.setGrade("B")
println("\nUpdated Student:")
println(s"Name: ${student.getName}")
println(s"Age: ${student.getAge}")
println(s"Country: ${student.getCountry}")
println(s"Grade: ${student.getGrade}")
}
}
Sample output:
Explanation:
In the above exercise -
The "Person" class defines the properties name, age, and country, along with the
corresponding getter and setter methods.
The "Student" class extends the Person class and adds an additional property called
grade. It also includes getter and setter methods specific to the grade property.
The StudentApp object contains the main method, which demonstrates the Student
class usage. It creates a Student object, prints its original values, updates the
properties using the setter methods inherited from the Person class and the setGrade
method from the Student class. It then prints the updated values.
5b. Write a Scala program that creates a class Triangle with properties side1, side2,
and side3. Implement a method isEquilateral to check if the triangle is equilateral.
class Triangle(val side1: Double, val side2: Double, val side3: Double) {
def isEquilateral(): Boolean = {
side1 == side2 && side2 == side3
}
}
object TriangleApp {
def main(args: Array[String]): Unit = {
val triangle1 = new Triangle(6.0, 6.0, 6.0)
val triangle2 = new Triangle(3.0, 4.0, 5.0)
Explanation:
● The "Triangle" class is defined with a constructor that takes side1, side2, and side3
as parameters and initializes the corresponding properties. The properties are
defined as val, making them read-only.
● The "isEquilateral()" method is defined in the Triangle class. It checks if all three
sides of the triangle are equal, indicating an equilateral triangle.
● The "TriangleApp" object contains the main method to test functionality. It creates
instances of Triangle with different side lengths, and calls the isEquilateral method
to check if the triangles are equilateral.
6a. Write a Scala program that creates an enum class Color with values for different
colors. Use the enum class to represent an object's color.
Program:
sealed trait Color
case object Red extends Color
case object Green extends Color
case object Blue extends Color
case object Orange extends Color
object ColorApp {
def main(args: Array[String]): Unit = {
val myColor: Color = Red
//val myColor: Color = Blue
printColor(myColor)
}
enum Color {
case Red, Green, Blue, Orange
}
object ColorApp {
def main(args: Array[String]): Unit = {
val myColor: Color = Color.Red
//val myColor: Color = Color.Blue
printColor(myColor)
}
Sample Output:
Explanation:
● First, we define a sealed trait "Color" that serves as the base type for different color
objects. Then, we define case objects "Red", Green, and Blue that extend the Color
trait to represent specific colors.
● The "ColorApp" object contains the “main()” method where we can test
functionality. It assigns the "Red" color to the myColor variable and calls the
"printColor()" method to print the color name.
● The "printColor()" method uses pattern matching to determine the specific color of
the object and prints a corresponding message.
6b. Write a Scala program that creates a class ContactInfo with properties name,
email, and address. Create a class Customer that includes a ContactInfo object.
Program:
class ContactInfo(val name: String, val email: String, val address: String)
object CustomerApp {
def main(args: Array[String]): Unit = {
val contact = new ContactInfo("Serafim Eline", "[email protected]", "11 Open
Street")
val customer = new Customer(contact)
Sample Output:
Explanation:
In the above exercise,
● The "ContactInfo" class is defined with the properties name, email, and address. It
has a primary constructor that takes these properties as parameters.
● The "Customer" class is defined by the property contactInfo of type ContactInfo. It
represents a customer and includes contact information.
● The CustomerApp object contains the main method to test functionality. It creates
an instance of the ContactInfo class with sample information and then creates a
Customer object using the ContactInfo instance.
● Finally, the program prints the customer's name, email, and address using string
interpolation.
7a. Write a Scala program to create a set and find the difference and intersection
between two sets.
Program:
object SetIntersectionExample {
def main(args: Array[String]): Unit = {
Output:
Explanation:
This program creates two sets, set1 and set2, and then finds their difference and intersection
using the diff and intersect methods provided by Scala's Set class. Finally, it prints the
original sets, the difference, and the intersection.
7b. Write a Scala program to create a set and find the second largest element in the set.
Program:
object SecondLargestElement {
def main(args: Array[String]): Unit = {
// Create a set
val mySet = Set(100, 59, 20, 15, 25, 30)
Output:
Explanation:
This program defines a function findSecondLargest that takes a set of integers as input and
returns an Option[Int], where the option contains the second largest element if it exists, or
None otherwise. It sorts the set in descending order and retrieves the second element if the set
has at least two elements. Finally, it prints the original set and the second largest element (if
found).
8a.Write a Scala program to create a list in different ways.
Program:
//Using List constructor directly:
val myList1 = List(1, 2, 3, 4, 5)
println(myList1)
//Using List.tabulate:
val myList3 = List.tabulate(5)(_ + 1)
println(myList3)
//Using List.fill:
val myList4 = List.fill(5)(scala.util.Random.nextInt(10))
println(myList4)
//Using List.range:
val myList5 = List.range(1, 6)
println(myList5)
// Lisp style
val lispList = 1 :: 2 :: 3 :: 4 :: 5 :: Nil
println(s"Lisp style list: $lispList")
// Java style
val javaList = List(1, 2, 3, 4, 5)
println(s"Java style list: $javaList")
// Range list
val rangeList = (1 to 5).toList
println(s"Range list: $rangeList")
// Uniform list
val uniformList = List.fill(5)(42)
println(s"Uniform list: $uniformList")
// Tabulate list
val tabulateList = List.tabulate(5)(n => n * n)
println(s"Tabulate list: $tabulateList")
}
Output:
Explanation:
Each of these methods creates a list containing the elements 1 to 5. You can replace
the elements or modify the ranges/methods as needed to create lists with different
contents
Lisp style:
Java style:
● Using the List companion object's apply method to create the list.
Range list:
Uniform list:
● Using List.fill to create a list where every element is the same value.
Tabulate list:
● Using List.tabulate to create a list where each element is generated by
applying a function to its index.
In Scala, App is a trait that can be used to quickly turn objects into executable
programs. When you extend App, the code within the object body is executed as the
main program. The App trait provides a main method, which makes it easy to write
small applications without needing to define the main method explicitly.
8b. Write a Scala program to flatten a given List of Lists, nested list structure.
Program:
object FlattenList {
def main(args: Array[String]): Unit = {
// Define a list of lists
val nestedList: List[List[Int]] = List(List(1, 2, 3), List(4, 5), List(6, 7, 8))
Output:
Explanation: In this program, the flatten method is called on the nestedList, which flattens the
list of lists into a single list. Then, it prints both the original list of lists and the flattened list.
Without Function:
object FlattenNestedList {
def flattenList(nestedList: List[Any]): List[Any] = {
var result: List[Any] = List()
flatten(nestedList)
result
}
9 a Write a Scala program to add each element n times to a given list of integers.
b Write a Scala program to split a given list into two lists.
a) Write a Scala program to add each element n times to a given list of integers
Program :
object Scala_List {
// function to add each elements in a list n times using List.fill(n) Method Here n= 3
def n_times_elements[A](o_list:List[A], n: Int):List[A] = {
o_list flatMap { element => List.fill(n)(element) }
}
Output :
Original List:
List(1, 2, 3, 3, 4, 5, 6, 7)
Add each element 3 times to a given list of integers:
List(1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7)
Conclusion:
In this Program we understood about List and Fill() Method . List. fill() method creates a list
consisting of zero or more copies of the same element
Program :
object Scala_List {
// function to split a given list using take() and drop() Method.drop() method is
utilized to drop the first 'n' elements from the top of the stack and 'take' method in
Scala is used with iterators to get the first 'n' elements from a collection
def split_list[A](nums: List[A], n: Int): (List[A], List[A]) = {
(nums.take(n), nums.drop(n))
}
Original List:
List(1,2,3,4,5,67,8)
Split the said list into 2 lists:
(List(1, 2),List(3, 4, 5, 6))
(List(1, 2, 3),List(4, 5, 6))
Conclusion:
In this Program we understood about List and take() and drop() Method . drop() method is
utilized to drop the first 'n' elements from the top of the stack and 'take' method in Scala is
used with iterators to get the first 'n' elements from a collection.
Extra :
object Scala_List {
10.
a.Write a Scala program to swap the elements of a tuple Further print no
swapping required if elements are same.
object SwapTupleElementsExample {
def main(args: Array[String]): Unit = {
// Create a tuple
val nums = (100, 200)
println("Original Tuple: "+nums)
// Swap the elements of the tuple
val swappedTuple = nums.swap
object NonUniqueElementsInTuple {
def main(args: Array[String]): Unit = {
// Define a sample tuple with some elements
val tuple = (1, 2, 3, 2, 4, 5, 3, 6, 1, 7, 8)
object CheckTupleEqualityExample {
def main(args: Array[String]): Unit = {
// Create two tuples
val tuple1 = (1, "Kotlin", true)
val tuple2 = (1, "Kotlin", true)
val tuple3 = (2, "Java", false)
println("Tuple1: "+tuple1)
println("Tuple2: "+tuple2)
println("Tuple3: "+tuple3)
// Check if the tuples are equal
val areEqual1 = tuple1 == tuple2
val areEqual2 = tuple1 == tuple3
Tuple1: (1,Kotlin,true)
Tuple2: (1,Kotlin,true)
Tuple3: (2,Java,false)
Are tuple1 and tuple2 equal? true
Are tuple1 and tuple3 equal? false