[go: up one dir, main page]

0% found this document useful (0 votes)
17 views30 pages

Practice Questions

The document contains a series of Java programming exercises that cover various array manipulations, including finding missing elements, calculating averages, moving zeros, deleting specific elements, and more. Each exercise is accompanied by a code snippet demonstrating the solution. The exercises range from basic operations like merging arrays and counting elements to more complex tasks like searching and frequency analysis.

Uploaded by

Yash Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views30 pages

Practice Questions

The document contains a series of Java programming exercises that cover various array manipulations, including finding missing elements, calculating averages, moving zeros, deleting specific elements, and more. Each exercise is accompanied by a code snippet demonstrating the solution. The exercises range from basic operations like merging arrays and counting elements to more complex tasks like searching and frequency analysis.

Uploaded by

Yash Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Q1.

Given an array of integers (in a series) and we have to find its missing
elements (there will be a missing element).
Code:
public class Arr1 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 6, 7};
int n = arr.length + 1;
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : arr) actualSum += num;
System.out.println("Missing element is: " + (expectedSum - actualSum));
}
}

Q2. Given an array of integers and we have to find their average .


Code:
import java.util.Scanner;
public class Arr2 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
int sum = 0;
System.out.println("Enter all elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
sum += arr[i];
}
System.out.println("Sum is: " + sum);
System.out.println("Average is: " + (double) sum / n);
}

}
Q3. Move all zero at the end of the array Given an integer array with zeros (0’s)
and we have to move all zeros at the end of the array
Code:
public class Arr3 {
public static void main(String[] args) {
int[] arr = {5, 1, 6, 0, 0, 3, 9, 0, 6, 7, 8, 12, 10, 0, 2};
int index = 0;
for (int num : arr) if (num != 0) arr[index++] = num;
while (index < arr.length) arr[index++] = 0;
for (int num : arr) System.out.print(num + " ");
}

Q4. Delete a specific element from a one dimensional array Given an array and
an element to delete and we have to delete it from array
Code:
import java.util.Scanner;
import java.util.Arrays;
public class Arr4 {

public static void main(String[] args) {


int[] arr = {10, 20, 30, 40, 50};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter element to delete: ");
int deleteElement = scanner.nextInt();
int[] newArr = Arrays.stream(arr).filter(e -> e !=
deleteElement).toArray();
System.out.println("Array after deletion: " + Arrays.toString(newArr));
}

Q5. Print EVEN and ODD elements from an array Given a one dimensional array
and we have to print its EVEN and ODD elements separately.
Code:
public class Arr5 {
public static void main(String[] args) {
int[] arr = {10, 11, 12, 13, 14};
System.out.print("Even numbers: ");
for (int num : arr) if (num % 2 == 0) System.out.print(num + " ");
System.out.print("\nOdd numbers: ");
for (int num : arr) if (num % 2 != 0) System.out.print(num + " ");
}

Q6. Merge two one dimensional arrays Given two one-dimensional arrays and we
have to merge them using java program.
Code:
import java.util.Arrays;
public class Arr6 {

public static void main(String[] args) {


int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] arr2 = {11, 12, 13, 14, 15};

// Create a new array with combined length of arr1 and arr2


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

// Copy elements from arr1 and arr2 into mergedArray


System.arraycopy(arr1, 0, mergedArray, 0, arr1.length);
System.arraycopy(arr2, 0, mergedArray, arr1.length, arr2.length);

// Print merged array


System.out.println("Merged array: " + Arrays.toString(mergedArray));
}

Q7. Read and print a two dimensional array Read number of rows and columns,
array elements for two dimensional array and print in matrix format using java
program.
Code:
import java.util.Scanner;
public class Arr7 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter number of columns: ");
int cols = scanner.nextInt();

int[][] matrix = new int[rows][cols];


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

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


for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}

System.out.println("Matrix is:");
for (int[] row : matrix) {
for (int elem : row) System.out.print(elem + " ");
System.out.println();
}
}

}
Q8. Count strings and integers from an array Given an array with strings and
integers and we have to count strings and integers using java program.
Code:
public class Arr8 {
public static void main(String[] args) {
Object[] arr = {"Raj", "77", "101", "99", "Jio"};
int stringCount = 0, intCount = 0;

for (Object obj : arr) {


if (obj instanceof String) {
try {
Integer.parseInt((String) obj);
intCount++;
} catch (NumberFormatException e) {
stringCount++;
}
}
}

System.out.println("Numeric: " + intCount);


System.out.println("Strings: " + stringCount);
}
}

