Write a program in Java to find the sum and product of all the elements of an integer array of size 20.
Answers
Solution:
The given problem is solved in Java.
import java.util.Arrays;
public class Main{
public static void main(String args[]){
int arr[] = {2,8,8,8,9,1,3,3,2,5,5,1,9,6,8,5,2,2,3,1};
int sum = 0, product = 1;
for(int x: arr){
sum += x;
product *= x;
}
System.out.println("Given Array: " + Arrays.toString(arr));
System.out.println("Sum of elements: " + sum);
System.out.println("Product of elements: " + product);
}
}
Logic:
To calculate the sum and product of elements in array -
(1) Initialise an array of integers.
(2) Initialise sum = 0 and product = 1
(3) Go through array elements using for-each loop
(4) Add the element to sum.
(5) Multiply the element with product variable and store the result.
(6) Display the sum and product after calculation is over.
See attachment for output.
Answer:
Program:-
import java.util.*;
public class Program
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int s=0,p=1;
int a[]=new int[10];
System.out.println("Enter the array elements");
for(int i=0;i<a.length;i++)
{
a[i]=in.nextInt();
s+=a[i];
p*=a[i];
}
System.out.println("Given Array:"+Arrays.toString(a));
System.out.println("The sum of array elements="+s);
System.out.println("The product of array elements="+p);
}
}