Java Questions Part7 - Array and Matrix Program

1. WAP where int []arary= {1,2,3,4,5,6,7,8,9,10} leftRotateArray(array,3) and output should be {4,5,6,7,8,9,10,1,2,3} and rightRotateArray (array,3) output should be {8,9,10,1,2,3,4,5,6,7}

Answer:
import java.util.Arrays;

public class ArrayRotate {

 // Initialize array

 public static int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

 // n determine the number of times an array should be rotated.

 public static int n = 3;

 public static void main(String[] args) {

  rightRotation();

  leftRotation();

 }

 public static void rightRotation() {

  // Displays original array

  System.out.println("Original array: ");

  for (int i = 0; i < arr.length; i++) {

   System.out.print(arr[i] + " ");

  }

  // Rotate the given array by n times toward right

  for (int i = 0; i < n; i++) {

   int j, last;

   // Stores the last element of array

   last = arr[arr.length - 1];



   for (j = arr.length - 1; j > 0; j--) {

    // Shift element of array by one

    arr[j] = arr[j - 1];

   }

   // Last element of array will be added to the start of array.

   arr[0] = last;

  }

  System.out.println();

  // Displays resulting array after rotation

  System.out.println("Array after right rotation: ");

  for (int i = 0; i < arr.length; i++) {

   System.out.print(arr[i] + " ");

  }

 }

 public static void leftRotation() {

  Arrays.sort(arr);

  // Rotate the given array by n times toward left

  for (int i = 0; i < n; i++) {

   int j, first;

   // Stores the first element of the array

   first = arr[0];

   for (j = 0; j < arr.length - 1; j++) {

    // Shift element of array by one

    arr[j] = arr[j + 1];

   }

   // First element of array will be added to the end

   arr[j] = first;

  }

  System.out.println();

  // Displays resulting array after rotation

  System.out.println("Array after left rotation: ");

  for (int i = 0; i < arr.length; i++) {

   System.out.print(arr[i] + " ");

  }
 }
}

Output:
Original array: 

1 2 3 4 5 6 7 8 9 10 

Array after right rotation: 

8 9 10 1 2 3 4 5 6 7 

Array after left rotation: 

4 5 6 7 8 9 10 1 2 3

2. An Array of numbers given. .Find the largest two number and print it.

Answer:
import java.util.Scanner;

public class largest_and_second

{

 public static void main (String[] args)

 {

  Scanner scn = new Scanner (System.in);

  System.out.print("Enter no. of elements you want in array:");

                int n = scn.nextInt();



  int array[] = new int[n];

                System.out.println("Enter all the elements:");

  for (int i = 0; i < array.length; i++)

  {

   array[i] = scn.nextInt();

  }


  int largest1, largest2, temp;


  largest1 = array[0];

  largest2 = array[1];


  if (largest1 < largest2)

  {

   temp = largest1;

   largest1 = largest2;

   largest2 = temp;

  }

  for (int i = 2; i < array.length; i++)

  {

   if (array[i] > largest1)

   {

    largest2 = largest1;

    largest1 = array[i];

   }

   else if (array[i] > largest2 && array[i] != largest1)

   {

    largest2 = array[i];

   }

  }

  System.out.println ("The First largest is " + largest1);

  System.out.println ("The Second largest is " + largest2);

 }

}

Output:
Enter no. of elements you want in array:5

Enter all the elements:

1

5

4

8

7

The First largest is 8

The Second largest is 7

3. How to convert array into Arraylist?

Answer:
import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

public class Tester {

   public static void main(String args[]) {

      String[] array = {"a", "b", "c", "d", "e"};

      //Method 1

      List<String> list = Arrays.asList(array);          

      System.out.println(list);

      //Method 2

      List<String> list1 = new ArrayList<String>();

      Collections.addAll(list1, array);

      System.out.println(list1);

      //Method 3

      List<String> list2 = new ArrayList<String>();

      for(String text:array) {

         list2.add(text);

      }

      System.out.println(list2);

   }  

}

Output:
[a, b, c, d, e]

[a, b, c, d, e]

[a, b, c, d, e]

4. Given an array int a[]=int a{1,2,2,3,4,4,5,5,6,7} find duplicate and store in different array.

Answer:
import java.util.ArrayList;

 public class FindDuplicateAndStoreInArray {

 public static void main(String[] args) {

  // Initialize array

  int[] arr = new int[] { 1,2,2,3,4,4,5,5,6,7};

  // Creating an ArrayList

  ArrayList<Integer> arrlist = new ArrayList<>();

  System.out.println("Duplicate elements in given array: ");

  // Searches for duplicate element

  for (int i = 0; i < arr.length; i++) {

   for (int j = i + 1; j < arr.length; j++) {

    if (arr[i] == arr[j]) {

     System.out.println(arr[j]);

     // Storing duplicate elements in an arrayList

     arrlist.add(arr[j]);

    }

   }

  }

  // Converting ArrayList to an Array

  Integer[] arr1 = new Integer[arrlist.size()];

  arr1 = arrlist.toArray(arr1);

  for (Integer x : arr1)

   System.out.print(x + " ");

 }

}

Output:
Duplicate elements in given array: 

2

4

5

2 4 5

5. Find duplicate integer from an array.

Answer:
class RepeatElement  

{ 

    void printRepeating(int arr[], int size)  

    { 

        int i, j; 

        System.out.println("Repeated Elements are :"); 

        for (i = 0; i < size; i++)  

        { 

            for (j = i + 1; j < size; j++)  

            { 

                if (arr[i] == arr[j])  

                    System.out.print(arr[i] + " "); 

            } 

        } 

    } 

    public static void main(String[] args)  

    { 

        RepeatElement repeat = new RepeatElement(); 

        int arr[] = {4, 2, 4, 5, 2, 3, 1}; 

        int arr_size = arr.length; 

        repeat.printRepeating(arr, arr_size); 

    } 

}

Output:
Repeating elements are 4 2

6. Find duplicate and store in an array and find unique and store in a separate array.

Answer:
import java.util.ArrayList; 

public class FindDuplicateAndStoreInArray {

 // Initialize array

 public static int[] arr = new int[] { 1, 2, 2, 3, 4, 4, 5, 5, 6, 7 };

 public static void main(String[] args) {

  findDuplicate();

  findUnique();

 }

 public static void findDuplicate() {

  // Creating an ArrayList

  ArrayList<Integer> arrlist = new ArrayList<>();

  System.out.println("Duplicate elements in given array: ");

  // Searches for duplicate element

  for (int i = 0; i < arr.length; i++) {

   for (int j = i + 1; j < arr.length; j++) {

    if (arr[i] == arr[j]) {

     System.out.println(arr[j]);

     // Storing duplicate elements in an arrayList

     arrlist.add(arr[j]);

    }

   }

  }

  // Converting ArrayList to an Array

  Integer[] arr1 = new Integer[arrlist.size()];

  arr1 = arrlist.toArray(arr1);

  System.out.print("Array Of Duplicate Elements:");

  for (Integer x : arr1)

   System.out.print(+x + " ");

 }

 public static void findUnique() {

  // Creating an ArrayList

  ArrayList<Integer> arrlist1 = new ArrayList<>();

  System.out.println("");

  System.out.println("Unique elements in given array: ");

  // Searches for Unique elements

  int count = 0, flag = 0;

  for (int i = 0; i < arr.length; i++) {

   for (int j = 0; j < arr.length; j++) {

    if (i != j) {

     if (arr[i] != arr[j]) {

      flag = 1;

     } else {

      flag = 0;

      break;

     }

    }
   }

   if (flag == 1) {

    count++;

    System.out.println(arr[i]);

    arrlist1.add(arr[i]);

   }

  }

  // Converting ArrayList to an Array

  Integer[] arr2 = new Integer[arrlist1.size()];

  arr2 = arrlist1.toArray(arr2);

  System.out.print("Array Of Unique Elements:");

  for (Integer y : arr2)

   System.out.print(+y + " ");

 }

}

