Write a program with a function which accepts an array of integers and a key value. The
function should return the sum of all the multiples of the key value in the array. For example,
for the array {1, 4, 10, 12, 15, 20, 22} and the key value 5, the function should return the sum
10+15+20.
Answers
Answer:
import java.util.Scanner;
public class Main {
public static int solve(int[] arr, int key) {
int sum = 0;
for(int i: arr) {
if(i % key == 0)
sum += i;
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the length of the array : ");
int n = sc.nextInt();
int[] arr = new int[n];
int i = 0;
while(n-- > 0) {
int number = sc.nextInt();
arr[i] = number;
i++;
}
System.out.println("Enter the key value : ");
int key = sc.nextInt();
int result = solve(arr, key);
System.out.println(result);
}
}
Explanation:
- We are asking the user for the length of the array
- Then we are creating the array and setting the length of the array
- We are then accepting the numbers from the users and appending to the array.
- After that, we accept the key value from the user again and store it in a variable called "key".
- We are then passing the array as well as the key value as the parameter to our main function named "solve".
- The "solve" function will iterate through the array and check for each number if when it is divided with the key value, does it return 0 as the remainder (eg. 20/5 = quotient = 4, remainder = 0), If true then store the number is a variable called "sum" and return the value.
- The "solve" function will return the value which will be stored in the "result" variable.
- The Last step, we will print the "result" variable to the console.