Java: Multiply corresponding elements of two arrays of integers
Multiply Array Elements
Write a Java program to multiply the corresponding elements of two integer arrays.
Sample Solution:
Java Code:
import java.util.*;
public class Exercise83 {
public static void main(String[] args) {
// Initialize a string to store the result
String result = "";
// Define two integer arrays
int[] left_array = {1, 3, -5, 4};
int[] right_array = {1, 4, -5, -2};
// Print the elements of Array1
System.out.println("\nArray1: " + Arrays.toString(left_array));
// Print the elements of Array2
System.out.println("\nArray2: " + Arrays.toString(right_array));
// Multiply corresponding elements from both arrays and build the result string
for (int i = 0; i < left_array.length; i++) {
int num1 = left_array[i];
int num2 = right_array[i];
result += Integer.toString(num1 * num2) + " ";
}
// Print the result string
System.out.println("\nResult: " + result);
}
}
Sample Output:
Array1: [1, 3, -5, 4] Array2: [1, 4, -5, -2] Result: 1 12 25 -8
Pictorial Presentation:
Flowchart:
For more Practice: Solve these Related Problems:
- Modify the program to add corresponding elements instead of multiplying.
- Write a program to divide corresponding elements of two arrays.
- Modify the program to return an array where each element is the square of the original.
- Write a program to check if all elements in one array are multiples of another array's elements.
Go to:
PREV : Largest of First, Last, Middle.
NEXT : Add Last 3 Chars to Both Ends.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.