Output:
Duplicate elements in given array: 

2

4

5

Array Of Duplicate Elements:2 4 5 

Unique elements in given array: 

1

3

6

7

Array Of Unique Elements:1 3 6 7

7. Write a Java program for accessing all the elements of the two dimensional array int[][] a = {{5,2,9},{4,6,8}}; using for loop? 

Answer:
import java.util.Arrays;

 public class Access2DArray {

 public static void main(String args[]) {

  // initializing two dimensional array as literal

  String[][] names = { { "John", "Smith" }, { "Javin", "Paul" }, { "James", "Gosling" }, };  // how to initialize two dimensional array in Java

  // using for loop

  int[][] a = { { 5, 2, 9 }, { 4, 6, 8 }, };

  // how to print

  System.out.println("Using For Loop");

  for (int i = 0; i < a.length; ++i) {

   for (int j = 0; j < a[i].length; ++j) {

    System.out.print(a[i][j] + "\t");

   }

   System.out.println("\n");

  }

  System.out.println("Using For each Loop");

  // now let's print a two dimensional array in Java

  for (int[] a1 : a) {

   for (int i : a1) {

    System.out.print(i + "\t");

   }

   System.out.println("\n");

  }

  // printing 2D array using Arrays.deepToString() method

  System.out.println("Another way to print 2D arrays");

  System.out.println(Arrays.deepToString(a));

 }

}


Output:
Using For Loop

5 2 9 

4 6 8 

Using For each Loop

5 2 9 

4 6 8 

Another way to print 2D arrays

[[5, 2, 9], [4, 6, 8]]

8. Write a Java program for sorting an array?

Answer:
import java.util.Scanner;

public class Ascending _Order 

{

    public static void main(String[] args) 

    {

        int n, temp;

        Scanner s = new Scanner(System.in);

        System.out.print("Enter no. of elements you want in array:");

        n = s.nextInt();

        int a[] = new int[n];

        System.out.println("Enter all the elements:");

        for (int i = 0; i < n; i++) 

        {

            a[i] = s.nextInt();

        }

        for (int i = 0; i < n; i++) 

        {

            for (int j = i + 1; j < n; j++) 

            {

                if (a[i] > a[j]) 

                {

                    temp = a[i];

                    a[i] = a[j];

                    a[j] = temp;

                }

            }

        }

        System.out.print("Ascending Order:");

        for (int i = 0; i < n - 1; i++) 

        {

            System.out.print(a[i] + ",");

        }

        System.out.print(a[n - 1]);

    }

}


Output:
Enter no. of elements you want in array:5

Enter all the elements:

4

3

2

6

1

Ascending Order:1,2,3,4,6

9. Write a Java program to create an integer array int[] a = {9,3,6,8,4,7} and print the elements of the array in reverse?

Answer:
public class ReverseArray {  

    public static void main(String[] args) {  

        //Initialize array  

        int [] arr = new int [] {9,3,6,8,4,7};  

        System.out.println("Original array: ");  

        for (int i = 0; i < arr.length; i++) {  

            System.out.print(arr[i] + " ");  

        }  

        System.out.println();  

        System.out.println("Array in reverse order: ");  

        //Loop through the array in reverse order  

        for (int i = arr.length-1; i >= 0; i--) {  

            System.out.print(arr[i] + " ");  

        }  

    }  

}  

Output:
Original array: 

9 3 6 8 4 7 

Array in reverse order: 

7 4 8 6 3 9

10. Write a Java program to print alternative elements in a String array String[] a = {“One”,”Two”,”Three”,”Four”} ?