Q9. Remove duplicate elements from an array Given an array of integers and we
have to remove duplicate elements using java program.
Code:
import java.util.Arrays;
public class Arr9 {

public static void main(String[] args) {


int[] arr = {1, 2, 3, 1, 2, 3, 4};
int[] uniqueArr = Arrays.stream(arr).distinct().toArray();

System.out.println("Elements after removing duplicates: " +


Arrays.toString(uniqueArr));
}

Q10. Find second largest element in an array Given an array of N integers and we
have to find its second largest element using Java program.
Code:
import java.util.Arrays;
public class Arr10 {

public static void main(String[] args) {


int[] arr = {45, 25, 69, 40};
Arrays.sort(arr);
System.out.println("Second largest element is: " + arr[arr.length - 2]);
}

Q11. Find second smallest element in an array .Given an array of N integers and
we have to find its second minimum/smallest element using Java program.
Code:
import java.util.Arrays;
public class Arr11 {

public static void main(String[] args) {


int[] arr = {45, 25, 69, 40};
Arrays.sort(arr);
System.out.println("Second smallest element is: " + arr[1]);
}

Q12. Find smallest element in an array Given an array of N integers and we have
to find its minimum/smallest element using Java program.
Code:
import java.util.Arrays;
public class Arr12 {

public static void main(String[] args) {


int[] arr = {45, 25, 69, 40};
int smallest = Arrays.stream(arr).min().getAsInt();
System.out.println("Smallest element is: " + smallest);
}

Q13. Count total positives, negatives and zeros from an array Given an array of
integers and we have to count total negatives, positives and zeros using java
program.
Code:
public class Arr13 {

public static void main(String[] args) {


int[] arr = {20, -10, 15, 0, -85};
int positives = 0, negatives = 0, zeros = 0;

for (int num : arr) {


if (num > 0) positives++;
else if (num < 0) negatives++;
else zeros++;
}
System.out.println("Positive Numbers: " + positives);
System.out.println("Negative Numbers: " + negatives);
System.out.println("Zeros: " + zeros);
}

Q14. Access elements of character array using for each loop In this program, we
will create an array of characters and access its elements using for each loop and
print it on the screen.
Code:
public class Arr14 {

public static void main(String[] args) {


char[] charArray = {'A', 'B', 'C', 'D', 'E', 'F'};
System.out.println("Array elements:");
for (char ch : charArray) {
System.out.println(ch);
}
}

Q15. Find prime and non-prime numbers in the array Given/input an integer
array, we have to find prime and non-prime numbers in the array.
Code:
public class Arr15 {

public static void main(String[] args) {


int[] arr = {10, 11, 13, 15, 17, 19, 23, 25, 30};
for (int num : arr) {
if (isPrime(num)) System.out.println(num + " - Prime");
else System.out.println(num + " - Not Prime");
}
}

public static boolean isPrime(int num) {


if (num < 2) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}

Q16. Search an item into the array using linear search The linear searching
algorithm is used to find the item in an array, This algorithm consists the
checking every item in the array until the required item is found or till the last
item is in the array. The linear search algorithm is also known as a sequential
algorithm. In this program, we will create an array of integers then we will search
an item into the array using linear search and print position of the item in the
array.
Code:
import java.util.Scanner;
public class Arr16 {

public static void main(String[] args) {


int[] arr = {10, 20, 30, 40, 50};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter item to search: ");
int target = scanner.nextInt();
boolean found = false;

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


if (arr[i] == target) {
System.out.println("Item found at index: " + i);
found = true;
break;
}
}

if (!found) System.out.println("Item not found");


}

Q17. Search an item in an array using binary search The binary searching
algorithm is used to find the item in a sorted array with the minimum number of
comparisons, in this algorithm key element compares with the middle index item.
In this program, we will create an array of sorted integers then we will search an
item into an array using binary search and print the position of the item in the
array.
Code:
import java.util.Arrays;
import java.util.Scanner;
public class Arr17 {

public static void main(String[] args) {


int[] arr = {10, 20, 30, 40, 50};
Arrays.sort(arr); // Ensure the array is sorted
Scanner scanner = new Scanner(System.in);
System.out.print("Enter item to search: ");
int target = scanner.nextInt();

int left = 0, right = arr.length - 1, mid;


boolean found = false;

while (left <= right) {


mid = left + (right - left) / 2;
if (arr[mid] == target) {
System.out.println("Item found at index: " + mid);
found = true;
break;
}
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}

if (!found) System.out.println("Item not found");


}

Q18. This is the Java Program to Find Repeated Elements and the Frequency of
Repetition. Problem Description Given an array of integers, find and print the
repeated elements and their frequency of repetition.
Code:
import java.util.HashMap;
public class Arr18 {

public static void main(String[] args) {


int[] arr = {1, 2, 3, 4, 5, 5, 3};
HashMap<Integer, Integer> frequencyMap = new HashMap<>();

for (int num : arr) {


frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}

System.out.println("Element -> Frequency");


for (int num : frequencyMap.keySet()) {
if (frequencyMap.get(num) > 1) {
System.out.println(num + " -> " + frequencyMap.get(num));
}
}
}

}
Q19. This is the Java Program to Find the Elements that do Not have Duplicates.
Problem Description Given an array, print all the elements whose frequency is
one, that is they do not have duplicates.
Code:
import java.util.HashMap;
public class Arr19 {

public static void main(String[] args) {


int[] arr = {-1, -2, 3, 3, -2};
HashMap<Integer, Integer> frequencyMap = new HashMap<>();

for (int num : arr) {


frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}

System.out.println("Elements with no duplicates:");


for (int num : frequencyMap.keySet()) {
if (frequencyMap.get(num) == 1) {
System.out.println(num);
}
}
}

Q20. his is the Java Program to Print Elements Which Occurs Even Number of
Times. Problem Description Given an array of elements, print the elements
whose frequency is even.
Code:
import java.util.HashMap;
public class Arr20 {

public static void main(String[] args) {


int[] arr = {5, 5, 2, 2, 2, 4, 4, 1, 7, 1};
HashMap<Integer, Integer> frequencyMap = new HashMap<>();

for (int num : arr) {


frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}

System.out.println("Elements with even frequency:");


for (int num : frequencyMap.keySet()) {
if (frequencyMap.get(num) % 2 == 0) {
System.out.print(num + " ");
}
}
}

Q21. This is the Java Program to Print Elements Which Occur Odd Number of
Times. Problem Description Given an array of integers, print all the elements
whose frequency are odd.
Code:
import java.util.HashMap;
public class Arr21 {

public static void main(String[] args) {


int[] arr = {5, 4, 4, 2, 1};
HashMap<Integer, Integer> frequencyMap = new HashMap<>();

for (int num : arr) {


frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}

System.out.println("Elements with odd frequency:");


for (int num : frequencyMap.keySet()) {
if (frequencyMap.get(num) % 2 != 0) {
System.out.print(num + " ");
}
}
}

Q22. Given an array of integers, print the even numbers present at even index
numbers.
Code:
public class Arr22 {

public static void main(String[] args) {


int[] arr = {2, 1, 4, 4, 5, 7};
System.out.print("Even numbers at even indices: ");

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


if (arr[i] % 2 == 0) {
System.out.print(arr[i] + " ");
}
}
}

Q23. Problem Description Given an array of integers, find the longest contiguous
subarray whose elements are increasing, that is, the elements following the
preceding elements in the subarray must be greater than them.
Code:
public class Arr23 {
public static void main(String[] args) {
int[] arr = {5, 6, 3, 0, 7, 8, 9, 1, 2};
int start = 0, maxLength = 1, maxStart = 0;

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


if (arr[i] > arr[i - 1]) {
if (i - start + 1 > maxLength) {
maxLength = i - start + 1;
maxStart = start;
}
} else {
start = i;
}
}

System.out.print("Longest increasing subarray: ");


for (int i = maxStart; i < maxStart + maxLength; i++) {
System.out.print(arr[i] + " ");
}
}

Q24. Given an array of integers, find the longest contiguous subarray whose
elements are decreasing, that is, the elements following the preceding elements
in the subarray must be smaller than them.
Code:
public class Arr24 {
public static void main(String[] args) {
int[] arr = {5, 6, 3, 0, 7, 8, 9, 1, 2};
int start = 0, maxLength = 1, maxStart = 0;

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


if (arr[i] < arr[i - 1]) {
if (i - start + 1 > maxLength) {
maxLength = i - start + 1;
maxStart = start;
}
} else {
start = i;
}
}

System.out.print("Longest decreasing subarray: ");


for (int i = maxStart; i < maxStart + maxLength; i++) {
System.out.print(arr[i] + " ");
}

Q25. This is a Java Program to Sort Names in an Alphabetical Order. Enter size of
array and then enter all the names in that array. Now with the help of compareTo
operator we can easily sort names in Alphabetical Order.
Code:
import java.util.Arrays;
import java.util.Scanner;
public class Arr25 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of names: ");
int n = scanner.nextInt();
String[] names = new String[n];
System.out.println("Enter names:");

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


names[i] = scanner.next();
}

Arrays.sort(names);
System.out.println("Names in sorted order: " + String.join(", ", names));
}
}

Q26. Problem Description Given an array of integers, shift all the zeroes present
in it to the beginning.
Code:
public class Arr26 {
public static void main(String[] args) {
int[] arr = {1, 0, 2, 3, 0, 4};
int index = arr.length - 1;

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


if (arr[i] != 0) {
arr[index--] = arr[i];
}
}

while (index >= 0) {


arr[index--] = 0;
}

System.out.println("Array after shifting zeros to beginning: ");


for (int num : arr) System.out.print(num + " ");
}

Q27. Problem Description Given an array of integers, shift all the zeroes present
in it to the end.
Code:
public class Arr27 {
public static void main(String[] args) {
int[] arr = {1, 0, 2, 3, 0, 4};
int index = 0;

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


if (arr[i] != 0) {
arr[index++] = arr[i];
}
}

while (index < arr.length) {


arr[index++] = 0;
}

System.out.println("Array after shifting zeros to end:");


for (int num : arr) System.out.print(num + " ");
}

Q28. Problem Description Given two arrays of integers, find and print the union
and intersection of the arrays.
Code:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Arr28 {

public static void main(String[] args) {


Integer[] arr1 = {1, 2, 3, 4, 5};
Integer[] arr2 = {5, 3, 6, 7, 9};

Set<Integer> unionSet = new HashSet<>(Arrays.asList(arr1));


unionSet.addAll(Arrays.asList(arr2));
System.out.println("Union: " + unionSet);

Set<Integer> intersectionSet = new HashSet<>(Arrays.asList(arr1));


intersectionSet.retainAll(Arrays.asList(arr2));
System.out.println("Intersection: " + intersectionSet);
}

}
Q29. Given an array arr of n elements that is first strictly increasing and then
maybe strictly decreasing, find the maximum element in the array. Note: If the
array is increasing then just print the last element will be the maximum value.
Code:
public class Arr29 {
public static void main(String[] args) {
int[] arr = {10, 20, 15, 2, 23, 90, 67};
int max = arr[0];

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


if (arr[i] > max) max = arr[i];
}

System.out.println("Maximum element in the array is: " + max);


}
}

Q30. An array contains both positive and negative numbers in random order.
Rearrange the array elements so that all negative numbers appear before all
positive numbers.
Code:
public class Arr30 {
public static void main(String[] args) {
int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
int index = 0;

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


if (arr[i] < 0) {
int temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
index++;
}
}

System.out.println("Array after rearranging:");


for (int num : arr) System.out.print(num + " ");
}
}
Q31. Given an array arr[] of non-negative integers and an integer sum, find a
subarray that adds to a given sum. Note: There may be more than one subarray
with sum as the given sum, print first such subarray.
Code:
public class Arr31 {
public static void main(String[] args) {
int[] arr = {1, 4, 20, 3, 10, 5};
int targetSum = 33;
boolean found = false;

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


int sum = 0;
for (int j = i; j < arr.length; j++) {
sum += arr[j];
if (sum == targetSum) {
System.out.println("Sum found between indexes " + i + " and " + j);
found = true;
break;
}
}
if (found) break;
}

if (!found) System.out.println("No subarray found with the given sum.");


}
}

Q32. Find the first repeating element in an array of integers Given an array of
integers arr[], The task is to find the index of first repeating element in it i.e. the
element that occurs more than once and whose index of the first occurrence is
the smallest.
Code:
import java.util.HashMap;

public class Arr32 {


public static void main(String[] args) {
int[] arr = {10, 5, 3, 4, 3, 5, 6};
HashMap<Integer, Integer> map = new HashMap<>();
int firstRepeating = -1;

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


if (map.containsKey(arr[i])) {
firstRepeating = arr[i];
} else {
map.put(arr[i], 1);
}
}

System.out.println("First repeating element is: " + firstRepeating);


}
}

Q33. Maximum Product Subarray Given an array that contains both positive and
negative integers, the task is to find the product of the maximum product
subarray.
Code:
public class Arr33 {
public static void main(String[] args) {
int[] arr = {6, -3, -10, 0, 2};
int maxProduct = arr[0], minProduct = arr[0], result = arr[0];

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


if (arr[i] < 0) {
int temp = maxProduct;
maxProduct = minProduct;
minProduct = temp;
}
maxProduct = Math.max(arr[i], maxProduct * arr[i]);
minProduct = Math.min(arr[i], minProduct * arr[i]);
result = Math.max(result, maxProduct);
}

System.out.println("Maximum product subarray is: " + result);


}
}

Q34. Program to remove duplicates from integer array without Collection.


Code:
public class Arr34 {
public static void main(String[] args) {
int[] arr = {1, 1, 2, 2, 3, 4, 5};
int length = arr.length;

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


for (int j = i + 1; j < length; j++) {
if (arr[i] == arr[j]) {
arr[j] = 0; // Mark duplicate as 0
}
}
}

System.out.print("Array after removing duplicates: ");


for (int num : arr) System.out.print(num + " ");
}
}

Q35. Program to find the smallest and largest number in an integer array.
Code:
public class Arr35 {
public static void main(String[] args) {
int[] arr = {-20, 34, 21, -87, 92, 2147483647};
int min = arr[0], max = arr[0];

for (int num : arr) {


if (num < min) min = num;
if (num > max) max = num;
}

System.out.println("Smallest number in array: " + min);


System.out.println("Largest number in array: " + max);
}
}

Q36. Reverse int and String array


Code:
public class Arr36 {
public static void main(String[] args) {
int[] intArray = {101, 102, 103, 104, 105};
String[] strArray = {"one", "two", "three", "four", "five"};

reverseArray(intArray);
reverseArray(strArray);

System.out.print("Reversed int array: ");


for (int num : intArray) System.out.print(num + " ");
System.out.print("\nReversed String array: ");
for (String str : strArray) System.out.print(str + " ");
}
public static void reverseArray(int[] arr) {
int start = 0, end = arr.length - 1;
while (start < end) {
int temp = arr[start];
arr[start++] = arr[end];
arr[end--] = temp;
}
}

public static void reverseArray(String[] arr) {


int start = 0, end = arr.length - 1;
while (start < end) {
String temp = arr[start];
arr[start++] = arr[end];
arr[end--] = temp;
}
}
}

Q37. Write a program to test if an array contains a specific value.


Code:
public class Arr37 {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int target = 30;
boolean found = false;

for (int num : arr) {


if (num == target) {
found = true;
break;
}
}

if (found) System.out.println("Array contains " + target);


else System.out.println("Array does not contain " + target);
}
}

Q38. Write a program to find the index of an array element.


Code:
public class Arr38 {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int target = 40;
int index = -1;

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


if (arr[i] == target) {
index = i;
break;
}
}

if (index != -1) System.out.println("Index of " + target + " is: " + index);


else System.out.println(target + " not found in array.");
}
}

