Java Program to cube sum of first n natural numbers


Following is the Java code to cube sum of first n natural numbers −

Example

 Live Demo

import java.util.*;
import java.lang.*;
public class Demo{
   public static int first_n_nat_no(int val){
      int ini_sum = 0;
      for (int x=1; x<=val; x++)
      ini_sum += x*x*x;
      return ini_sum;
   }
   public static void main(String[] args){
      int val = 7;
      System.out.println("The sum of cube of first 7 natural numbers is ");
      System.out.println(first_n_nat_no(val));
   }
}

Output

The sum of cube of first 7 natural numbers is
784

A class named Demo defines a static function that takes a value as parameter. Here, an initial sum is defined as 0. Next, a ‘for’ loop is run over values 1 to the value passed as parameter. This is the value up to which the cubes of numbers beginning from 1 need to be computed. Next, every element up to the value is multiplied with itself thrice and returned. Next, the main function defines the value up to which the cube of numbers need to be found. It is calculated and displayed on the console.

Updated on: 04-Jul-2020

374 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements