LAB 8 Classwork
unknown
java
a year ago
3.2 kB
23
Indexable
//classwork one import java.util.Scanner; public class ClassworkOne { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("N = "); int N = sc.nextInt(); int[] array = new int[N]; for (int i = 0; i < N; i++) { System.out.print("Enter a number: "); array[i] = sc.nextInt(); } System.out.println("The elements of the array are: "); for (int i = 0; i < N; i++) { System.out.println(i + ": " + array[i]); } System.out.print("Enter another number: "); int newNum = sc.nextInt(); int[] resizedArray = new int[N + 1]; for (int i = 0; i < N; i++) { resizedArray[i] = array[i]; } resizedArray[N] = newNum; System.out.println("After resizing the array:"); for (int i = 0; i < resizedArray.length; i++) { System.out.print(resizedArray[i] + " "); } } } //classwork two public class ClassworkTwo { public static void main(String[] args) { int[] array = {9, -5, 7, 9, -5, 5, 7}; System.out.println("Before removing duplicates:"); for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } for (int i = 0; i < array.length; i++) { if (array[i] != 0) { for (int j = i + 1; j < array.length; j++) { if (array[i] == array[j]) { array[j] = 0; } } } } System.out.println("\nAfter replacing duplicates with 0:"); for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); } } //classwork three import java.util.Scanner; public class ClassworkThree { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the length of the array: "); int length = sc.nextInt(); int[] array = new int[length]; for (int i = 0; i < length; i++) { System.out.print("Enter a number: "); array[i] = sc.nextInt(); } int[] reversedArrayOutOfPlace = new int[length]; for (int i = 0; i < length; i++) { reversedArrayOutOfPlace[length - 1 - i] = array[i]; } System.out.println("Reversed Array using a new array:"); for (int i = 0; i < length; i++) { System.out.print(reversedArrayOutOfPlace[i] + " "); } System.out.println(); for (int i = 0; i < length / 2; i++) { int temp = array[i]; array[i] = array[length - 1 - i]; array[length - 1 - i] = temp; } System.out.println("Reversed the original array:"); for (int i = 0; i < length; i++) { System.out.print(array[i] + " "); } System.out.println(); } }
Editor is loading...
Leave a Comment