Q39. Write a program to remove a specific element from an array.


Code:
import java.util.Arrays;

public class Arr39 {


public static void main(String[] args) {
int[] arr = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
int target = 15;

int[] newArr = Arrays.stream(arr).filter(num -> num != target).toArray();

System.out.print("Array after removing " + target + ": ");


for (int num : newArr) System.out.print(num + " ");
}
}

Q40. Matrix Multiplication Program


Code:
import java.util.Scanner;

public class Arr40 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter rows and columns for first matrix: ");
int rows1 = scanner.nextInt(), cols1 = scanner.nextInt();
System.out.print("Enter rows and columns for second matrix: ");
int rows2 = scanner.nextInt(), cols2 = scanner.nextInt();

if (cols1 != rows2) {
System.out.println("Matrix multiplication not possible.");
return;
}

int[][] matrix1 = new int[rows1][cols1];


int[][] matrix2 = new int[rows2][cols2];
int[][] result = new int[rows1][cols2];

System.out.println("Enter first matrix:");


for (int i = 0; i < rows1; i++)
for (int j = 0; j < cols1; j++)
matrix1[i][j] = scanner.nextInt();

System.out.println("Enter second matrix:");


for (int i = 0; i < rows2; i++)
for (int j = 0; j < cols2; j++)
matrix2[i][j] = scanner.nextInt();

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


