Functions & Pass by Value/Reference
Write a function that returns the square of an integer. Call it and print both the result and the original value to show that the caller value is unchanged.
Work through the cases
3 examplesInput notation
One integer x, with absolute value at most 10000.Expected result
The square and the original value, separated by a space.Case 1
Input
6
Expected output
36 6
Case 2
Input
-3
Expected output
9 -3
Case 3
Input
0
Expected output
0 0
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
Call a function that computes a square without modifying the caller value. Time and extra space: O(1).
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Long> values = new ArrayList<>();
while (in.hasNextLong()) values.add(in.nextLong());
long[] a = values.stream().mapToLong(Long::longValue).toArray();
long n = a[0];
java.util.function.LongUnaryOperator square = x -> x * x; System.out.println(square.applyAsLong(n) + " " + n);
}
}
Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.