diff --git a/OOP/Java/Lab/Week12/ArrayExchange.java b/OOP/Java/Lab/Week12/ArrayExchange.java new file mode 100644 index 0000000..5d9c518 --- /dev/null +++ b/OOP/Java/Lab/Week12/ArrayExchange.java @@ -0,0 +1,46 @@ +public class ArrayExchange { + + public static void swapElements(T[] array, int pos1, int pos2) { + T temp = array[pos1]; + array[pos1] = array[pos2]; + array[pos2] = temp; + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.print("Enter number of elements: "); + int size = scanner.nextInt(); + scanner.nextLine(); // consume newline + + String[] array = new String[size]; + + // Get array elements from user + for (int i = 0; i < size; i++) { + System.out.print("Enter element " + i + ": "); + array[i] = scanner.nextLine(); + } + + System.out.println("\nOriginal array: "); + for (String element : array) { + System.out.print(element + " "); + } + + System.out.print("\nEnter first position to swap: "); + int pos1 = scanner.nextInt(); + + System.out.print("Enter second position to swap: "); + int pos2 = scanner.nextInt(); + + swapElements(array, pos1, pos2); + + System.out.println( + "\nArray after swapping positions " + pos1 + " and " + pos2 + ": " + ); + for (String element : array) { + System.out.print(element + " "); + } + + scanner.close(); + } +}