Product and Square of Array Program in Java
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.
import java.util.Scanner;
public class ProductOfArray
{
public static void main(String[] args)
{
double ar[] = new double[2];
double product=1.0;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 2; i++)
{
System.out.print("Enter the number ar[" + i + "]:");
ar[i] = sc.nextDouble();
}
System.out.println("------------------------------------");
for (int i = 0; i < 2; i++)
{
product = product * ar[i];
}
System.out.println("Product of array="+product);
System.out.println("------------------------------------");
System.out.println("Square of array:-");
for (int i = 0; i < 2; i++)
{
System.out.println(ar[i]*ar[i]);
}
}
}
Output:
Enter the number ar[0]:1 Enter the number ar[1]:2 Enter the number ar[2]:1 Enter the number ar[3]:2 Enter the number ar[4]:2 Enter the number ar[5]:1 Enter the number ar[6]:2 Enter the number ar[7]:1 Enter the number ar[8]:2 Enter the number ar[9]:2 Enter the number ar[10]:1 Enter the number ar[11]:3 Enter the number ar[12]:5 Enter the number ar[13]:6 Enter the number ar[14]:3 Enter the number ar[15]:1 Enter the number ar[16]:3 Enter the number ar[17]:2 Enter the number ar[18]:4 Enter the number ar[19]:3 ------------------------------------ Product of array=1244160.0 ------------------------------------ Square of array:- 1.0 4.0 1.0 4.0 4.0 1.0 4.0 1.0 4.0 4.0 1.0 9.0 25.0 36.0 9.0 1.0 9.0 4.0 16.0 9.0