-
Notifications
You must be signed in to change notification settings - Fork 1
/
017_UpdateFirstElementOfAnArray.java
50 lines (38 loc) · 1.81 KB
/
017_UpdateFirstElementOfAnArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.Scanner;
public class UpdateFirstElementOfAnArray {
// Function to update the first element of the array with the given value
// Time Complexity: O(1), Space Complexity: O(1)
public static void updateFirstElement(int[] arr, int x) {
arr[0] = x; // Update the first element of the array
}
// Function to print the elements of the array
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " "); // Print each element followed by two spaces
}
System.out.println(); // Move to the next line after printing all elements
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Create a Scanner object for user input
// Prompt user for the size of the array and read the input
System.out.print("Enter size of the array: ");
int n = sc.nextInt();
int[] arr = new int[n]; // Initialize the array with the specified size
// Prompt user to enter the array elements and read them
System.out.println("Enter array elements: ");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Prompt user to enter the new value for the first element
System.out.print("Enter the element: ");
int x = sc.nextInt();
// Print the array elements before the update
System.out.print("Before update array elements are: ");
printArray(arr);
// Update the first element of the array with the new value
updateFirstElement(arr, x);
// Print the array elements after the update
System.out.print("After update array elements are: ");
printArray(arr);
}
}