Scala assignment
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 ")
}
}
}
}
4)find second maximum number of four given numbers
object demo
{
def main(args:Array[String])
{
var arr=new ArrayInt
for(i<-0 to (arr.length-1))
{
println("enter the numbers : ")
arr(i)=scala.io.StdIn.readInt();
}
var temp:Int=0
for(x<-0 to (arr.length-1))
{
for(y<-x+1 to (arr.length-1))
{
if(arr(x) < arr(y))
{
temp=arr(y)
arr(y)=arr(x)
arr(x)=temp
}
}
}
println("second maximun number is : "+arr(1))
}
}
5)calculate sum of prime numbers between 1 to 100
object demo
{
def main(args:Array[String])
{
var primesum:Int=0;
for(a<-2 to 100)
{
var sum:Int=0;
for(i<-2 to a)
{
if(a%i==0)
{
sum=sum+i
}
}
if(sum==a)
{
primesum=primesum+a;
}
}
println("sum of prime number 1 to 100 is : "+primesum)
}
}
6)integer from user and convert it to binary and octal using defined functions
object demo
{
def octal(num:Int):Unit=
{
printf("ocatal value:%0\n",num)
}
def main(args:Array[String])
{
println("enter a number : ")
var num=scala.io.StdIn.readInt();
var binary=(num).toBinaryString
println("binary of " +num+ " is : "+binary)
octal(num);
}
}
Array
-
write a program to find maximum and minimum of an array
object demo
{
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 numbers : ")
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("maximum number is : "+max)
println("minimum number is : "+min)
}
} -
write a program to calculate transpose of matrix
object demo
{
def main(args:Array[String])
{
var mat=Array.ofDimInt
var tmat=Array.ofDimInt
println("enter the data for array is : ")
for(i<-0 to 2)
{
for(j<-0 to 2)
{
mat(i)(j)=scala.io.StdIn.readInt()
}
}
for(i<-0 to 2)
{
for(j<-0 to 2)
{
tmat(i)(j)=mat(j)(i)
}
}
println("transpose of matrix : ")
for(i<-0 to 2)
{
for(j<-0 to 2)
{
print(tmat(i)(j)+ " ")
}
println()
}
}
}
3)write a program to calculate determinant of 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 is : ")
for(i<-0 until 2)
{
for(j<-0 until 2)
{
print(a(i)(j)+" ")
}
println()
}
det= a(0)(0)*a(1)(1)-a(0)(1)*a(1)(0)
println("determinant is : "+det)
}
}
4)write a program to check if the matrix is upper triangular or not
object demo
{
def main(args:Array[String]):Unit=
{
println("enter the array size : ")
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 and values are : ")
for(row<-0 to m-1)
for(col<-0 to n-1)
if(A(row)(col)!=0)
{
print(A(row)(col) + "\t")
}
}
else
{
println("this is not a upper triangular matrix and values are : ")
}
}
}
5)write a program to sort the matrix using insertion sort
object demo
{
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 is : ")
for(row<-0 to 2)
{
for(col<-0 to 2)
{
print(matrix(row)(col)+ " ")
}
println()
}
}
}
6)write program for multiplication of two matrices (validate no of rows & cols before multiplication and give appropriate message)
object demo
{
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 ; i<-0 to 1)
{
print(c(i)(j)+ " ")
}
println()
}
}
}
string
1)write a program to count uppercase letters in a string and convrt it to lowercase and display the new string
object demo
{
def main(args:Array[String])
{
var str:String = "SIDDHI"
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)
}
}
- Write a program to read a character from user and count the number of occurrences of that character
object demo
{
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)
}
}
3)write program to read two strings remove the occurance of second string in first string
object def
{
def main(args:Array[String])
{
object demo
{
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)
}
}
4)create array of strings and read a string from user.display all the elements of array containing given string
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
1)define a class currentaccount(accno,name,balance,minbalance) define appropriate constructors and operations withdraw(),deposte(),viewbalance()
create an object and performance operations
class CurrentAccount(accno: Int ,nm: String, bal:Int, minBal:Int)
{
var accNo:Int= accno;
var name:String=nm
var balance:Int=bal;
var minBalance:Int=minBal;
def withdraw(amount:Int)
{
if((balance-amount)<minBalance)
println("Insufficient balance to withdraw ")
else
balance-=amount
println("Current Balance = "+balance);
}
def deposit(amount:Int)
{
balance+=amount
println("Current Balance = "+balance);
}
def viewBalance()
{
println("Current Available Balance = "+balance);
}
}
object mainObject
{
def main(args:Array[String])
{
var b=new CurrentAccount(1,"Ram",5000,500)
var choice:Int=0
println("WELCOME.....")
do
{
println("1: WITHDRAW\n2:DEPOSIT\n3:VIEW BALANCE\n4:EXIT")
println("Enter your choice : ");
choice=scala.io.StdIn.readInt
var amount:Int=0
choice match
{
case 1 => print("Enter the amount to withdraw : ")
amount=scala.io.StdIn.readInt()
b.withdraw(amount)
case 2 => print("Enter the amount to deposit : ")
amount=scala.io.StdIn.readInt()
b.deposit(amount)
case 3 => b.viewBalance()
case 4 => println("Exiting...")
case _ => println("Invalid choice entered, Try again...")
}
}while(choice!=4)
}
}
2)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()
}
}
3)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()
}
}
4)create abstract class shape with abstract functions volume() and display().Extend two classes cube and cylinder from it.
calculate volume of each and display it
abstract class shape(r:Int,h:Int)
{
var vol1:Double=0
var pi:Double=3.14
def volume()
def display()
}
class cylinder(r:Int,h:Int)extends shape(r,h)
{
def volume()
{
var vol:Double=0
vol=pirr*h
vol1=vol
println("**")
println("volume is:"+vol)
}
def display()
{ println("")
println("radius of cylinder:"+r)
println("height of cylinder:"+h)
println("volume of cylinder:"+vol1)
}
}
object MainObject{
def main(args:Array[String]){
var radius:Int=0
var height:Int=0
println("enter radius of cylinder:")
radius=scala.io.StdIn.readInt()
println("enter hight of cylinder")
height=scala.io.StdIn.readInt()
var n=new cylinder(radius,height)
n.volume()
n.display()
}
}
5)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()
}
}
6)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())
indoor.play()
outdoor.play()
}
}
7)design 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 additional incentives
abstract class Employees {
def computeSal(): Double
}
class Worker extends Employees {
private var hoursWorked: Double = 0.0
private var hourlyWage: Double = 0.0
def setHoursWorked(hours: Double): Unit = {
hoursWorked = hours
}
def setHourlyWage(wage: Double): Unit = {
hourlyWage = wage
}
override def computeSal(): Double = {
hoursWorked * hourlyWage
}
}
class Manager extends Employees {
private var monthlySalary: Double = 0.0
private var incentives: Double = 0.0
def setMonthlySalary(salary: Double): Unit = {
monthlySalary = salary
}
def setIncentives(inc: Double): Unit = {
incentives = inc
}
override def computeSal(): Double = {
monthlySalary + incentives
}
}
object prog7 {
def main(args: Array[String]): Unit = {
val worker = new Worker
worker.setHoursWorked(40)
worker.setHourlyWage(15)
val workerSalary = worker.computeSal()
println("Worker Salary : " + workerSalary)
val manager = new Manager
manager.setMonthlySalary(5000)
manager.setIncentives(1000)
val managerSalary = manager.computeSal()
println("Manager Salary : " + managerSalary)
}
}