Square at Alternate Indices
Given an array
Sample Input 1
[ 1, 2, 3, 4, 5 ]
Sample Output 1
[ 1, 2, 9, 4, 25 ]
Sample Input 2
[ 2, 4 ]
Sample Output 2
[ 4, 4 ]
public int[] squareAlt(int[] myArray) {
// create array to return
int[] ans = new int[myArray.length];
// iterate over myArray
for(int i = 0; i < myArray.length; i++) {
// if even index, square the number
if(i%2 == 0) {
ans[i] = myArray[i]*myArray[i];
}
// else number remain as it is
else {
ans[i] = myArray[i];
}
}
// return ans array
return ans;
}
The above code in Java has a method public int[] squareAlt(int[] myArray) which takes in integer array and outputs an integer array where each element is squared if the it's index if even.
Following is the code to test that above method works correctly(only for testing):
import java.util.*;
public class MyClass {
public int[] squareAlt(int[] myArray) {
// create array to return
int[] ans = new int[myArray.length];
// iterate over myArray
for(int i = 0; i < myArray.length; i++) {
// if even index, square the number
if(i%2 == 0) {
ans[i] = myArray[i]*myArray[i];
}
// else number remain as it is
else {
ans[i] = myArray[i];
}
}
// return ans array
return ans;
}
public static void main(String[] args) {
MyClass obj = new MyClass();
Scanner sc = new Scanner(System.in);
String[] p = sc.nextLine().split(", ");
int[] arr = new int[p.length];
for (int i = 0; i < p.length; i++) {
arr[i] = Integer.parseInt(p[i]);
}
int[] ans = obj.squareAlt(arr);
for (int i = 0; i < ans.length; i++) {
System.out.print(ans[i]);
if(i != ans.length-1)
System.out.print(", ");
}
}
}
Comments
Leave a comment