- Related Questions & Answers
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- Python Program for cube sum of first n natural numbers
- C Program for the cube sum of first n natural numbers?
- Program for cube sum of first n natural numbers in C++
- Java Program to calculate Sum of squares of first n natural numbers
- Sum of first n natural numbers in C Program
- 8085 program to find the sum of first n natural numbers
- Program to find sum of first n natural numbers in C++
- Sum of sum of first n natural numbers in C++
- C++ Program for Sum of squares of first n natural numbers?
- Sum of squares of first n natural numbers in C Program?
- Python Program for Sum of squares of first n natural numbers
- Sum of square-sums of first n natural numbers
- Java program to find the sum of n natural numbers

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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)); } }

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.

Advertisements