Scala assignment by Amaya
control structure
- calculate avg of all no. between n1 & n2
object demo
{
def main(args:Array[String])
{
println("enter first number:")
var n1=scala.io.StdIn.readInt();
println("enter second number:")
var n2=scala.io.StdIn.readInt();
var sum=(n1+n2)/2;
println("Average is:"+sum)
}
}
2)calculate factorial of numbers
object demo
{
def main(args:Array[String])
{
println("enter no. you want to be search:")
var n=scala.io.StdIn.readInt();
var fact:Int=1;
for(i<-1 to n)
{
fact=fact*i;
}
println("factorial of " +n+ " is : "+fact);
}
}
3)read five random numbers and check that random numbers perfect or not
object demo
{
def main(args:Array[String])
{
println("how many no. you want to be search : ")
var n=scala.io.StdIn.readInt();
for(a<-1 to n)
{
println("enter the " +a+ " number is : ")
var num=scala.io.StdIn.readInt();
var sum:Int=0;
var i:Int=1;
while(i<=num/2)
{
if (num%i==0)
{
sum=sum+i;
}
i=i+1;
}
if(sum==num)
{
println(+num+ " is a prime number ")
}
else
{
println(" +num+ " is not a prime number ")
}
}
}
}
Q.3 Write a program to read five random numbers and check that random numbers are perfect number or not.
object Perfect
{
def main(args : Array[String])
{
var r=scala.util.Random;
var sum =0;
for(i <- 1 to 5)
{
var n = r.nextInt(100)
for(j <- 1 to n-1)
{
if(n % j == 0)
{
sum += j
}
}
if(sum == n)
println(n + " is a perfect number")
else
println(n + " is not a perfect number")
}
}
}
Q.4 Write a program to find second maximum number of four given numbers
object Max
{
def main(args: Array[String])
{
var arr=Array(50,30,60,40)
scala.util.Sorting.quickSort(arr)
for(i <- 0 to (arr.length-1))
{
println(arr(i))
}
println("2nd Max num Is : "+arr(2))
}
Q5 Write a program to calculate sum of prime numbers between 1 to 100
object PrimeSum
{
def main(args: Array[String])
{
var primesum=0
for(i <- 2 to 100)
{
var sum=0
for(j<-2 to i)
if(i%j==0)
sum=sum+j
if(sum==i)
{
primesum = primesum + i
}
}
println("sum of prime num are "+primesum)
}
}
Q6 Write a program to read an integer from user and convert it to binary and octal using user defined functions.?
object demo
{
def octal(num:Int) :Unit=
{
printf("Octal value: %o\n", num)
}
def main(args:Array[String])
{
print("Enter the Number = ")
var num = scala.io.StdIn.readInt()
var binary = (num).toBinaryString
println("Binary of "+num+" is "+binary)
octal(num);
}
}
Array
Q1 Write a program to find maximum and minimum of an array?
object Demo1
{
def main(args:Array[String])
{
println("How Many Elements do u want in Array = ")
var n = scala.io.StdIn.readInt()
var arr = new ArrayInt
for(b<-0 to (arr.length-1))
{
println("Enter Number = ")
arr(b) = scala.io.StdIn.readInt()
}
var max:Int = arr(0)
var min:Int = arr(0)
for(i<-0 to (arr.length-1))
{
if(arr(i) > max)
{
max = arr(i)
}
if(arr(i) < min)
{
min = arr(i)
}
}
println("Maximun number is = "+max)
println("Minimum number is = "+min)
}
}
Q2. Write a program to calculate transpose of a matrix.
object HelloWorld
{
def main(args:Array[String])
{
var mat=Array.ofDimInt;
var rmat=Array.ofDimInt;
for(i<-0 to 2)
{
for(j<-0 to 2)
{
mat(i)(j)=scala.io.StdIn.readInt();
}
println();
}
for(i<-0 to 2)
{
for(j<-0 to 2)
{
rmat(i)(j)=mat(j)(i);
}
}
println("Transepose of Matrix is:");
for(i<-0 to 2)
{
for(j<-0 to 2)
{
print(rmat(i)(j)+" ");
}
println();
}
}
}
Q3 Write a program to calculate determinant of a matrix?
object demo
{
def main(args:Array[String])
{
var det=0
var a=Array.ofDimInt
a(0)(0)=1
a(0)(1)=2
a(1)(0)=3
a(1)(1)=4
println("matrix")
for(i<-0 until 2)
{
for(j<-0 until 2)
{
print(a(i)(j)+"\t")
}
println()
}
det=a(0)(0)*a(1)(1)-a(0)(1)*a(1)(0)
println("determinant="+det)
}
}
Q4 Write a program to check if the matrix is upper triangular or not
object UpperTrang {
def main(args: Array[String]): Unit =
{
var A=Array.ofDimInt
var m= scala.io.StdIn.readInt()
var n = scala.io.StdIn.readInt()
for (i <- 0 to m-1)
{
for (j <- 0 to n-1)
{
A(i)(j)=scala.io.StdIn.readInt()
}
}
println("The given matrix is ");
for (i <- 0 to m-1)
{
for (j <- 0 to n-1)
{
print(A(i)(j)+"\t");
}
println(" ");
}
var isUpper = 1;
for(row<-0 to m-1)
for(col<-0 to n-1)
if(col<row && A(row)(col)!=0)
isUpper = 0;
if(isUpper==1)
{
println("This is a Upper triangular matrix")
for(row<-0 to m-1)
for(col<-0 to n-1)
if(A(row)(col)!= 0)
{
print(A(row)(col) +"");
}
}
else
{
println("This is Not a Upper triangular matrix.");
}
}
}
Q5 Write a program to sort the matrix using insertion sort
object InsertionSortMatrix
{
def main(args: Array[String])
{
val matrix = Array(Array(5, 4, 7),
Array(1, 3, 8),
Array(2, 9, 6))
for (row <- 0 to 2)
{
for (col <- 0 to 2)
{
for (innerCol <- 0 until col)
{
if (matrix(row)(innerCol) > matrix(row)(col))
{
val temp = matrix(row)(innerCol)
matrix(row)(innerCol) = matrix(row)(col)
matrix(row)(col) = temp
}
}
}
}
println("Sorted Matrix :")
for (row <- 0 to 2)
{
for (col <- 0 to 2)
{
print(matrix(row)(col) + " ")
}
println()
}
}
}
Q6 Write a program for multiplication of two matrices(Validate number of rows andcolumns before multiplication and give appropriate message)
object matrix {
def main(args: Array[String])
{
val a = Array.ofDimInt
val b = Array.ofDimInt
val c = Array.ofDimInt
var i = 0
var j = 0
var k = 0
println("Enter the elements of first matrix: ")
for(i <- 0 to 1; j <- 0 to 1)
{
a(i)(j) = scala.io.StdIn.readInt()
}
println("Enter the elements of second matrix: ")
for(i <- 0 to 1; j <- 0 to 1)
{
b(i)(j) = scala.io.StdIn.readInt()
}
if(a(0).length == b.length)
{
for(i <- 0 to 1; j <- 0 to 1; k <- 0 to 1)
{
c(i)(j) = c(i)(j) + a(i)(k) * b(k)(j)
}
println("Product of two matrix is: ")
for(i <- 0 to 1; j <- 0 to 1)
{
print(c(i)(j) + " ")
println()
}
}
}
}
}
String
Q1. Write a program to count uppercase letters in a string and convert it to lowercase and display the new string.
object Demo1
{
def main(args:Array[String])
{
var str:String = "ARTI"
var cnt:Int = 0
for(s<-0 to (str.length-1))
{
if(str.charAt(s)>='A' && str.charAt(s)<='Z')
{
cnt = cnt + 1
}
}
println("Original String is = "+str)
println("LowerCase string is = "+str.toLowerCase())
println("Count is = "+cnt)
}
}
Q2 Write a program to read a character from user and count the number of occurrences ofthat character.
object char
{
def main(args: Array[String])
{
println("Enter a character to count its occurrences: ")
var char = scala.io.StdIn.readChar()
println("Enter a String: ")
var str = scala.io.StdIn.readLine()
var count = 0
for(i <- 0 until str.length)
{
if(char == str(i))
count += 1
}
println("Number of occurrences of given char in a string: " + count)
}
}
Q2 Write a program to read a character from user and count the number of occurrences of that character.
object count_occurrence {
def main(args: Array[String]): Unit = {
var s: String="hello word"
println(s+ "/Enter char to count occurrence of char in above sentence :- ")
var char : Char = scala.io.StdIn.readChar()
println("Occurrence of character "+char+" ="+s.count(_==char))
}
}
Q3 Write a program to read two strings. Remove the occurrence of second string in first string. in scala program
object RemoveString {
def main(args: Array[String])
{
val str1 = "Hello World"
val str2 = "Hello"
println("String 1: "+str1)
println("String 2: "+str2)
val newStr = str1.replace(str2,"")
println("New String: "+newStr)
}
}
Q4 Create array of strings and read a string from user. Display all the elements of array containing given string. in scala program
object demo
{
def main(args:Array[String])
{
var arrayData = Array("Hello","World","Scala","Programming")
println("Enter a String to search: ")
var searchString =scala.io.StdIn.readLine()
for(data <- arrayData)
{
if(data.contains(searchString))
println(data)
}
}
}
Class and object
Q3 Create abstract class Order (id, description). Derive two classes PurchaseOrder& SalesOrder with members Vendor and Customer. Create object of each PurchaseOrder and SalesOrder. Display the details of each account. in scala
abstract class Order(id: Int, description: String)
class PurchaseOrder(id: Int, description: String, vendor: String) extends Order(id, description) {
def displayDetails(): Unit = {
println("Id: " + id)
println("Description: " + description)
println("Vendor: " + vendor)
}
}
class SalesOrder(id: Int, description: String, customer: String) extends Order(id, description) {
def displayDetails(): Unit = {
println("Id: " + id)
println("Description: " + description)
println("Customer: " + customer)
}
}
object Main {
def main(args: Array[String]): Unit = {
val purchaseOrder = new PurchaseOrder(1, "Computer", "Dell")
val salesOrder = new SalesOrder(2, "Laptop", "John")
println("Purchase Order Details: ")
purchaseOrder.displayDetails()
println("Sales Order Details: ")
salesOrder.displayDetails()
}
}
Q4 Define a class Employee (id, name, salary). Define methods accept() and display().Display details of employee having maximum salary
class Employee(id:Int, name:String, salary:Double)
{
def accept()
{
println("Employee ID: "+id)
println("Employee Name: "+name)
println("Employee Salary: "+salary)
}
def display()
{
println("Employee ID: "+id)
println("Employee Name: "+name)
println("Employee Salary: "+salary)
}
}
object Employee
{
def getMaxSalaryEmployee(employees:Array[Employee]):Employee=
{
var maxSalaryEmployee = employees(0)
for(employee <- employees)
{
maxSalaryEmployee = employee
}
return maxSalaryEmployee
}
def main(args: Array[String]) {
val emp1 = new Employee(1, "John", 10000)
val emp2 = new Employee(2, "Smith", 15000)
val emp3 = new Employee(3, "Peter", 20000)
val employees = Array(emp1, emp2, emp3)
val maxSalaryEmployee = getMaxSalaryEmployee(employees)
println("\nEmployee having maximum salary:")
maxSalaryEmployee.display()
}
}
Q5 Create class Project (id, name, location). Define parameterized constructor. Keep a count of each object created and display the details of each project. in scala
class Project(id:Int, name:String, location:String){
private var count = 0
count += 1
def displayDetails(){
println("Project id: "+id)
println("Project Name: "+name)
println("Project Location: "+location)
println("Total Projects created: "+count)
}
}
object MainObject{
def main(args:Array[String]){
var p1 = new Project(1, "Project1", "Delhi")
p1.displayDetails()
var p2 = new Project(2, "Project2", "Mumbai")
p2.displayDetails()
}
}
Q6 Define a class Sports (id, name, description, amount). Derive two classes Indoor and Outdoor.
Define appropriate constructors and operations. Create an object and perform operations. in scala
class Sports(id: Int, name: String, description: String, amount: Double)
{
def getId(): Int = this.id
def getName(): String = this.name
def getDescription(): String = this.description
def getAmount(): Double = this.amount
}
class Indoor(id: Int, name: String, description: String, amount: Double) extends Sports(id, name, description, amount)
{
def play(): Unit = println(" ")
}
`
class Outdoor(id: Int, name: String, description: String, amount: Double) extends Sports(id, name, description, amount)
{
def play(): Unit = println(" ")
}
object Main {
def main(args: Array[String]): Unit = {
val indoor = new Indoor(1,"Badminton", "Racquet sport", 50.0)
val outdoor = new Outdoor(2, "Cricket", "Bat and Ball", 100.0)
println("Name of indoor game: " + indoor.getName())
println("Name of outdoor game: " + outdoor.getName())
}
}
Q7Design abstract class Employee with computeSal() as abstract function. Create two subclasses Worker and Manager. Salary of worker should be calculated on hourly basis of work and Salary of Manager should be calculated on monthly basis with additionalincentives.
abstract class Employee()
{
def ComputeSal();
}
class Worker(a:Int) extends Employee()
{
var S:Int=a;
var ans:Int=300;
def ComputeSal()
{
print("Salary of Worker WeekWise:"+((S*ans)*7)+"\n");
}
}
class Manager(b:Int) extends Employee()
{
var R:Int=b;
var ans:Double=10000;
def ComputeSal()
{
print("Salary of Manager MonthWise:"+(ans+(R*300))+"\n");
}
}
object EmpSal
{
def main(a:Array[String])
{
val ob1=new Worker(4);
val ob2=new Manager(12);
while(true)
{
println("MENU"+"\n"+"1:Worker"+"\n"+"2:Manager"+"\n"+"3:Exit")
println("Enter the Choise:");
var n1:Int=scala.io.StdIn.readInt();
n1 match{
case 1=>ob1.ComputeSal();
case 2=>ob2.ComputeSal();
case 3=>System.exit(0);
}
}
}
}