/* using for loop*/
import java.util.*;
class SumNQubes {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int sum=0;
System.out.println("enter number");
int n=scan.nextInt();
for(int i=0;i<=n;i++)
{
sum=sum+(i*i*i);
}
System.out.println("sum of "+n+"^3 natural numbers"+sum);
}}
OUTPUT:
enter number
10
sum of 10^3 natural numbers: 3025
/*Using mathematical formulae*/
import java.util.*;
class SumNCubes {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("enter number");
int n=scan.nextInt();
int S= n*n*(n+1)*(n+1)/4;
System.out.println("Sum of Ncubes are:"+S);
}}
OUTPUT:
enter number
10
Sum of Ncubes are:3025
import java.util.*;
class SumNQubes {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int sum=0;
System.out.println("enter number");
int n=scan.nextInt();
for(int i=0;i<=n;i++)
{
sum=sum+(i*i*i);
}
System.out.println("sum of "+n+"^3 natural numbers"+sum);
}}
OUTPUT:
enter number
10
sum of 10^3 natural numbers: 3025
/*Using mathematical formulae*/
import java.util.*;
class SumNCubes {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("enter number");
int n=scan.nextInt();
int S= n*n*(n+1)*(n+1)/4;
System.out.println("Sum of Ncubes are:"+S);
}}
OUTPUT:
enter number
10
Sum of Ncubes are:3025
No comments:
Post a Comment