Java Exercise 4

Mannan Ul Haq
0

Objective:

  • 1D Array
  • 2D Array

Activity 1:

Write a program that declare an int array of size N inside the main function. Write the following functions for this array:

  1. initializeArray(int[] arr) This function takes an int array parameter. The function will be used to populate the array by taking input from user.
  2. void printArray(int[] arr) Print the array data in an efficient manner that each element is separated with appropriate space. Note: Use this function to print all results of below functions.
  3. int find2Largest(int[] arr) The function returns the second largest element of an array.
  4. void findMinMax(int[] arr) This function should store the min and max value in the relevant variables which are passed to the function.
  5. void searchData(int[] arr, int key). This function should search the key using linear search technique and return the index. If key isn't available in the array, then return -1.
  6. void sortData(int[] arr, char choice)  This function also takes choice variable as parameters and sort the data according to users choice, i.e., ascending or descending. You can use any sorting technique to sort the data in ascending order.
  7. void sortEvenOdd(int[] arr) function to separate even and odd numbers of an array of integers. Put all even numbers first, and then odd numbers.
  8. void checkFrequency(int[] arr)  - the function will take an array as input and print the frequency of each element of an array

Solution:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static final int SIZE = 6;

    static void initializeArray(int[] arr) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter values of Set: ");
        for (int i = 0; i < SIZE; i++) {
            arr[i] = scanner.nextInt();
        }
    }

    static void printArray(int[] arr) {
        System.out.print("The Elements in Set are: ");
        for (int n = 0; n < SIZE; n++) {
            System.out.print(arr[n]);
            if (n < (SIZE - 1))
                System.out.print(" ");
        }
        System.out.println();
    }

    static int find2Largest(int[] arr) {
        int[] arr2 = new int[SIZE];
        int max1 = 0, max2 = 0;
        for (int i = 0; i < SIZE; i++) {
            arr2[i] = arr[i];
            if (arr2[i] > max1)
                max1 = arr2[i];
        }
        for (int i = 0; i < SIZE; i++) {
            if (arr2[i] == max1)
                arr2[i] = 0;
            if (arr2[i] > max2)
                max2 = arr2[i];
        }
        return max2;
    }

    static int[] findMinMax(int[] arr) {
        int min = arr[0];
        int max = arr[0];
        for (int i = 1; i < SIZE; i++) {
            if (arr[i] < min)
                min = arr[i];
            if (arr[i] > max)
                max = arr[i];
        }
        return new int[] {min, max};
    }

    static int searchData(int[] arr, int key) {
        int found = -1;
        for (int i = 0; i < SIZE; i++) {
            if (arr[i] == key)
                found = key;
        }
        return found;
    }

    static void sortData(int[] arr, char choice) {
        Arrays.sort(arr);
        if (choice == 'd')
            for (int i = 0; i < arr.length / 2; i++) {
                int temp = arr[i];
                arr[i] = arr[arr.length - 1 - i];
                arr[arr.length - 1 - i] = temp;
            }

        System.out.print(choice == 'a' ? "Elements sorted in the Ascending Order are: " : "Elements sorted in the Descending Order are: ");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
            if (i < (arr.length - 1))
                System.out.print(" ");
        }
        System.out.println();
    }

    static void sortEvenOdd(int[] arr) {
        System.out.print("Even Elements of Array: ");
        for (int i : arr) {
            if (i % 2 == 0)
                System.out.print(i + " ");
        }
        System.out.println();

        System.out.print("Odd Elements of Array: ");
        for (int i : arr) {
            if (i % 2 != 0)
                System.out.print(i + " ");
        }
        System.out.println();
    }

    static void checkFrequency(int[] arr) {
        System.out.println("Frequency of all Elements in the Array: ");
        for (int i = 0; i < SIZE; i++) {
            int count = 0;
            for (int j = 0; j < SIZE; j++) {
                if (arr[i] == arr[j])
                    count++;
            }
            System.out.println(arr[i] + " occurs " + count + " time(s)");
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[SIZE];
        int key, found, max, min;
        char choice;

        initializeArray(arr);
        System.out.println();
        printArray(arr);
        System.out.println();
        System.out.println("The Second Largest in the Array is: " + find2Largest(arr));
        System.out.println();
        int[] minMax = findMinMax(arr);
        min = minMax[0];
        max = minMax[1];
        System.out.println("The Max. value in the Array is: " + max);
        System.out.println("The Min. value in the Array is: " + min);
        System.out.println();
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter value to find: ");
        key = scanner.nextInt();
        found = searchData(arr, key);
        System.out.println(found == -1 ? "Value not found in the Array." : "Value found in the Array.");
        System.out.println();
        do {
            System.out.println("Type 'a' for Ascending Order or 'd' for Descending Order.");
            choice = scanner.next().charAt(0);
        } while (choice != 'a' && choice != 'd');
        sortData(arr, choice);
        System.out.println();
        sortEvenOdd(arr);
        System.out.println();
        checkFrequency(arr);
        System.out.println();
    }
}