Answer:
public class AlternateElementsInStringArray {

 public static void main(String[] args) {

  String[] a = new String[] { "One", "Two", "Three", "Four" };

  for (int i = 0; i < a.length; i = i + 2) {

   System.out.println(a[i]);

  }

 }

}

Output:


One

Three

11. Write a Java program to find the greatest number in an integer array int[] a = {9,3,6,4,8,5} ?

Answer:
public class FindBiggestSmallestNumber {

 public static void main(String[] args) {

        int numbers[] = new int[]{9,3,6,4,8,5};

        int smallest = numbers[0];

        int biggest = numbers[0];

       

        for(int i=1; i< numbers.length; i++)

        {

                if(numbers[i] > biggest)

                        biggest = numbers[i];

                else if (numbers[i] < smallest)

                        smallest = numbers[i];

               

        }

       

        System.out.println("Largest Number is : " + biggest);

        //System.out.println("Smallest Number is : " + smallest);

}

}


Output:
Largest Number is : 9

12. Write a Java program to find the Smallest number in an integer array int[] a = {9,3,6,4,8,5} ?
Answer:
public class FindBiggestSmallestNumber {



 public static void main(String[] args) {

        int numbers[] = new int[]{9,3,6,4,8,5};

        int smallest = numbers[0];

        int biggest = numbers[0];

       

        for(int i=1; i< numbers.length; i++)

        {

                if(numbers[i] > biggest)

                        biggest = numbers[i];

                else if (numbers[i] < smallest)

                        smallest = numbers[i];
               

        }
        //System.out.println("Largest Number is : " + biggest);

        System.out.println("Smallest Number is : " + smallest);

}

}

Output:
Smallest Number is : 3

13. How to find missing number in an Array?

Answer:
public class MissingNumber {

 public static void main(String[] args) {

  int[] arr1 = { 7, 5, 6, 1, 4, 2 };

  System.out.println("Missing number from array arr1: " + missingNumber(arr1));

  int[] arr2 = { 5, 3, 1, 2 };

  System.out.println("Missing number from array arr2: " + missingNumber(arr2));

 }

 public static int missingNumber(int[] arr) {

  int n = arr.length + 1;

  int sum = n * (n + 1) / 2;

  int restSum = 0;

  for (int i = 0; i < arr.length; i++) {

   restSum += arr[i];

  }

  int missingNumber = sum - restSum;

  return missingNumber;

 }

}

Output:
Missing number from array arr1: 3

Missing number from array arr2: 4

14. Write a Java program to demonstrate creating an Array?

Answer:
Syntax to Declare an Array in Java

dataType[] arr; (or)  

dataType []arr; (or)  

dataType arr[];  

Instantiation of an Array in Java

arrayRefVar=new datatype[size];  

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization


15. Write a Java program to demonstrate creating Multidimensional array?

Answer:
Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)  

dataType [][]arrayRefVar; (or)  

dataType arrayRefVar[][]; (or)  

dataType []arrayRefVar[];   

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column  

Example to initialize Multidimensional Array in Java

arr[0][0]=1;  

arr[0][1]=2;  

arr[0][2]=3;  

arr[1][0]=4;  

arr[1][1]=5;  

arr[1][2]=6;  

arr[2][0]=7;  

arr[2][1]=8;  

arr[2][2]=9;  


16. Write a Java program to add two matrix?

Answer:
public class MatrixAdditionExample{  

public static void main(String args[]){  

//creating two matrices    

int a[][]={{1,3,4},{2,4,3},{3,4,5}};    

int b[][]={{1,3,4},{2,4,3},{1,2,4}};    

    

//creating another matrix to store the sum of two matrices    

int c[][]=new int[3][3];  //3 rows and 3 columns  

    

//adding and printing addition of 2 matrices    

for(int i=0;i<3;i++){    

for(int j=0;j<3;j++){    

c[i][j]=a[i][j]+b[i][j];    //use - for subtraction  

System.out.print(c[i][j]+" ");    

}    

System.out.println();//new line    

}    

}}  


