Write a program to array elements to print sum of Cubic Values


This is a Java program that prompts the user to enter an array of integers, and then calculates the sum of the cubes of all elements in the array. Here is a step-by-step explanation of how the program works:

  • The program starts by importing the java.util.Scanner class, which is used to read user input from the console.
  • The Array_Sum_Cubic class is defined, which contains the main method that will be executed when the program runs.
  • Inside the main method, a Scanner object is created to read user input.
  • The user is prompted to enter the array limit, which is the maximum number of elements that the array can hold. The user input is stored in the l variable.
  • An integer array a of size l is created.
  • A for loop is used to prompt the user to enter each element of the array. The loop iterates l times, and for each iteration, the user is prompted to enter an integer value, which is then stored in the corresponding index of the array a.
  • Another for loop is used to iterate through all the elements of the array a. For each element c, the loop calculates its cube (i.e., c*c*c) and adds the result to the sum variable.
  • Finally, the program prints out the sum of the cubes of all elements in the array.

Source Code

import java.util.Scanner;
class Array_Sum_Cubic
{
	public static void main(String[] args)
	{   
		Scanner input =new Scanner(System.in);
		System.out.print("Enter the Array Limit :");
		int l =input.nextInt();
		int [] a =new int[l];
		int sum = 0;
		for(int i=0;i<l;i++)
		{
			System.out.printf("Element of a[%d] :",i);
			a[i]=input.nextInt();
		}
		for(int c:a)
		{
			sum = sum + (c*c*c);
		}
		System.out.println("Sum of Cubic Array Elements : "+sum);
    }
}
 

Output

Enter the Array Limit :5
Element of a[0] :1
Element of a[1] :2
Element of a[2] :3
Element of a[3] :4
Element of a[4] :5
Sum of Cubic Array Elements : 225

Example Programs