Activity 2:

Write a Java program to read a sentence from console into a character array. Now separate each word and find the word with minimum length and display it on screen. You also have to make integer array to store length of each word in sentence. Your code should be generic. 
*Note: Your sentence always ends with full stop.

Solution: 

import java.util.Scanner;

public class Main {
    static final int SIZE = 100;

    static void Min(char[] arr) {
        int[] lengths = new int[SIZE];
        int lengthIndex = 0;
        int minLength = SIZE;
        int currentLength = 0;

        for (int i = 0; i < arr.length && arr[i] != '\0'; i++) {
            if (arr[i] != ' ' && arr[i] != '.') {
                currentLength++;
            }
            else if (currentLength > 0) {
                System.out.print(currentLength + " ");
                lengths[lengthIndex] = currentLength;
                lengthIndex++;

                if (currentLength < minLength) {
                    minLength = currentLength;
                }

                currentLength = 0;
            }
        }

        System.out.println("\nMin: " + minLength);
    }

    public static void main(String[] args) {
        char[] arr = new char[SIZE];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a Sentence: ");
        String input = scanner.nextLine();
        arr = input.toCharArray();
        Min(arr);
    }
}


Activity 3:

Write a function in Java called void trace(int[][] data) that calculates and returns the trace of a square matrix of size 3x3. The trace of a square matrix is the sum of values present in its diagonal.


Solution:

import java.util.Scanner;

public class Main {
    static final int rows = 3, columns = 3;

    static void trace(int[][] data) {
        int trace = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                if (i == j)
                    trace += data[i][j];
            }
        }
        System.out.println("Trace = " + trace);
    }

    public static void main(String[] args) {
        int[][] data = new int[rows][columns];
        Scanner scanner = new Scanner(System.in);

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.printf("Enter (%d) and (%d) value: ", i, j);
                data[i][j] = scanner.nextInt();
            }
        }
        System.out.println("Given Matrix is: ");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.print(data[i][j] + " ");
            }
            System.out.println();
        }
        trace(data);
    }
}



Activity 4:

Write a Java function to compare two do the following tasks:

  1. Compare two char arrays
  2. Copy contents of 1 array into other and then compare both 

Solution:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static final int SIZE = 30;

    static void compare(char[] arr1, char[] arr2) {
        System.out.println("First String: " + new String(arr1).trim());
        System.out.println("Second String: " + new String(arr2).trim());
        if (Arrays.equals(arr1, arr2)) {
            System.out.println("Both Strings are Same.\n");
        }
        else {
            System.out.println("Both Strings are not Same.\n");
        }
    }

    public static void main(String[] args) {
        char[] arr1 = new char[SIZE];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter 1st Sentence: ");
        String input1 = scanner.nextLine();
        arr1 = Arrays.copyOf(input1.toCharArray(), SIZE);

        char[] arr2 = new char[SIZE];
        System.out.println("Enter 2nd Sentence: ");
        String input2 = scanner.nextLine();
        arr2 = Arrays.copyOf(input2.toCharArray(), SIZE);

        compare(arr1, arr2);

        System.arraycopy(arr1, 0, arr2, 0, arr1.length);
        System.out.println("After Copying contents of 1st array into other.");
        compare(arr1, arr2);
    }
}



Activity 5:

Ask user for an input, store that input in a char array. Count small letters, capital letters, its and special charters in that input.


Solution:

import java.util.Scanner;

public class Main {
    static final int SIZE = 30;

    static void count(char[] arr) {
        int upper = 0, lower = 0, number = 0, special = 0;
        for (int i = 0; i < arr.length && arr[i] != '\0'; i++) {
            if (arr[i] >= 'A' && arr[i] <= 'Z')
                upper++;
            else if (arr[i] >= 'a' && arr[i] <= 'z')
                lower++;
            else if (arr[i] >= '0' && arr[i] <= '9')
                number++;
            else
                special++;
        }
        System.out.println("Capital Letters: " + upper);
        System.out.println("Small Letters : " + lower);
        System.out.println("Numbers : " + number);
        System.out.println("Special Characters : " + special);
    }

    public static void main(String[] args) {
        char[] arr = new char[SIZE];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter the String: ");
        String input = scanner.nextLine();
        arr = input.toCharArray();
        count(arr);
    }
}

 


Activity 6:

  1. Write a function static int[] inputArray() that asks user to enter size of required array allocates the memory, takes input in array.
  2. Write a program static void outputArray(int[] array) that takes an integer array and prints its data.
  3. Implement a function static int[] intersection(int[] array1, int[] array2) that finds intersection (common elements) of two sets (stored using arrays).

