All Scala practical Question upto The Class and Object


 //Write a program to calculate average of all numbers between n1 and n2(eg.100 to 300 Read
//values of n1 and n2 from user)
object MyClass {
    def main(args: Array[String]) {
        print("Enter the number from there you want to start");
        var n1=scala.io.StdIn.readInt();
        print("Enter the number upto were you want to go");
        var n2=scala.io.StdIn.readInt();
        var sum:Float=0;
        var count:Int=0;
        for(i<-n1 to (n2)){
            sum+=i;
            count=count+1;
        }
        var result:Float=(sum/count);
        print("The Average of all element is "+result)
    }
}


//2. Write a program to calculate factorial of a number
object Main{
    def main(args:Array[String])
    {
        var fact=1;
        print("Eneter the number which factorial you want")
        var n=scala.io.StdIn.readInt();
        for(i<-1 to n){
            fact=fact*i;
        }
        print("The given number fact is"+fact)
    }}

//3Write a program to read five random numbers and check that random numbers are perfect

object Main{
    def main(args:Array[String])
    {
        var arr=new Array[Int](5);
      print("Enter five Random Number");
      for(i<-0 to 5-1){
          print("Enter the number "+i+":  ");
          arr(i)=scala.io.StdIn.readInt();
          
      }
      var ans=0;
        for(i<-0 to 5-1){
         for(j<-1 to (arr(i)/2)){
             if(arr(i)%j==0){
                 
                 ans=ans+j;
             }else{}
             
         }
         if(ans==arr(i)){
             print("The Given number "+arr(i)+" is perfect \n");
                  
         }else{
             print("The Given number "+arr(i)+" not is perfect \n");
         }
         }
    }
}
//4. Write a program to find second maximum number of four given numbers.

object Main{
    def main(args:Array[String])
    {
        var arr=new Array[Int](5);
      print("Enter five Random Number");
      for(i<-0 to 4-1)
      {
          print("Enter the number "+i+1+":  ");
          arr(i)=scala.io.StdIn.readInt();  
      }
     var temp:Int=0;
        for(i<-0 to 4-2)
        {
         for(j<-i+1 to 4-1)
         {
             if(arr(i)<arr(j))
             {
                 temp=arr(i);
                 arr(i)=arr(j);
                 arr(j)=temp;
             }
         }
      }
      print("The second highest number"+arr(1));
    }
}


 
//1 to 100 prime umber sum
object Main{
    def main(args:Array[String])
    { var sum=0;
     var n: Int=2;
      var count=0;
      for(j<- 2 to 100){
          count=0;
    for(i<- 2 to j/2){
        if(j%i==0){
            count=count+1;
        }
    }
    if(count==0){
        print("It is a prime number "+j+"\n");
        sum=sum+j;
    }else{
       
    }
      }
      print("sum "+sum)
    }
}
//6. Write a program to read an integer from user and convert it to binary and octal using user
//defined functions.
object Demo6
	{
		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);
		}
	}
Arrays.
//1. Write a program to find maximum and minimum of an array
object MyClass {
    

    def main(args: Array[String]) {
        print("Enter")
       var n=scala.io.StdIn.readInt();
       var arr=new Array[Int](n);
       
       for(i<-0 to n-1){
           arr(i)=scala.io.StdIn.readInt();
         
          
       }
       var temp=0;
     for(i<- 0 to n-2){
         for(j<- i+1 to n-1)
         {
             if(arr(i)>arr(j)){
                 temp=arr(i);
                 arr(i)=arr(j);
                 arr(j)=temp;
                 
             }
         }
     }
     print("Then minimun number is "+arr(0)+"\n");
     print("The maximun number is "+arr(n-1))
    }
}
//2. Write a program to calculate transpose of a matrix.

object MyClass {
    

    def main(args: Array[String]) {
        print("Enter")
    
       var A= Array.ofDim[Int](2,2);
       
       var c= Array.ofDim[Int](2,2);
     
      
     for(i<- 0 to 2-1){
         for(j<- 0 to 2-1)
         {
              print("Enter the element of the matix \t");
                 A(i)(j)=scala.io.StdIn.readInt();
                 
             }
         }
     
     
      for(i<- 0 to 2-1){
         for(j<- 0 to 2-1)
         {
                 print(A(j)(i)+" ");
                 
             }
             print("\n")
         }
     
     
    }
}
//3. Write a program to calculate determinant of a matrix
object Main{
    def main(args:Array[String]){
        var A=Array.ofDim[Int](2,2);
        for(i<- 0 to 1)
        {
            for(j<- 0 to 1)
            {
                A(i)(j)=scala.io.StdIn.readInt();
                
            }
        }
        var det=(A(0)(0)*A(1)(1))-(A(0)(1)*A(1)(0))
        print("The determinant is "+ det)
    }
}
//4. Write a program to check if the matrix is upper triangular or not.
object Main{
    def main(args:Array[String]){
         print("Enter the matrix ");
        var n=scala.io.StdIn.readInt();
        var A=Array.ofDim[Int](n,n);
        for(i<- 0 to n-1)
        {
            for(j<- 0 to n-1)
            {
                print("Enter the matrix vlaue")
                A(i)(j)=scala.io.StdIn.readInt();
                
            }
        }
        
        
        var isUpper = 1;
    for(i<-0 to n-1)
    {
        for(j<-0 to n-1)
        {
            if(j<i && A(i)(j)!=0)
            {
                isUpper = 0;
            }
        }
    }
    if(isUpper==1)
    {
        println("\nThis is a Upper triangular matrix")
        for(i<-0 to n-1)
        {
            for(j<-0 to n-1)
            {
                if(A(i)(j)!= 0)
                {
                    print(A(i)(j)+"\t");
                }
                else
                {
                    print("\t");
                }
 
            }
        print("\n\n");
        }
    }
    else
    {
        print("\nThis is Not a Upper triangular matrix.");
    }
        
       
    }
}





// 5. Write a program to sort the matrix using insertion sort.



object InsertionSort {
  def main(args: Array[String]) {
    val array = Array.ofDim[Int](2,2)
    array(0)(0)=3
    array(0)(1)=2
    array(1)(0)=1
    array(1)(1)=0
    println("Unsorted matrix ")
    for(i <- 0 until 2){
      for(j <- 0 until 2){
        print(array(i)(j)+"\t")
      }
      println()
    }
    println("Asceding sorted matrix ")
    var temp=0
    var a:Int=0
    var b:Int=0
    for (a <- 0 until 2) {
      for (b <- 0 until 2){
        if(a==0 && b==0){}
        else{
          temp = array(a)(b)
        }
        var k = a
        var l = b
        while (k >= 0 && l>=0 && temp < array(a)(b)) {
          array(a + 1)(b + 1) = array(a)(b)
            k = k-1;
            l = l-1;
        }
          array(a)(b) = temp 
          print(array(a)(b)+"\t")
      }
      println()
    }
  }
}

//6. Write a program for multiplication of two matrices(Validate number of rows andcolumns
//efore multiplication and give appropriate message)

