Use Java to answer the question: Given an array of integers. Now you need to imp
ID: 3796304 • Letter: U
Question
Use Java to answer the question:
Given an array of integers. Now you need to implement four functions. a) add(int arr[]) - should add integer 2 to each element of the array. b) subtract(int arr[]) - should subtract 1 from each element of the array c) multiply(int arr[]) - each element of the array should be multiplied by 3 d) divide(int arr[])- each element of the array should be divided by 2 Each of the four functions, take an integer array as its parameter. The return type of the function is also an array.First pass the input array, say x[] to the add function. Get the result of the add function. Pass this result to the subtract function. Get the result from the subtract function. Pass this result to the multiply function and so on. Eg:- arr = add(arr) arr = subtract(arr) arr = multiply(arr) arr = divide(arr) Finally print the array, using a loop.
Explanation / Answer
ArraysImp.java :
package org.chegg;
import java.util.Scanner;
public class ArraysImp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter length of the array:");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter array elements:");
for(int i=0;i<arr.length;i++)
arr[i] = sc.nextInt();
arr = add(arr);
arr = sub(arr);
arr = multiply(arr);
arr = divide(arr);
System.out.println("Final array elements are:");
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]+ " ");
}
public static int[] add(int[] arr){
for(int i=0;i<arr.length;i++)
arr[i] = arr[i] + 2;
return arr;
}
public static int[] sub(int[] arr){
for(int i=0;i<arr.length;i++)
arr[i] = arr[i] - 1 ;
return arr;
}
public static int[] multiply(int[] arr){
for(int i=0;i<arr.length;i++)
arr[i] = arr[i] * 3 ;
return arr;
}
public static int[] divide(int[] arr){
for(int i=0;i<arr.length;i++)
arr[i] = arr[i] / 2 ;
return arr;
}
}
Sample Input & output:
Enter length of the array:
5
Enter array elements:
7 4 3 8 9
Final array elements are:
12
7
6
13
15
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.