Solution:

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        System.out.println("For Array 1: ");
        int[] array1 = inputArray();
        System.out.println("For Array 2: ");
        int[] array2 = inputArray();

        System.out.println("Array 1: ");
        outputArray(array1);
        System.out.println("Array 2: ");
        outputArray(array2);

        int[] intersection = intersection(array1, array2);

        System.out.println("Intersection: ");
        outputArray(intersection);
    }

    static int[] inputArray() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the Size of the Array:");
        int size = scanner.nextInt();

        int[] array = new int[size];
        System.out.println("Enter Values for the Array: ");
        for (int i = 0; i < size; i++) {
            array[i] = scanner.nextInt();
        }

        return array;
    }

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

    static int[] intersection(int[] array1, int[] array2) {
        int size3 = Math.min(array1.length, array2.length);
        int[] array = new int[size3];
        int k = 0;

        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array2.length; j++) {
                if (array1[i] == array2[j]) {
                    array[k] = array1[i];
                    k++;
                    if (k >= size3)
                        return Arrays.copyOf(array, k);
                }
            }
        }

        return Arrays.copyOf(array, k);
    }
}



Activity 7: 

a) Write a function static int[] allocateMemory() that takes size of matrix (rows and columns) from user.
b) Write a function static void inputMatrix() which creates an array and takes input values in matrix from user(console).
c) Write a function static void displayMatrix(int[][] matrix) that displays the matrix in proper format.
d) Write a function called maxRow that takes a 2D array. It should return the largest element in each row of the array. Since there is more than one row in 2D array, you have to return a dynamic array that contains largest of each row. 
For example, if the Sample Matrix is
1 4 8
9 1 6
5 7 2
Your function will return array containing maximum elements of all the columns i.e.
8, 9, 7
e) (Concatinate tables ) It takes two 2D arrays and returns a new 2D array that is concation on y or x axis.
static void Concat(int[,] A, int[,] B, int row1, int column1, int row2, int column2) //axis 0 mean x axis 1 means Y axis.

Array 1
1,2,3
4,4,5
3,4,6

Array 2
5,8,9
4,9,4
4,6,0

If axis = 0 (x-axis)
Output 
1,2,3,5,8,9
4,4,5,4,9,4
3,4,6,4,6,0

If axis = 1 (y-axis)
Output
1,2,3
4,4,5
3,4,6
5,8,9
4,9,4
4,6,0

Solution:

import java.util.Scanner;

public class Main {

    static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("For Array A:");
        int[] dimsA = allocateMemory();
        int[][] A = inputMatrix(dimsA);
        displayMatrix(A);

        System.out.println("The Maximum Values in each Row are: ");
        int[] maxRowArray = maxRow(A);
        for (int num : maxRowArray) {
            System.out.print(num + " ");
        }
        System.out.println();

        System.out.println("For Array B:");
        int[] dimsB = allocateMemory();
        int[][] B = inputMatrix(dimsB);
        displayMatrix(B);

        System.out.println("Concatenate Table: ");
        concat(A, B);
    }

    static int[] allocateMemory() {
        System.out.println("Enter the Number of Rows: ");
        int rows = scanner.nextInt();
        System.out.println("Enter the Number of Columns: ");
        int columns = scanner.nextInt();
        return new int[] {rows, columns};
    }

    static int[][] inputMatrix(int[] dims) {
        int[][] matrix = new int[dims[0]][dims[1]];
        System.out.println("Enter Values for Matrix: ");
        for (int i = 0; i < dims[0]; i++) {
            for (int j = 0; j < dims[1]; j++) {
                System.out.print("[" + i + "][" + j + "] = ");
                matrix[i][j] = scanner.nextInt();
            }
        }
        return matrix;
    }

    static void displayMatrix(int[][] matrix) {
        System.out.println("Given Matrix: ");
        for (int[] row : matrix) {
            for (int val : row) {
                System.out.print(val + "  ");
            }
            System.out.println();
        }
        System.out.println();
    }

    static int[] maxRow(int[][] matrix) {
        int[] maxValues = new int[matrix.length];
        for (int i = 0; i < matrix.length; i++) {
            int maxVal = matrix[i][0];
            for (int j = 1; j < matrix[i].length; j++) {
                if (matrix[i][j] > maxVal) {
                    maxVal = matrix[i][j];
                }
            }
            maxValues[i] = maxVal;
        }
        return maxValues;
    }

    static void concat(int[][] A, int[][] B) {
        System.out.println("Press 0: For x-axis");
        System.out.println("Press 1: For y-axis");
        int choice = scanner.nextInt();

        if (choice == 0 && A.length == B.length) {
            for (int i = 0; i < A.length; i++) {
                for (int j = 0; j < A[i].length; j++) {
                    System.out.print(A[i][j] + "  ");
                }
                for (int j = 0; j < B[i].length; j++) {
                    System.out.print(B[i][j] + "  ");
                }
                System.out.println();
            }
        }
        else if (choice == 1 && A[0].length == B[0].length) {
            for (int[] row : A) {
                for (int val : row) {
                    System.out.print(val + "  ");
                }
                System.out.println();
            }
            for (int[] row : B) {
                for (int val : row) {
                    System.out.print(val + "  ");
                }
                System.out.println();
            }
        }
        else {
            System.out.println("Invalid choice or matrices dimensions are not compatible for concatenation.");
        }
    }
}

 

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !