Automation QA Testing Course Content

Java Array Programs

Question 1
Write Java statements that do the following:
a) Declare an array numArray of 15 elements of type int.
b) Output the value of the tenth element of the array alpha.
c) Set the value of the fifth element of the array alpha to 35.
d) Set the value of the ninth element of the array alpha to the sum of the sixth and thirteenth elements of the array alpha.
 //Declare an array numArray of 15 elements of type int
 int[] numArray = new int[15];
        
 //Output the value of the tenth element of the array alpha.
 System.out.println(alpha[9]);
        
 //Set the value of the fifth element of the array alpha to 35.
 alpha[4] = 35;
        
 //Set the value of the ninth element of the array alpha to the sum of 
 //the sixth and thirteenth elements of the array alpha
 alpha[8] = alpha[5] + alpha[12];
Question 2
a) Write a statement that declares a string array initialized with the following strings:
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" and "Saturday".
b) Write a loop that displays the contents of each element in the array that you declared.

 // Declare a string array and initialize
 String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" , "Saturday"};      
        
 // Displays the contents of each element
 for (String day : days)
 {
    System.out.println(day);
 }
Question 3
Write a program that creates an array of 10 elements size. Your program should prompt the user to input numbers in array and then display the sum of all array elements.

import java.util.Scanner;

public class ArraySum
{
   public static void main(String[] args)
   {
      final int SIZE = 10;

      // Create an array to hold numbers.
      int[] numbers = new int[SIZE];

      Scanner console = new Scanner(System.in);
      System.out.println("Enter " + SIZE + " numbers.");

      // Get employees' salary.
      for (int i = 0; i < SIZE; i++)
      {
         numbers[i] = console.nextInt();
      }

      int sum = 0;

      // Calculate the sum.
      for (int i = 0; i < SIZE; i++)
      {
         sum += numbers[i];
      }
      
      System.out.println("Sum of numbers: " + sum);
   }
}
Question 4
The variable list1 and list2 are reference arrays that each have 5 elements. Write code that copies the values in list1 to list2. Values in list1 are input by user.

import java.util.Scanner;

public class ArrayCopy
{
   public static void main(String[] args)
   {
      final int SIZE = 5;

      int[] list1 = new int[SIZE];
      int[] list2 = new int[SIZE];

      Scanner console = new Scanner(System.in);
      System.out.println("Enter " + SIZE + " numbers.");

      // Get value in list1
      for (int i = 0; i < SIZE; i++)
      {
          list1[i] = console.nextInt();
      }

      // Copy elements in list2.
      for (int i = 0; i < SIZE; i++)
      {
          list2[i] = list1[i];
      }
      
      // Display elements of list2.
      System.out.println("Elements of list2 are: ");
      for (int i = 0; i < SIZE; i++)
      {
          System.out.println(list2[i]);
      }
   }
}
Question 5
Write a Java program to reverse the element of an integer 1-D array.

import java.util.Scanner;

public class ReverseArray
{
   public static void main(String[] args)
   {
      int size;
      
      Scanner console = new Scanner(System.in);

      System.out.print("Enter the size of the array: ");
      size = console.nextInt();

      int[] list = new int[size];

      System.out.println("Enter " + list.length + " integers.");

      for (int i = 0; i < list.length; i++)
      {
         list[i] = console.nextInt();
      }

      int temp;
      // Reversing elements of the array.
      for (int i = 0; i < list.length / 2; i++)
      {
         temp = list[i];
         list[i] = list[list.length - i - 1];
         list[list.length - i - 1] = temp;      
      }

      System.out.println("Reverse array: ");
      // Display the reverse array.
      for (int i = 0; i < list.length; i++)
      {
         System.out.println(list[i]);
      }
   }
}
Question 6
Write a Java program to find the largest and smallest element of an array.

import java.util.Scanner;

public class MaxMinElement
{
   public static void main(String[] args)
   {
      int size;
      
      Scanner console = new Scanner(System.in);

      System.out.print("Enter the size of the array: ");
      size = console.nextInt();

      int[] list = new int[size];

      System.out.println("Enter " + list.length + " integers.");

      for (int i = 0; i < list.length; i++)
      {
         list[i] = console.nextInt();
      }

      int max = list[0];
      int min = list[0];
      
      for (int i = 1; i < list.length; i++)
      {
         if(list[i] > max)
         {
             max = list[i];
         }
         if(list[i] < min)
         {
             min = list[i];
         }          
      }

      System.out.println("Largest element: " + max 
                          + " Smallest element: " + min);
   }
}
Question 7
Write a menu driven Java program with following option
a. Accept elements of an array
b. Display elements of an array
c. Search the element within array given by user
d. Sort the array using bubble sort method
Write methods for all options. The methods should be static and have one parameter name of the array.

import java.util.Scanner;

public class SearchSortArray 
{
    static Scanner console = new Scanner(System. in );
    
    public static void main(String[] args) 
    {
        int size;

        System.out.print("Enter the size of the array: ");
        size = console.nextInt();
        int[] list = new int[size];
        
        int option;
        do 
        {
            System.out.println("Menu ");
            System.out.println("1. Read Array");
            System.out.println("2. Display Array");
            System.out.println("3. Search an Item in Array");
            System.out.println("4. Sort the Array");
            System.out.println("5. Exit");
            System.out.print("Select an Option : ");
            option = console.nextInt();
        
            switch (option) 
            {
                case 1:
                    readArray(list);
                    break;
                case 2:
                    displayArray(list);
                    break;
                case 3:
                    System.out.print("Enter the number you want to search: ");
                    int item = console.nextInt();
                    int index = searchArray(list, item);
                    if (index == -1) 
                    {
                        System.out.println("Item not found");
                    }
                    else 
                    {
                        System.out.println("Item found at position " + (index + 1));
                    }
                    break;
                case 4:
                    System.out.println("Sorted array :");
                    sortArray(list);
                    displayArray(list);
                    break;
            }
        } while (option != 5);
    }
    
    static void readArray(int[] array) 
    {
        for (int i = 0; i < array.length; i++)
        {
           array[i] = console.nextInt();
        }
    }