for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

System.out.println("Product of matrices:");
for (int[] row : result) {
for (int val : row) System.out.print(val + " ");
System.out.println();
}
}
}
Q41. Passing Division Program
Code:
import java.util.Scanner;

public class Arr41 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] marks = new int[5];
String[] subjects = {"Math", "English", "Science", "Art", "Computer"};
int totalMarks = 0;

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


System.out.print("Enter marks of " + subjects[i] + ": ");
marks[i] = scanner.nextInt();
totalMarks += marks[i];
}

int maxMarks = marks.length * 100;


double percentage = (double) totalMarks / maxMarks * 100;

System.out.println("Total marks out of " + maxMarks + " = " + totalMarks);


System.out.println("Percentage of marks = " + percentage);
if (percentage >= 60) System.out.println("First Division");
else if (percentage >= 45) System.out.println("Second Division");
else if (percentage >= 33) System.out.println("Third Division");
else System.out.println("Failed");
}
}
Q42. Find second largest element in an array Given an array of N integers and we
have to find its second largest element
Code:
import java.util.Arrays;

public class Arr42 {


public static void main(String[] args) {
int[] arr = {45, 25, 69, 40};
Arrays.sort(arr);
System.out.println("Second largest element is: " + arr[arr.length - 2]);
}
}

