You are given an array nums
of integers. Write a Java method traverseAndMultiply
that performs the following operations:
The method should have the following signature:
public static void traverseAndMultiply(int[] nums)
Example:
Input:
int[] nums = {1, 2, 3, 4, 5}
Output:
[2, 4, 6, 8, 10]
Note:
public class ArrayTraversal {
public static void traverseAndMultiply(int[] nums) {
// Traverse the array starting from index 0
// Iterate using a standard for loop
for (int i = 0; i < nums.length; i++) {
// Multiply each element of the array by 2
nums[i] *= 2;
}
// Print the modified array
System.out.print("[");
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]);
// Add comma and space for elements except the last one
if (i < nums.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5};
traverseAndMultiply(nums);
}
}
The traverseAndMultiply
method takes an array of integers nums
as input. It uses a for
loop to traverse the array and multiply each element by 2. The modified array is then printed using another for
loop.
In the for
loop, the variable i
is used as the index to access each element. The element is multiplied by 2 using the compound assignment operator *=
, which is short for nums[i] = nums[i] * 2
.
After multiplying each element, the modified array is printed. First, the opening square bracket [
is printed. Then, each element of the array is printed using a for
loop. A comma and space are added after each element, except for the last one. Finally, the closing square bracket ]
is printed, resulting in the modified array being displayed.