object Sample {
  def main(args: Array[String]) {
    var Matrix1 = Array.ofDim[Int](2, 2)
    var Matrix2 = Array.ofDim[Int](2, 2)
    var Matrix3 = Array.ofDim[Int](2, 2)

    var i: Int = 0
    var j: Int = 0
    var k: Int = 0

    var sum: Int = 0

    printf("Enter elements of MATRIX1:\n")
    i = 0;
    while (i < 2) {
      j = 0;
      while (j < 2) {
        printf("ELEMENT(%d)(%d): ", i, j);
        Matrix1(i)(j) = scala.io.StdIn.readInt();
        j = j + 1;
      }
      i = i + 1;
    }

    printf("Enter elements of MATRIX2:\n")
    i = 0;
    while (i < 2) {
      j = 0;
      while (j < 2) {
        printf("ELEMENT(%d)(%d): ", i, j);
        Matrix2(i)(j) = scala.io.StdIn.readInt();
        j = j + 1;
      }
      i = i + 1;
    }

    //Multiply Matrix1 and Matrix2
    i = 0;
    while (i < 2) {
      j = 0;
      while (j < 2) {
        sum = 0;
        k = 0;
        while (k < 2) {
          sum = sum + (Matrix1(i)(k) * Matrix2(k)(j));
          k = k + 1;
        }
        Matrix3(i)(j) = sum;
        j = j + 1;
      }
      i = i + 1;
    }

    printf("MATRIX1:\n")
    i = 0;
    while (i < 2) {
      j = 0;
      while (j < 2) {
        printf("%d ", Matrix1(i)(j));
        j = j + 1;
      }
      i = i + 1;
      println();
    }

    printf("MATRIX2:\n")
    i = 0;
    while (i < 2) {
      j = 0;
      while (j < 2) {
        printf("%d ", Matrix2(i)(j));
        j = j + 1;
      }
      i = i + 1;
      println();
    }

    printf("Multiplication of Matrix1 and Matrix2:\n")
    i = 0;
    while (i < 2) {
      j = 0;
      while (j < 2) {
        printf("%d ", Matrix3(i)(j));
        j = j + 1;
      }
      i = i + 1;
      println();
    }
  }
}
String.

//1. Write a program to count uppercase letters in a string and convert it to lowercase and display
//the new string.




object Sample {
 

  def main(args: Array[String]): Unit = {
    var str = "Divya Manoj Harke";
    var count=0;
  
    for(i<-0 to str.length()-1){
        var ch:Char =str.charAt(i);
    if(ch>='A' &&  ch<='Z')
    {
    count=count+1;
    }
    }
    // Convert the above string to all lowercase.
    var lowerStr = str.toLowerCase();
    var upperStr = str.toUpperCase();
    
    println("uppercase letters:"+count)
    // Display the two strings for comparison.
    println("Original String: " + str);
    println("String in lowercase: " + lowerStr);
    //println("String in uppercase: " + upperStr);
  
}

}
//2.Write a program to read a character from user and count the number of occurrences ofthat
//character.





object myObject {
    def main(args: Array[String]) {
        print("Enter the string");
        var s:Char=scala.io.StdIn.readChar();
        val string = "Learn programming at IncludeHelp"
        val count = string.count(_ == s)
        println("This string is '" + string + "'")
        println("Count of 'r' in the string :" + count)
    }
}

//Q3. Write a program to read two strings. Remove the occurrence of second string in first string.

	object Demo3
	{
		def main(args:Array[String])
		{
			print("Enter First String = ")
			var st1 = scala.io.StdIn.readLine().toCharArray()

			print("Enter Second String = ")
			var st2 = scala.io.StdIn.readLine().toCharArray()

			for(i<-0 to (st2.length-1))
			{
				for(j<-0 to (st1.length-1))
				{
					if(st2(i) == st1(j))
					{
						st1(j) = '*' 
					}
				}
			}

			for(i<-0 to (st1.length-1))
			{
				println(st1(i))
			}

		}
	}

//4. Create array of strings and read a string from user. Display all the elements of array
//containing given string.


object Demo4
	{
		def main(args:Array[String])
		{
			print("How Many String Do u want to store = ")
			var n = scala.io.StdIn.readInt()

			var arr = new Array[String](n)

			for(a<-0 to (arr.length-1))
			{
				print("Enter String"+" "+(a+1)+" = ")
				arr(a) = scala.io.StdIn.readLine()
			}

			for(i<-arr)
			{
				println(i)
			}
		}
	}

Classes and Objects:
//1. Define a class CurrentAccount (accNo, name, balance, minBalance). Define appropriate
//constructors and operations withdraw(), deposit(), viewBalance(). Create an object and
//perform operations	

class CurrentAc(accN:Int,nam:String,Balanc:Double){
    var accNo=accN;
    var name=nam;
    var Balance=Balanc;
    var minB:Double=3000;
    def withdraw(){
        print("Enter the widdraw amount ")
        var w=scala.io.StdIn.readInt();
        if((Balance-w)>=minB){
            print("Withdraw suscceful "+"\n");
            Balance=Balance-w;
            print("The balance is "+Balance+"\n");
        }else{
            print("can't widthdraw balance insuffeciber "+"\n");
        }
    }
    def deposit(){
        print("Enter the amount you want to deposit ")
        var d=scala.io.StdIn.readInt();
        Balance=Balance+d;
        print("The Updated balance is "+Balance+"\n");
        
    }
    def viewBalance(){
        print("The account Balance is "+ Balance +"\n")
    }
    
    
    
}
object Main
	{
		def main(args:Array[String]): Unit =
		
		{
		     print("Enter the  Acount Number"+"\n");
		     val accNo=scala.io.StdIn.readInt();
		    print("Enter the name of the AcountHolder"+"\n");
		    var name =scala.io.StdIn.readLine();
		     print("Enter Balance"+"\n");
		     var Balance=scala.io.StdIn.readDouble();
		     var A=new CurrentAc(accNo,name,Balance);
	
	          var s=0;
	          do{
	              print("1.Enter 1 for withdraw \n");
		          print("2.Enter 2 for Deposit \n");
		          print("3. Enter 3 for View Balance \n")
	              print("4. Enter exit \n")
	              var n=scala.io.StdIn.readInt()
	           n match{
	              case 1=>A.withdraw();
	              case 2=>A.deposit();
	              case 3=>A.viewBalance();
	              case 4=>print("exiting ...");s=1;
	              case _ => println("Invalid choice entered, Try again...")
	          }
	          }while(s==0);
	          
		    
		    
		
		}
	}
//Q2. Define a class Employee (id, name, salary). Define methods accept() and display().//Display details of employee having maximum salary.

	class Empoley(id:Int, name:String)
	{  
	    var salary:Int = 0  //default value
	    def showDetails()
	    {  
		println(id+" "+name+" "+salary)  
	    }  
	    def this(id:Int, name:String,salary:Int)
	    {  
		this(id,name)       // Calling primary constructor (see parameters in class decalration)  
		this.salary = salary 
	    }  
	}  
	  
	object MainObject
	{  
	    def main(args:Array[String])
	    {
		var emp:Array[Empoley]=new Array[Empoley](4)
		emp(0)=new Empoley(101,"Rama",201241)
		emp(1)=new Empoley(10,"Ram",601341)
		emp(2)=new Empoley(103,"Ramay",801234)
		emp(3)=new Empoley(104,"Ramo",1001234)
		
		
		var salary:Empoley=new Empoley(0,"",0) // a temporary object
	salary = emp(0) //assigning first record/object to max
		var maxsalary=emp(0).salary // a temporary maxmarks variable to contain max value
		for( i <-0 to 3)
		  {
		    
		    if(emp(i).salary>maxsalary)
		    {
		      maxsalary=emp(i).salary
		      salary=emp(i)
		    }
		    
		  }
		  println("student details with maximum marks is")
		  println(salary.showDetails())
	      
	    }  
	}
//Q4. Create abstract class Shape with abstract functions volume() and display(). Extend two classes //Cube and Cylinder from it. Calculate volume of each and display 


	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=pi*r*r*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 Demo4
	{
	  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()
	  }
	}
	
	
Q5. Create class Project (id, name, location). Define parameterized constructor. Keep a count of each object created and display the details of each project.

	class Project(id:Int,name:String,location:String)
	{
	    var i:Int = 0;
	   
	    def display()
	    {
	       println(id+" "+name+" "+" "+location)
	    }
	}



	object Demo5 {
	   

	    def main(args: Array[String])
	    {
		print("How Many Object = ")
		var n = scala.io.readInt
	       
		var arr = Array[Project]=new Array[Project](n)
	       
		for(i<-1 to n)
		{
		    print("Enter id = ")
		    var id = scala.io.readInt
		   
		    print("Enter name = ")
		    var name = scala. io. StdIn. readLine()
		   
		    print("Enter Location = ")
		    var location = scala. io. StdIn. readLine()
		   
		    arr(i) = new Project(id,name,location)
		}
	       
		print("Number Of Object Created = "+n);

	    }
	}