Q43. Find second smallest element in an array Given an array of N integers and
we have to find its second minimum/smallest element
Code:
import java.util.Arrays;

public class Arr43 {


public static void main(String[] args) {
int[] arr = {45, 25, 69, 40};
Arrays.sort(arr);
System.out.println("Second smallest element is: " + arr[1]);
}
}

Q44. Count total positives, negatives and zeros from an array Given an array of
integers and we have to count total negatives, positives and zeros
Code:
public class Arr44 {
public static void main(String[] args) {
int[] arr = {20, -10, 15, 0, -85};
int positives = 0, negatives = 0, zeros = 0;

for (int num : arr) {


if (num > 0) positives++;
else if (num < 0) negatives++;
else zeros++;
}

System.out.println("Positive Numbers: " + positives);


System.out.println("Negative Numbers: " + negatives);
System.out.println("Zeros: " + zeros);
}
}

Q45. Find the length of an array In this program, we will create an array of 10
integers then we will find the length of the array
Code:
public class Arr45 {
public static void main(String[] args) {
int[] intArr = new int[10];
System.out.println("Length of array is: " + intArr.length);
}
}

Q46. Find prime and non-prime numbers in the array Given/input an integer
array, we have to find prime and non-prime numbers in the array.
Code:
public class Arr46 {
public static void main(String[] args) {
int[] arr = {10, 11, 13, 15, 17, 19, 23, 25, 30};

for (int num : arr) {


if (isPrime(num)) System.out.println(num + " - Prime");
else System.out.println(num + " - Not Prime");
}
}

public static boolean isPrime(int num) {


if (num < 2) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}
}

