Write a java program to find Sum of cubes and squares of elements in an array.

Write a program to get an int array as input and identify even and odd numbers. If the number is odd to get the cube of it if the number even gets square of it. Finally add all cubes and squares together and return it as output.

The return type of the output is an integer which is the sum of cubes and squares of elements in the array.

Assume the maximum size of the array is 20.

Input and Output Format:

Input an integer for the number of elements in the array.

Input consists of the integer array.

The output is an integer sum.

Refer sample output for formatting specifications.

Sample Input 1:

5

2

6

3

4

5

Sample Output 1:

208

Find Sum of cubes and squares of elements in an array in Java.

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int a[] = new int[20];
    int n = sc.nextInt();
    for (int i = 0; i < n; i++) {
      a[i] = sc.nextInt();
    }

    System.out.println(summationPattern(a));
  }

  public static int summationPattern(int[] a) {
    int n1 = 0, n2 = 0;
    for (int i = 0; i < a.length; i++)
      if (a[i] % 2 == 0)
        n1 += (a[i] * a[i]);
      else
        n2 += (a[i] * a[i] * a[i]);
    return n1 + n2;
  }
}

Add a Comment

Your email address will not be published. Required fields are marked *

20 + 9 =