Sunday 1 October 2017

Java program that takes two arrays a and b of length n storing int values, and returns the dot product of a and b. That is, it returns an array c of length n such that c[i] = a[i] · b[i], for i = 0, . . . ,n−1.

Problem:

Write a short Java program that takes two arrays a and b of length n storing int
values, and returns the dot product of a and b. That is, it returns an array c of
length n such that c[i] = a[i] · b[i], for i = 0, . . . ,n−1.

Solution:

package com.basics;

import java.util.Arrays;
import java.util.Scanner;

public class ArrayProduct {

static int[] arrayOne;
static int[] arrayTwo;
static int[] resultArray;
int arrayLimit;

public static void main(String[] args) {
ArrayProduct arrayProduct = new ArrayProduct();
arrayProduct.initializeTheArrays();
arrayProduct.findArrayProduct();
System.out.println("The first Array elements are " + Arrays.toString(arrayOne));
System.out.println("The second Array elements are " + Arrays.toString(arrayTwo));
System.out.println("The product result Array elements are " + Arrays.toString(resultArray));
}

public void initializeTheArrays(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the array limit");
arrayLimit = scanner.nextInt();
arrayOne = new int[arrayLimit];
arrayTwo = new int[arrayLimit];
resultArray = new int[arrayLimit];
System.out.println("enter the first array elements");
for (int i = 0; i < arrayOne.length; i++) {
System.out.println("enter the element");
arrayOne[i] = scanner.nextInt();
}
System.out.println("enter the second array elements");
for (int i = 0; i < arrayTwo.length; i++) {
System.out.println("enter the element");
arrayTwo[i] = scanner.nextInt();
}
scanner.close();
}

public void findArrayProduct(){
for (int i = 0; i < arrayOne.length; i++) {
resultArray[i] = arrayOne[i] * arrayTwo[i];
}
}
}


Output:

enter the array limit
3
enter the first array elements
enter the element
2
enter the element
3
enter the element
4
enter the second array elements
enter the element
5
enter the element
6
enter the element
7
The first Array elements are [2, 3, 4]
The second Array elements are [5, 6, 7]
The product result Array elements are [10, 18, 28]


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...