Define a class to declare an array of size twenty of double datatype, accept the elements into the array and perform the following: - Calculate and print the product of all the elements. - Print the square of each element of the array.
Topic: Product and squares of array elements
Answer
import java.util.Scanner;
class ProductSquare { public static void main(String args[]) { Scanner sc = new Scanner(System.in); double arr[] = new double[20]; double prod = 1.0;
System.out.println("Enter 20 double values :"); for(int i = 0; i < 20; i++) { arr[i] = sc.nextDouble(); prod = prod * arr[i]; }
System.out.println("Product of all elements = " + prod);
System.out.println("Squares of the elements :"); for(int i = 0; i < 20; i++) System.out.println(arr[i] + " squared = " + (arr[i] * arr[i])); } }
Two straightforward tasks, with one initialisation that decides the whole answer.
The product accumulator MUST start at 1.0, never at 0.0. An accumulator built by addition starts at 0, but one built by multiplication starts at 1 — because 0 multiplied by anything remains 0, and the program would confidently print a product of zero. This is the single most common error in this question.
The product is gathered in the same loop that reads the values, which saves a pass. The squares need their own loop only because the question asks for the product to be printed first.
Square with arr[i] * arr[i] rather than Math.pow(arr[i], 2) — simpler, faster and it avoids any question of casting.
Note that with twenty values a real product can grow very large; double handles that comfortably, which is why the question specifies the type.
arr[] double[20] - the twenty values entered by the user prod double - running product of all the elements i int - loop variable sc Scanner - object used to read input