Pass by Value
Completed
Write static void addOne(int x) that adds 1 to its parameter, and static void addOneAll(int[] a) that adds 1 to every element. Read a number and an array, call both, and print the number and the array.
Input
Line 1: a number. Line 2: n. Line 3: n integers.
Output
Two lines: the (unchanged) number, then the changed array.
Example
Input
5 3 1 2 3
Output
5 [2, 3, 4]
Editor
Java
Hints
Java always passes a copy of the value.
For an array, the copied value is a reference to the same array.
Solution explanation
Changing a primitive parameter never affects the caller; changing an array's contents does, because both refer to the same array.
Show solution
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static void addOne(int x) {
x++;
}
static void addOneAll(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i]++;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
addOne(number);
addOneAll(a);
System.out.println(number);
System.out.println(Arrays.toString(a));
}
}