    static void displayArray(int[] array) 
    {
        for (int i = 0; i < array.length; i++)
        {
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }

    static int searchArray(int[] array, int data) 
    {
        for (int i = 0; i < array.length; i++)
        {
            if(array[i] == data)
            {
                return i;
            }
        }        
        return -1;
    }
    
    static void sortArray(int[] array) 
    {
        for (int i = 0; i < array.length - 1; i++)
        {
            for(int j = 0; j < array.length -i-1; j++)
            {
                if(array[j] > array[j+1])
                {
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                }
            }
        }          
    }
    
}
-----------------------------------------------------------------------------------

Program to left rotate the elements of an array

In this program, we need to rotate the elements of an array towards the left by the specified number of times. In the left rotation, each element of the array will be shifted to its left by one position and the first element of the array will be added to end of the list. This process will be followed for a specified number of times.
Algorithm
  • Step 1 : Let inputArray be an array to be rotated left by n positions.
    Step 2 : Print inputArray before rotation.
    System.out.println(Arrays.toString(inputArray));
    Step 3 : Define one temporary variable temp which will hold the first element of inputArray.
    int temp;
    Step 4 : First copy the first element of inputArray into temp and then shift all elements one position left. After shifting, copy back temp into inputArray as last element. Repeat this step times.
    for (int i = 0; i < n; i++) {         temp = inputArray[0];
            for (int j = 0; j < inputArray.length-1; j++)         {                 inputArray[j] = inputArray[j+1];         }
            inputArray[inputArray.length – 1] = temp; }
    Step 5 : Print the rotated inputArray.
    System.out.println(Arrays.toString(inputArray));
  1. class RotateLeft {  
  2.     public static void main(String[] args) {  
  3.         //Initialize array  
  4.         int [] inputArray = new int [] {12345};  
  5.         //n determine the number of times an array should be rotated  
  6.         int n = 3;  
  7.        int temp;
             
            for (int i = 0; i < n; i++)
            {
                temp = inputArray[0];
                 
                for (int j = 0; j < inputArray.length-1; j++)
                {
                    inputArray[j] = inputArray[j+1];
                }
                 
                inputArray[inputArray.length - 1] = temp;
            }
             
            System.out.println("Input Array After Left Rotation By "+n+" Positions :");
             
            System.out.println(Arrays.toString(inputArray));
        }
  8. }  
 Original Array:
1   2   3   4   5
Array after left rotation:
4   5   1   2   3

Program to print the duplicate elements of an array

In this program, we need to print the duplicate elements present in the array. This can be done through two loops. The first loop will select an element and the second loop will iteration through the array by comparing the selected element with other elements. If a match is found, print the duplicate element.
Program to print the duplicate elements of an array
In the above array, the first duplicate will be found at the index 4 which is the duplicate of the element (2) present at index 1. So, duplicate elements in the above array are 2, 3 and 8.

Algorithm

  • STEP 1: START
  • STEP 2: INITIALIZE arr[]= {1, 2, 3, 4, 2, 7, 8, 8, 3}.
  • STEP 3: PRINT "Duplicate elements in given array:"
  • STEP 4: REPEAT STEP 5 to STEP 7 for(i=0; i<arr.length; i++)
  • STEP 5: REPEAT STEP 6 and STEP 7 for(j=i+1; j<arr.length; j++)
  • STEP 6: if(arr[i] == arr[j])
  • STEP 7: PRINT arr[j]
  • STEP 8: END

Program:

  1. public class DuplicateElement {  
  2. public static void main(String[] args) {  
  3.         //Initialize array  
  4.         int [] arr = new int [] {123427883};  
  5.         System.out.println("Duplicate elements in given array: ");  
  6.         //Searches for duplicate element  
  7.         for(int i = 0; i < arr.length; i++) {  
  8.             for(int j = i + 1; j < arr.length; j++) {  
  9.                 if(arr[i] == arr[j])  
  10.                     System.out.println(arr[j]);  
  11.             }  
  12.         }  
  13.     }  
  14. }  
------------------------------------------------------------------------------------

Java Program to right rotate the elements of an array

In this program, we need to rotate the elements of array towards its right by the specified number of times. An array is said to be right rotated if all elements of the array are moved to its right by one position. One approach is to loop through the array by shifting each element of the array to its next position. The last element of the array will become the first element of the rotated array.
Algorithm
  • Step 1 : Let inputArray be an array to be rotated right by n positions.
    Step 2 : Print inputArray before rotation.
  • System.out.println(Arrays.toString(inputArray));
    Step 3 : Define one temporary variable temp which will hold the last element of inputArray.
    int temp;
    Step 4 : First copy the last element of inputArray into temp and then shift all elements one position right. After shifting, copy back temp as first element of inputArray. Repeat this step times.
    for (int i = 1; i <= n; i++) {         temp = inputArray[inputArray.length-1];
            for (int j = inputArray.length-1; j > 0; j–)        {                 inputArray[j] = inputArray[j-1];        }
           inputArray[0] = temp; }
    Step 5 : Print the rotated inputArray.
    System.out.println(Arrays.toString(inputArray));

Program:

  1. class RotateRight {    
  2.  public static void main(String[] args) {    
  3.         //Initialize array     
  4.         int [] arr = new int [] {12345};     
  5.         //n determine the number of times an array should be rotated.    
  6.         int n = 3;    
  7.            
  8.       System.out.println("Input Array Before Rotation :");
             
            System.out.println(Arrays.toString(inputArray));
             
            int temp;
             
            for (int i = 1; i <= n; i++)
            {
                temp = inputArray[inputArray.length-1];
                 
                for (int j = inputArray.length-1; j > 0; j--)
                {
                    inputArray[j] = inputArray[j-1];
                }
                 
                inputArray[0] = temp;
            }
             
            System.out.println("Input Array After Right Rotation By "+n+" Positions :");
             
            System.out.println(Arrays.toString(inputArray));
        }
---------------------------------------------------------------------------------

Program to find the frequency of each element in the array

In this program, we have an array of elements to count the occurrence of its each element. One of the approaches to resolve this problem is to maintain one array to store the counts of each element of the array. Loop through the array and count the occurrence of each element as frequency and store it in another array fr.
  1. 1    2   8  3   2   2   2   5   1  
In the given array, 1 has appeared two times so its frequency be 2 and 2 has appeared four times so have frequency 4 and so on.

Algorithm

  • STEP 1: START
  • STEP 2: INITIALIZE arr[] ={1, 2, 8, 3, 2, 2, 2, 5, 1 }.
  • STEP 3: CREATE fr[] of arr[] length.
  • STEP 4: SET visited = -1.
  • STEP 5: REPEAT STEP 6 to STEP 9 for(i=0;i<arr.length;i++)
  • STEP 6: SET count = 1
  • STEP 7: REPEAT STEP 8 for(j=i+1;j<arr.length;j++)
  • STEP 8: if(arr[i]==arr[j]) then             count++             fr[j] =visited
  • STEP 9: if(fr[i]!=visited) then             fr[i]=count
  • STEP 10: PRINT "------------"
  • STEP 11: PRINT "Element | Frequency"
  • STEP 12: PRINT "-------------"
  • STEP 13: REPEAT STEP 14 for(i=0;i<fr.length;i++)
  • STEP 14: if(fr[i]!=visited) then             PRINT arr[i] and fr[i]
  • STEP 15: PRINT "-------------"
  • STEP 16: END

Program:

  1. public class Frequency {  
  2.     public static void main(String[] args) {  
  3.         //Initialize array  
  4.         int [] arr = new int [] {128322251};  
  5.         //Array fr will store frequencies of element  
  6.         int [] fr = new int [arr.length];  
  7.         int visited = -1;  
  8.         for(int i = 0; i < arr.length; i++){  
  9.             int count = 1;  
  10.             for(int j = i+1; j < arr.length; j++){  
  11.                 if(arr[i] == arr[j]){  
  12.                     count++;  
  13.                     //To avoid counting same element again  
  14.                     fr[j] = visited;  
  15.                 }  
  16.             }  
  17.             if(fr[i] != visited)  
  18.                 fr[i] = count;  
  19.         }  
  20.   
  21.         //Displays the frequency of each element present in array  
  22.         System.out.println("---------------------------------------");  
  23.         System.out.println(" Element | Frequency");  
  24.         System.out.println("---------------------------------------");  
  25.         for(int i = 0; i < fr.length; i++){  
  26.             if(fr[i] != visited)  
  27.                 System.out.println("    " + arr[i] + "    |    " + fr[i]);  
  28.         }  
  29.         System.out.println("----------------------------------------");  
  30.     }}  
------------------------------------------------------------------------------------

Java Program to sort the elements of an array in ascending order

In this program, we need to sort the given array in ascending order such that elements will be arranged from smallest to largest. This can be achieved through two loops. The outer loop will select an element, and inner loop allows us to compare selected element with rest of the elements.
Java Program to sort the elements of an array in ascending order
Elements will be sorted in such a way that the smallest element will appear on extreme left which in this case is 1. The largest element will appear on extreme right which in this case is 8.

Algorithm

  • STEP 1: START
  • STEP 2: INITIALIZE arr[] ={5, 2, 8, 7, 1 }.
  • STEP 3: SET temp =0
  • STEP 4: PRINT "Elements of Original Array"
  • STEP 5: REPEAT STEP 6 UNTIL i<arr.length             //for(i=0; i<arr.length; i++)
  • STEP 6: PRINT arr[i]
  • STEP 7: REPEAT STEP 8 to STEP 9 UNTIL i<arr.length             //for(i=0; i<arr.length; i++ )
  • STEP 8: REPEAT STEP 9 UNTIL j<arr.length             //for(j=i+1;j<arr.length;j++)
  • STEP 9: if(arr[i]>arr[j]) then             temp = arr[i]             arr[i]=arr[j]             arr[j]=temp
  • STEP 10: PRINT new line
  • STEP 11: PRINT "Elements of array sorted in ascending order"
  • STEP 12: REPEAT STEP 13 UNTIL i<arr.length             //for(i=0;i<arr.length;i++)
  • STEP 13: PRINT arr[i]
  • STEP 14: END

Program:

  1. public class AscendingOrder 
  2. {
  3.     public static void main(String[] args) 
  4.     {
  5.         int n, temp;
  6.         Scanner s = new Scanner(System.in);
  7.         System.out.print("Enter no. of elements you want in array:");
  8.         n = s.nextInt();
  9.         int a[] = new int[n];
  10.         System.out.println("Enter all the elements:");
  11.         for (int i = 0; i < n; i++) 
  12.         {
  13.             a[i] = s.nextInt();
  14.         }
  15.         for (int i = 0; i < n; i++) 
  16.         {
  17.             for (int j = i + 1; j < n; j++) 
  18.             {
  19.                 if (a[i] > a[j]) 
  20.                 {
  21.                     temp = a[i];
  22.                     a[i] = a[j];
  23.                     a[j] = temp;
  24.                 }
  25.             }
  26.         }
  27.         System.out.print("Ascending Order:");
  28.         for (int i = 0; i < n; i++) 
  29.         {
  30.             System.out.print(a[i] + ",");
  31.         }
  32.         System.out.print(a[n - 1]);
  33.     }
  34. }
---------------------------------------------------------------------------------

Java Program to sort the elements of an array in descending order

In this program, we need to sort the given array in descending order such that elements will be arranged from largest to smallest. This can be achieved through two loops. The outer loop will select an element, and inner loop allows us to compare selected element with rest of the elements.
Java Program to sort the elements of an array in descending order
Elements will be sorted in such a way that largest element will appear on extreme left which in this case is 8. The smallest element will appear on extreme right which in this case is 1.

Algorithm

  • STEP 1: START
  • STEP 2: INITIALIZE arr[] ={5, 2, 8, 7, 1 }.
  • STEP 3: SET temp =0
  • STEP 4: PRINT "Elements of Original Array"
  • STEP 5: REPEAT STEP 6 UNTIL i<arr.length             //for(i=0; i<arr.length; i++)
  • STEP 6: PRINT arr[i]
  • STEP 7: REPEAT STEP 8 to STEP 9 UNTIL i<arr.length             //for(i=0; i<arr.length; i++ )
  • STEP 8: REPEAT STEP 9 UNTIL j<arr.length             //for(j=i+1;j<arr.length;j++)
  • STEP 9: if(arr[i]<arr[j]) then             temp = arr[i]             arr[i]=arr[j]             arr[j]=temp
  • STEP 10: PRINT new line
  • STEP 11: PRINT "Elements of array sorted in descending order"
  • STEP 12: REPEAT STEP 13 UNTIL i<arr.length             //for(i=0;i<arr.length;i++)
  • STEP 13: PRINT arr[i]
  • STEP 14: END

Program:

  1. import java.util.Scanner;
  2. public class DescendingOrder
  3. {
  4.     public static void main(String[] args) 
  5.     {
  6.         int n, temp;
  7.         Scanner s = new Scanner(System.in);
  8.         System.out.print("Enter no. of elements you want in array:");
  9.         n = s.nextInt();
  10.         int a[] = new int[n];
  11.         System.out.println("Enter all the elements:");
  12.         for (int i = 0; i < n; i++) 
  13.         {
  14.             a[i] = s.nextInt();
  15.         }
  16.         for (int i = 0; i < n; i++) 
  17.         {
  18.             for (int j = i + 1; j < n; j++) 
  19.             {
  20.                 if (a[i] < a[j]) 
  21.                 {
  22.                     temp = a[i];
  23.                     a[i] = a[j];
  24.                     a[j] = temp;
  25.                 }
  26.             }
  27.         }
  28.         System.out.print("Descending Order:");
  29.         for (int i = 0; i <=n - 1; i++) 
  30.         {
  31.             System.out.print(a[i] + ",");
  32.         }
  33.        
  34.     }
  35. }
-----------------------------------------------------------------------------

Java Program to find Third Largest Number in an Array

We can find the third largest number in an array in java by sorting the array and returning the 3nd largest number. Let's see the full example to find the third largest number in java array.
  1. public class ThirdLargestInArrayExample{  
  2. public static int getThirdLargest(int[] a, int total){  
  3. int temp;  
  4. for (int i = 0; i < total; i++)   
  5.         {  
  6.             for (int j = i + 1; j < total; j++)   
  7.             {  
  8.                 if (a[i] > a[j])   
  9.                 {  
  10.                     temp = a[i];  
  11.                     a[i] = a[j];  
  12.                     a[j] = temp;  
  13.                 }  
  14.             }  
  15.         }  
  16.        return a[total-3];  
  17. }  
  18. public static void main(String args[]){  
  19. int a[]={1,2,5,6,3,2};  
  20. int b[]={44,66,99,77,33,22,55};  
  21. System.out.println("Third Largest: "+getThirdLargest(a,6));  
  22. System.out.println("Third Largest: "+getThirdLargest(b,7));  
  23. }}  
---------------------------------------------------------------------------------

Java Program to find Second Largest Number in an Array

We can find the second largest number in an array in java by sorting the array and returning the 2nd largest number. Let's see the full example to find the second largest number in java array.
  1. public class SecondLargestInArrayExample{  
  2. public static int getSecondLargest(int[] a, int total){  
  3. int temp;  
  4. for (int i = 0; i < total; i++)   
  5.         {  
  6.             for (int j = i + 1; j < total; j++)   
  7.             {  
  8.                 if (a[i] > a[j])   
  9.                 {  
  10.                     temp = a[i];  
  11.                     a[i] = a[j];  
  12.                     a[j] = temp;  
  13.                 }  
  14.             }  
  15.         }  
  16.        return a[total-2];  
  17. }  
  18. public static void main(String args[]){  
  19. int a[]={1,2,5,6,3,2};  
  20. int b[]={44,66,99,77,33,22,55};  
  21. System.out.println("Second Largest: "+getSecondLargest(a,6));  
  22. System.out.println("Second Largest: "+getSecondLargest(b,7));  
  23. }}  

Find 2nd Largest Number in Array using Arrays

Let's see another example to get second largest element or number in java array using collections.
  1. import java.util.Arrays;  
  2. public class SecondLargestInArrayExample1{  
  3. public static int getSecondLargest(int[] a, int total){  
  4. Arrays.sort(a);  
  5. return a[total-2];  
  6. }  
  7. public static void main(String args[]){  
  8. int a[]={1,2,5,6,3,2};  
  9. int b[]={44,66,99,77,33,22,55};  
  10. System.out.println("Second Largest: "+getSecondLargest(a,6));  
  11. System.out.println("Second Largest: "+getSecondLargest(b,7));  
  12. }}  
-----------------------------------------------------------------------------------

Java Program to find Second Smallest Number in an Array

We can find the second smallest number in an array in java by sorting the array and returning the 2nd element. Let's see the full example to find the second smallest number in java array.
  1. public class SecondSmallestInArrayExample{  
  2. public static int getSecondSmallest(int[] a, int total){  
  3. int temp;  
  4. for (int i = 0; i < total; i++)   
  5.         {  
  6.             for (int j = i + 1; j < total; j++)   
  7.             {  
  8.                 if (a[i] > a[j])   
  9.                 {  
  10.                     temp = a[i];  
  11.                     a[i] = a[j];  
  12.                     a[j] = temp;  
  13.                 }  
  14.             }  
  15.         }  
  16.        return a[1];//2nd element because index starts from 0  
  17. }  
  18. public static void main(String args[]){  
  19. int a[]={1,2,5,6,3,2};  
  20. int b[]={44,66,99,77,33,22,55};  
  21. System.out.println("Second smallest: "+getSecondSmallest(a,6));  
  22. System.out.println("Second smallest: "+getSecondSmallest(b,7));  
  23. }}  

Find 2nd Smallest Number in Array using Arrays

Let's see another example to get second smallest element or number in java array using Arrays.
  1. import java.util.*;  
  2. public class SecondSmallestInArrayExample1{  
  3. public static int getSecondSmallest(int[] a, int total){  
  4. Arrays.sort(a);  
  5. return a[1];  
  6. }  
  7. public static void main(String args[]){  
  8. int a[]={1,2,5,6,3,2};  
  9. int b[]={44,66,99,77,33,22,55};  
  10. System.out.println("Second Smallest: "+getSecondSmallest(a,6));  
  11. System.out.println("Second Smallest: "+getSecondSmallest(b,7));  
  12. }}  
--------------------------------------------------------------------------------

Java Program to remove duplicate element in an Array

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays.sort(arr) method.

1) Remove Duplicate Element in Array using Temporary Array

  1. public class RemoveDuplicateInArrayExample{  
  2. public static int removeDuplicateElements(int arr[], int n){  
  3.         if (n==0 || n==1){  
  4.             return n;  
  5.         }  
  6.         int[] temp = new int[n];  
  7.         int j = 0;  
  8.         for (int i=0; i<n-1; i++){  
  9.             if (arr[i] != arr[i+1]){  
  10.                 temp[j++] = arr[i];  
  11.             }  
  12.          }  
  13.         temp[j++] = arr[n-1];     
  14.         // Changing original array  
  15.         for (int i=0; i<j; i++){  
  16.             arr[i] = temp[i];  
  17.         }  
  18.         return j;  
  19.     }  
  20.        
  21.     public static void main (String[] args) {  
  22.         int arr[] = {10,20,20,30,30,40,50,50};  
  23.         int length = arr.length;  
  24.         length = removeDuplicateElements(arr, length);  
  25.         //printing array elements  
  26.         for (int i=0; i<length; i++)  
  27.            System.out.print(arr[i]+" ");  
  28.     }  
  29. }  

Remove Duplicate Element in Array using separate index

  1. public class RemoveDuplicateInArrayExample2{  
  2.     public static int removeDuplicateElements(int arr[], int n){  
  3.         if (n==0 || n==1){  
  4.             return n;  
  5.         }    
  6.         int j = 0;//for next element  
  7.         for (int i=0; i < n-1; i++){  
  8.             if (arr[i] != arr[i+1]){  
  9.                 arr[j++] = arr[i];  
  10.             }  
  11.         }  
  12.         arr[j++] = arr[n-1];  
  13.         return j;  
  14.     }  
  15.        
  16.     public static void main (String[] args) {  
  17.         int arr[] = {10,20,20,30,30,40,50,50};  
  18.         int length = arr.length;  
  19.         length = removeDuplicateElements(arr, length);  
  20.         //printing array elements  
  21.         for (int i=0; i<length; i++)  
  22.            System.out.print(arr[i]+" ");  
  23.     }  
  24. }  

Remove Duplicate Elements in Unsorted Array

If you have unsorted array, you need to sort it first. To do so, use Arrays.sort(arr) method.
  1. import java.util.Arrays;  
  2. public class RemoveDuplicateInArrayExample3{  
  3. public static int removeDuplicateElements(int arr[], int n){  
  4.         if (n==0 || n==1){  
  5.             return n;  
  6.         }  
  7.         int[] temp = new int[n];  
  8.         int j = 0;  
  9.         for (int i=0; i<n-1; i++){  
  10.             if (arr[i] != arr[i+1]){  
  11.                 temp[j++] = arr[i];  
  12.             }  
  13.          }  
  14.         temp[j++] = arr[n-1];     
  15.         // Changing original array  
  16.         for (int i=0; i<j; i++){  
  17.             arr[i] = temp[i];  
  18.         }  
  19.         return j;  
  20.     }  
  21.        
  22.     public static void main (String[] args) {  
  23.         int arr[] = {10,70,30,90,20,20,30,40,70,50};//unsorted array  
  24.         Arrays.sort(arr);//sorting array  
  25.         int length = arr.length;  
  26.         length = removeDuplicateElements(arr, length);  
  27.         //printing array elements  
  28.         for (int i=0; i<length; i++)  
  29.            System.out.print(arr[i]+" ");  
  30.     }  
  31. }  
------------------------------------------------------------------------------

Java Program to add two matrices

We can add two matrices in java using binary + operator. A matrix is also known as array of arrays. We can add, subtract and multiply matrices.
Add two matrices in Java
To subtract two matrices, use - operator. Let's see a simple example to add two matrices of 3 rows and 3 columns.
  1. public class MatrixAdditionExample{  
  2. public static void main(String args[]){  
  3. //creating two matrices    
  4. int a[][]={{1,3,4},{2,4,3},{3,4,5}};    
  5. int b[][]={{1,3,4},{2,4,3},{1,2,4}};    
  6.     
  7. //creating another matrix to store the sum of two matrices    
  8. int c[][]=new int[3][3];  //3 rows and 3 columns  
  9.     
  10. //adding and printing addition of 2 matrices    
  11. for(int i=0;i<3;i++){    
  12. for(int j=0;j<3;j++){    
  13. c[i][j]=a[i][j]+b[i][j];    //use - for subtraction  
  14. System.out.print(c[i][j]+" ");    
  15. }    
  16. System.out.println();//new line    
  17. }    
  18. }}  
------------------------------------------------------------------------------

Java Program to multiply two matrices

We can multiply two matrices in java using binary * operator and executing another loop. A matrix is also known as array of arrays. We can add, subtract and multiply matrices.
In case of matrix multiplication, one row element of first matrix is multiplied by all columns of second matrix.
Matrix Multiplication in Java
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
  1. public class MatrixMultiplicationExample{  
  2. public static void main(String args[]){  
  3. //creating two matrices    
  4. int a[][]={{1,1,1},{2,2,2},{3,3,3}};    
  5. int b[][]={{1,1,1},{2,2,2},{3,3,3}};    
  6.     
  7. //creating another matrix to store the multiplication of two matrices    
  8. int c[][]=new int[3][3];  //3 rows and 3 columns  
  9.     
  10. //multiplying and printing multiplication of 2 matrices    
  11. for(int i=0;i<3;i++){    
  12. for(int j=0;j<3;j++){    
  13. c[i][j]=0;      
  14. for(int k=0;k<3;k++)      
  15. {      
  16. c[i][j]+=a[i][k]*b[k][j];      
  17. }//end of k loop  
  18. System.out.print(c[i][j]+" ");  //printing matrix element  
  19. }//end of j loop  
  20. System.out.println();//new line    
  21. }    
  22. }}  
--------------------------------------------------------------------------------

Java Program to transpose matrix

Converting rows of a matrix into columns and columns of a matrix into row is called transpose of a matrix.
Let's see a simple example to transpose a matrix of 3 rows and 3 columns.
  1. public class MatrixTransposeExample{  
  2. public static void main(String args[]){  
  3. //creating a matrix  
  4. int original[][]={{1,3,4},{2,4,3},{3,4,5}};    
  5.     
  6. //creating another matrix to store transpose of a matrix  
  7. int transpose[][]=new int[3][3];  //3 rows and 3 columns  
  8.     
  9. //Code to transpose a matrix  
  10. for(int i=0;i<3;i++){    
  11. for(int j=0;j<3;j++){    
  12. transpose[i][j]=original[j][i];  
  13. }    
  14. }    
  15.   
  16. System.out.println("Printing Matrix without transpose:");  
  17. for(int i=0;i<3;i++){    
  18. for(int j=0;j<3;j++){    
  19. System.out.print(original[i][j]+" ");    
  20. }    
  21. System.out.println();//new line    
  22. }    
  23. System.out.println("Printing Matrix After Transpose:");  
  24. for(int i=0;i<3;i++){    
  25. for(int j=0;j<3;j++){    
  26. System.out.print(transpose[i][j]+" ");    
  27. }    
  28. System.out.println();//new line    
  29. }    
  30. }}  
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 
----------------------------------------------------------------------------------

Java Program to subtract the two matrices

In this program, we need to get the result of subtraction of two matrices.
Two matrices A and B can be subtracted if and only if they have same dimensions that are, the same number of rows and columns. It is not possible to subtract a 2 × 3 matrix from a 3 × 2 matrix. Subtraction of two matrices can be performed by subtracting their corresponding elements as
  1. (A - B)<sub>ij</sub>= A<sub>ij</sub> - B<sub>ij</sub>  
Java Program to subtract the two matrices
Subtraction of two matrices can be performed by looping through the first and second matrix. Calculating the difference between their corresponding elements and store the result in the third matrix.

Algorithm

  • STEP 1: START
  • STEP 2: DEFINE rows, cols
  • STEP 3: INITIALIZE first matrix a[][] ={{4,5,6},{3,4,1}, {1,2,3}}
  • STEP 4: INITIALIZE second matrix b[][] ={{2,0,3}, {2,3,1}{1,1,1}}
  • STEP 5: rows = a.length
  • STEP 6: cols = a[0].length
  • STEP 7: DEFINE diff[][]
  • STEP 8: REPEAT STEP 9 to STEP 10 UNTIL i<rows             //for(i=0;i<rows; i++)
  • STEP 9: REPEAT STEP 10 UNTIL j<cols             //for(j=0;j<cols; j++)
  • STEP 10: diff[i][j] =a[i][j] - b[i][j]
  • STEP 11: PRINT "Subtraction of two matrices:"
  • STEP 12: REPEAT STEP 13 to STEP 14 UNTIL i<rows             //for(i=0;i<rows; i++)
  • STEP 13: REPEAT STEP 14 UNTIL j<cols             //for(j=0; j<cols; j++)
  • STEP 13: PRINT diff[i][j]
  • STEP 14: PRINT new line
  • STEP 15: END

Program:

  1. public class Sub_Matrix  
  2. {  
  3.     public static void main(String[] args) {  
  4.         int rows, cols;  
  5.   
  6.         //Initialize matrix a  
  7.           int a[][] = {  
  8.                           {456},  
  9.                           {341},  
  10.                           {123}  
  11.                        };  
  12.   
  13.           //Initialize matrix b  
  14.           int b[][] = {  
  15.                           {203},  
  16.                          {231},  
  17.                          {111}  
  18.                      };  
  19.   
  20.           //Calculates number of rows and columns present in given matrix  
  21.           rows = a.length;  
  22.         cols = a[0].length;  
  23.   
  24.           //Array diff will hold the result  
  25.         int diff[][] = new int[rows][cols];  
  26.   
  27.         //Performs subtraction of matrices a and b. Store the result in matrix diff  
  28.         for(int i = 0; i < rows; i++){  
  29.             for(int j = 0; j < cols; j++){  
  30.                 diff[i][j] = a[i][j] - b[i][j];  
  31.             }  
  32.         }  
  33.   
  34.         System.out.println("Subtraction of two matrices: ");  
  35.         for(int i = 0; i < rows; i++){  
  36.             for(int j = 0; j < cols; j++){  
  37.                System.out.print(diff[i][j] + " ");  
  38.             }  
  39.             System.out.println();  
  40.         }  
  41.     }  
  42. }    
Output:
Subtraction of two matrices:
1 5    3
1    1    0
0    1    2
-------------------------------------------------------------------------------

Java Program to determine whether a given matrix is an identity matrix

In this program, we need to check whether the given matrix is an identity matrix.
Identity Matrix
Java Program to determine whether a given matrix is an identity matrix
A matrix is said to be an identity matrix if it is a square matrix in which elements of principle diagonal are ones, and the rest of the elements are zeroes.

Algorithm