Q48. Program to Find the Largest Two Numbers in a Given Array. Enter size of
array and then enter all the elements of that array.
Code:
import java.util.Scanner;

public class Arr48 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements:");
for (int i = 0; i < n; i++) arr[i] = scanner.nextInt();

int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;


for (int num : arr) {
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2 && num != max1) {
max2 = num;
}
}

System.out.println("First largest is: " + max1);


System.out.println("Second largest is: " + max2);
}
}

Q49. Program to Separate Odd and Even Numbers from an Array Program to Put
Even & Odd Elements of an Array in 2 Separate Arrays
Code:
public class Arr49 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
StringBuilder odd = new StringBuilder(), even = new StringBuilder();

for (int num : arr) {


if (num % 2 == 0) even.append(num).append(" ");
else odd.append(num).append(" ");
}

System.out.println("Odd: " + odd.toString());


System.out.println("Even: " + even.toString());
}
}

Q50. Problem Description Given an array of integers, find the longest contiguous
subarray whose elements are increasing, that is, the elements following the
preceding elements in the subarray must be greater than them.
Code:
public class Arr50 {
public static void main(String[] args) {
int[] arr = {5, 6, 3, 0, 7, 8, 9, 1, 2};
int start = 0, maxLength = 1, maxStart = 0;

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


if (arr[i] > arr[i - 1]) {
if (i - start + 1 > maxLength) {
maxLength = i - start + 1;
maxStart = start;
}
} else {
start = i;
}
}

System.out.print("Longest increasing subarray: ");


for (int i = maxStart; i < maxStart + maxLength; i++) {
System.out.print(arr[i] + " ");
}
}
}

You might also like