Output:
2 6 8

4 8 6

4 6 9

17. Write a Java program to multiply two matrix?

Answer:
public class MatrixMultiplicationExample{  

public static void main(String args[]){  

//creating two matrices    

int a[][]={{1,1,1},{2,2,2},{3,3,3}};    

int b[][]={{1,1,1},{2,2,2},{3,3,3}};    

   
//creating another matrix to store the multiplication of two matrices    

int c[][]=new int[3][3];  //3 rows and 3 columns  


//multiplying and printing multiplication of 2 matrices    

for(int i=0;i<3;i++){    

for(int j=0;j<3;j++){    

c[i][j]=0;      

for(int k=0;k<3;k++)      

{      

c[i][j]+=a[i][k]*b[k][j];      

}//end of k loop  

System.out.print(c[i][j]+" ");  //printing matrix element  

}//end of j loop  

System.out.println();//new line    

}    

}}  

Output:
6 6 6 

12 12 12 

18 18 18

18. Write a Java program to get the transpose of matrix?

Answer:
public class MatrixTransposeExample{  

public static void main(String args[]){  

//creating a matrix  

int original[][]={{1,3,4},{2,4,3},{3,4,5}};    

    
//creating another matrix to store transpose of a matrix  

int transpose[][]=new int[3][3];  //3 rows and 3 columns  
  

//Code to transpose a matrix  

for(int i=0;i<3;i++){    

for(int j=0;j<3;j++){    

transpose[i][j]=original[j][i];  

}    

}    

  

System.out.println("Printing Matrix without transpose:");  

for(int i=0;i<3;i++){    

for(int j=0;j<3;j++){    

System.out.print(original[i][j]+" ");    

}    

System.out.println();//new line    

}    

System.out.println("Printing Matrix After Transpose:");  

for(int i=0;i<3;i++){    

for(int j=0;j<3;j++){    

System.out.print(transpose[i][j]+" ");    

}    

System.out.println();//new line    

}    

}}  

Output:
Printing Matrix without transpose:

1 3 4 

2 4 3 

3 4 5 

Printing Matrix After Transpose:

1 2 3 

3 4 4 

4 3 5

19. Write a Java program for printing the Multiplication table?

Answer:
import java.util.Scanner;

class MultiplicationTable

{

  public static void main(String args[])

  {

    int n, c;

    System.out.println("Enter an integer to print it's multiplication table");

    Scanner in = new Scanner(System.in);

    n = in.nextInt();

    System.out.println("Multiplication table of " + n);



    for (c = 1; c <= 10; c++)

      System.out.println(n + "*" + c + " = " + (n*c));

  }

}


Output:
Enter an integer to print it's multiplication table

9

Multiplication table of 9

9*1 = 9

9*2 = 18

9*3 = 27

9*4 = 36

9*5 = 45

9*6 = 54

9*7 = 63

9*8 = 72

9*9 = 81

9*10 = 90

20. Write a Java program for pascle triangle?

Answer:
public class PascalsTriangle {

   static int factorial(int n) {

      int f;

      for(f = 1; n > 1; n--){

         f *= n;

      }

      return f;

   }

   static int ncr(int n,int r) {

      return factorial(n) / ( factorial(n-r) * factorial(r) );

   }

   public static void main(String args[]){

      System.out.println();

      int n, i, j;

      n = 5;



      for(i = 0; i <= n; i++) {

         for(j = 0; j <= n-i; j++){

            System.out.print(" ");

         }

         for(j = 0; j <= i; j++){

            System.out.print(" "+ncr(i, j));

         }

         System.out.println();

      }

   }

}

Output:

             1

          1     1

        1    2    1

      1    3   3     1

   1    4     6    4    1

1   5   10     10    5    1

No comments:

Post a Comment