  • STEP 1: START
  • STEP 2: DEFINE rows, cols
  • STEP 3: SET flag =true
  • STEP 4: INITIALIZE matrix a[][] ={{1,0,0},{0,1,0}, {0,0,1}}
  • STEP 5: rows = a.length
  • STEP 6: cols = a[0].length
  • STEP 7: if(rows!=cols)             then           PRINT "Matrix should be a square matrix"          else        go to step 8
  • STEP 8: REPEAT STEP 9 to STEP 11 UNTIL i<rows             //for(i=0; i<rows; i++)
  • STEP 9: REPEAT STEP 10 to STEP 11 UNTIL j<cols             //for(j=0; j<cols; j++)
  • STEP 10: if(i==j && a[i][j]== 1) then             SET flag =false             break
  • STEP 11: if( i!=j && a[i][j]!=0)             SET flag = false             break
  • STEP 12: if(flag)             then PRINT ("Given matrix is an identity matrix")             else             PRINT ("Given matrix is not an identity matrix")
  • STEP 13: END

Program:

  1. public class IdentityMatrix     
  2. {    
  3.     public static void main(String[] args) {    
  4.         int rows, cols;    
  5.         boolean flag = true;    
  6.             
  7.         //Initialize matrix a    
  8.         int a[][] = {       
  9.                         {100},    
  10.                         {010},    
  11.                         {001}    
  12.                     };    
  13.             
  14.         //Calculates the number of rows and columns present in the given matrix    
  15.     
  16.           rows = a.length;    
  17.         cols = a[0].length;    
  18.             
  19.         //Checks whether given matrix is a square matrix or not    
  20.         if(rows != cols){    
  21.             System.out.println("Matrix should be a square matrix");    
  22.         }    
  23.         else {    
  24.             //Checks if diagonal elements are equal to 1 and rest of elements are 0    
  25.             for(int i = 0; i < rows; i++){    
  26.                 for(int j = 0; j < cols; j++){    
  27.                   if(i == j && a[i][j] != 1){    
  28.                       flag = false;    
  29.                       break;    
  30.                   }    
  31.                   if(i != j && a[i][j] != 0){    
  32.                       flag = false;    
  33.                       break;    
  34.                   }    
  35.                 }    
  36.             }    
  37.                 
  38.             if(flag)    
  39.                 System.out.println("Given matrix is an identity matrix");    
  40.             else    
  41.                 System.out.println("Given matrix is not an identity matrix");    
  42.         }    
  43.     }    
  44. }    
--------------------------------------------------------------------------

Java Program to determine whether a given matrix is a sparse matrix

In this program, we need to check whether the given matrix is a sparse matrix.
A matrix is said to be sparse matrix if most of the elements of that matrix are 0. It implies that it contains very less non-zero elements.
To check whether the given matrix is the sparse matrix or not, we first count the number of zero elements present in the matrix. Then calculate the size of the matrix. For the matrix to be sparse, count of zero elements present in an array must be greater than size/2.
Java Program to determine whether a given matrix is a sparse matrix
Number of zeroes present in above matrix is 6 and size of the matrix is 3 * 3 = 9. Since, 6 > 4.5 that means, most elements of given array are zero. Hence, the above matrix is a sparse matrix.

Algorithm

  • STEP 1: START
  • STEP 2: DEFINE rows, cols, size
  • STEP 3: SET count = 0
  • STEP 4: INITIALIZE first matrix a[][] ={{4,0,0}, {0,5,0}, {0,0,6}}
  • STEP 5: rows = a.length
  • STEP 6: cols = a[0].length
  • STEP 7: size = rows*cols
  • STEP 8: REPEAT STEP 9 to STEP 10 UNTIL i<rows         //for(i=0;i<rows; i++)
  • STEP 9: REPEAT STEP 10 UNTIL j<cols         //for(j=0;j<cols; j++)
  • STEP 10: if(a[i][j]==0) then count++
  • STEP 11: if(count>size/2) then PRINT "Yes" else PRINT "No"
  • STEP 12: END

Program

  1. public class SparseMatrix    
  2. {    
  3.     public static void main(String[] args) {    
  4.         int rows, cols, size, count = 0;    
  5.             
  6.         //Initialize matrix a    
  7.         int a[][] = {       
  8.                         {400},    
  9.                         {050},    
  10.                         {006}    
  11.                     };    
  12.               
  13.           //Calculates number of rows and columns present in given matrix    
  14.           rows = a.length;    
  15.         cols = a[0].length;    
  16.             
  17.         //Calculates the size of array    
  18.         size = rows * cols;    
  19.             
  20.         //Count all zero element present in matrix    
  21.         for(int i = 0; i < rows; i++){    
  22.             for(int j = 0; j < cols; j++){    
  23.                 if(a[i][j] == 0)    
  24.                     count++;    
  25.                 }    
  26.             }    
  27.                 
  28.         if(count > (size/2))    
  29.             System.out.println("Given matrix is a sparse matrix");    
  30.         else    
  31.             System.out.println("Given matrix is not a sparse matrix");    
  32.     }    
  33. }     
--------------------------------------------------------------------------------

Java Program to display the lower triangular matrix

In this program, we need to display the lower triangular matrix.

Lower Triangular Matrix

Lower triangular matrix is a square matrix in which all the elements above the principle diagonal will be zero. To find the lower triangular matrix, a matrix needs to be a square matrix that is, the number of rows and columns in the matrix need to be equal. Dimensions of a typical square matrix can be represented by n x n.
Java Program to display the lower triangular matrix
Consider the above example, principle diagonal element of given matrix is (1, 6, 6). All the elements above the diagonal needs to made zero. In our example, those elements are at positions (1, 2), (1, 3) and (2, 3). To convert given matrix into the lower triangular matrix, loop through the matrix and set the values of the element to zero where column number is greater than row number.

Algorithm

  • STEP 1: START
  • STEP 2: DEFINE rows, cols
  • STEP 3: INITIALIZE matrix a[][] ={{1,2,3},{8, 6, 4}, {4, 5, 6}}
  • STEP 4: rows = a.length
  • STEP 5: cols = a[0].length
  • STEP 6: if(rows!=cols)         then         PRINT "Matrix should be a square matrix"         else         Go to step 7
  • STEP 7: REPEAT STEP 4 to STEP 6 UNTIL i<rows         //for(i=0; i<rows; i++)
  • STEP 8: REPEAT STEP 9 UNTIL j<cols // for(j=0; j<cols; j++)         If(j>i) then PRINT 0 else PRINT a[i][j]
  • STEP 9: PRINT new line
  • STEP 10: END

Program

  1. public class LowerTriangular    
  2. {    
  3.     public static void main(String[] args) {    
  4.     int rows, cols;    
  5.     //Initialize matrix a    
  6.         int a[][] = {       
  7.                         {123},    
  8.                         {864},    
  9.                         {456}    
  10.                     };    
  11.               
  12.           //Calculates number of rows and columns present in given matrix    
  13.           rows = a.length;    
  14.           cols = a[0].length;    
  15.             
  16.           if(rows != cols){    
  17.               System.out.println("Matrix should be a square matrix");    
  18.           }    
  19.           else {    
  20.               //Performs required operation to convert given matrix into lower triangular matrix    
  21.               System.out.println("Lower triangular matrix: ");    
  22.               for(int i = 0; i < rows; i++){    
  23.                   for(int j = 0; j < cols; j++){    
  24.                     if(j > i)    
  25.                       System.out.print("0 ");    
  26.                     else    
  27.                       System.out.print(a[i][j] + " ");    
  28.                 }    
  29.                 System.out.println();    
  30.             }    
  31.         }    
  32.     }    
  33. }    
Output:
Lower triangular matrix:
1 0   0
8    6   0
4    5   6
--------------------------------------------------------------------------------

Java Program to display the upper triangular matrix

In this program, we need to display the upper triangular matrix.

Upper Triangular Matrix

Upper triangular matrix is a square matrix in which all the elements below the principle diagonal are zero. To find the upper triangular matrix, a matrix needs to be a square matrix that is, the number of rows and columns in the matrix need to be equal. Dimensions of a typical square matrix can be represented by n x n.
Java Program to display the upper triangular matrix
Consider the above example, principle diagonal element of given matrix is (1, 6, 6). All the elements below diagonal needs to be zero to convert it into an upper triangular matrix, in our example, those elements are at positions (2, 1), (3, 1) and (3, 2). To convert given matrix into the upper triangular matrix, loop through the matrix and set the values of the element to zero where row number is greater than column number.

Algorithm

  • STEP 1: START
  • STEP 2: DEFINE rows, cols
  • STEP 3: INITIALIZE matrix a[][] ={{1,2,3},{8, 6, 4}, {4, 5, 6}}
  • STEP 4: rows = a.length
  • STEP 5: cols = a[0].length
  • STEP 6: if(rows!=cols)         then         PRINT "Matrix should be a square matrix"         else         Go to step 7
  • STEP 7: REPEAT STEP 8 to STEP 10 UNTIL i<rows         //for(i=0; i<rows; i++)
  • STEP 8: REPEAT STEP 9 UNTIL j<cols // for(j=0; j<cols; j++)
  • STEP 9: If(i>j) then PRINT 0 else PRINT a[i][j]
  • STEP 10: PRINT new line
  • STEP 11: END

program

  1. public class UpperTriangular    
  2. {    
  3.     public static void main(String[] args) {    
  4.         int rows, cols;    
  5.             
  6.         //Initialize matrix a    
  7.         int a[][] = {       
  8.                         {123},    
  9.                         {864},    
  10.                         {456}    
  11.                     };    
  12.               
  13.           //Calculates number of rows and columns present in given matrix    
  14.           rows = a.length;    
  15.         cols = a[0].length;    
  16.             
  17.         if(rows != cols){    
  18.             System.out.println("Matrix should be a square matrix");    
  19.         }    
  20.         else {    
  21.             //Performs required operation to convert given matrix into upper triangular matrix    
  22.             System.out.println("Upper triangular matrix: ");    
  23.             for(int i = 0; i < rows; i++){    
  24.                 for(int j = 0; j < cols; j++){    
  25.                   if(i > j)    
  26.                     System.out.print("0 ");    
  27.                   else    
  28.                     System.out.print(a[i][j] + " ");    
  29.                 }    
  30.                 System.out.println();    
  31.             }    
  32.         }    
  33.     }    
  34. }    
Output:
Upper triangular matrix:
1 2   3
0    6   4
0    0   0

public class PairsOfElementsInArray
{
    static void findThePairs(int inputArray[], int inputNumber)
    {
        System.out.println("Pairs of elements whose sum is "+inputNumber+" are : ");
 
        for (int i = 0; i < inputArray.length; i++)
        {
            for (int j = i+1; j < inputArray.length; j++)
            {
                if(inputArray[i]+inputArray[j] == inputNumber)
                {
                    System.out.println(inputArray[i]+" + "+inputArray[j]+" = "+inputNumber);
                }
            }
        }
    }
 
    public static void main(String[] args)
    {
        findThePairs(new int[] {4, 6, 5, -10, 8, 5, 20}, 10);
 
        findThePairs(new int[] {4, -5, 9, 11, 25, 13, 12, 8}, 20);
 
        findThePairs(new int[] {12, 13, 40, 15, 8, 10, -15}, 25);
 
        findThePairs(new int[] {12, 23, 125, 41, -75, 38, 27, 11}, 50);
    }
}
Output :
Pairs of elements whose sum is 10 are : 4 + 6 = 10 5 + 5 = 10 -10 + 20 = 10 Pairs of elements whose sum is 20 are : -5 + 25 = 20 9 + 11 = 20 12 + 8 = 20 Pairs of elements whose sum is 25 are : 12 + 13 = 25 40 + -15 = 25 15 + 10 = 25 Pairs of elements whose sum is 50 are : 12 + 38 = 50 23 + 27 = 50 125 + -75 = 50
Count the number of pairs in an array having sums that are evenly divisible by a given number.

package hackerrank; import java.util.Arrays; public class CountPairOfSum { private static int countPairOfSum(int[] arr, int k) { //brute force method --time complexity o(n2) System.out.println("Array is:"+Arrays.toString(arr)); System.out.println(""); int paircount=0; for(int i=0;i<arr.length;i++) { for(int j=i+1;j<arr.length;j++) { if((arr[i]+arr[j])%k==0) { System.out.println("Pair is :"+(arr[i]+","+arr[j])); paircount++; } } } return paircount; } public static void main(String[] args) { //int[] ar = {1, 2, 3, 4, 5, 6}; int k=5 int[] ar= {1, 3, 2, 6, 1, 2}; int k=3; System.out.println(countPairOfSum(ar, k)); } }


How to reverse the first half of Array?

public class revfirsthalfIntegerArray {

    public static void main(String[] args) {

        int[] arr= {10,2,5,4,6,9,5,3};


        int len=arr.length;


        for(int i=0; i<len/4;i++)

        {

            int t = arr[i]; 

            arr[i] = arr[len/2 - i - 1]; 

            arr[len/2 - i - 1] = t; 

        }


        for(int j=0; j<lenj++)

        {

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

        }

    }

}



What is ModeOfArray and write the code for it?


public static void modeofarray() {


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

int maxnumber=-1;

int maxapperance=-1;

int result=0;


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

int count=0;

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

                             {

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

count++;

}

}

if (count > maxapperance) {

maxnumber=arr[i];

maxapperance=count;

}

}

System.out.println("+" +maxnumber);

}

What is median in array, define the logic and write the code?



To calculate the median first we need to sort the list in ascending or descending order. If the number of elements are even, then the median will the average of two numbers in the middle. But the number is odd then the middle element of the array after sorting will be considered as the median










 public static void medianofarray() {


int arr[]= {1,2,3,4}; //array is already sorted so no need to sort again

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


if (arr.length % 2 != 0)  //if number of elements are odd

                {

System.out.println("median of array is: " + arr[arr.length/2]);


}else {


System.out.println("median of array is: " + (arr[(arr.length/2)]+arr[(arr.length/2-1)])/2.0);


}

}


16. How to merge two array in Java?


public static void mergetwoarray() {

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

int arr2[]= {5,3,8,7,9};


//sort both arrays

Arrays.sort(arr1);

Arrays.sort(arr2);

int resultarray[] = new int[arr1.length+arr2.length];


int i = 0,j = 0,k=0;


while(i<arr1.length && j<arr2.length) {

if (arr1[i]<arr2[j]) {

resultarray[k++]=arr1[i++];

}

else{

resultarray[k++]=arr2[j++];

}

}

while(i<arr1.length) {

resultarray[k++]=arr1[i++];

}

while(j<arr2.length) {

resultarray[k++]=arr2[j++];

}

for (int l=0;l<resultarray.length;l++) {

System.out.println(resultarray[l]);

}

}


How to find the leader in an Array?


An element is leader if it is greater than all the elements to its right side.


public static void leaderinarray() {


int arrl[]= {1,2,4,3,8,6,7,1};


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

int j;

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


if (arrl[i]<arrl[j]) 

                                {

break;

}

}

if (j==arrl.length) {


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

}

}

}



Revision :Find the second largest in an ARRAY?


public class firstsecodlargest {

public static void main(String[] args) {

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

int firstlargest=0;

int secondlargest=0;

int i=0;

int narr.length;

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

{

if (arr[i]>firstlargest){

secondlargest=firstlargest;

firstlargest=arr[i];

}

}

System.out.println(firstlargest + "  " + secondlargest);


}}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.