/* with using of mathematical formulae*/
import java.util.*;
class NSquare {
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+1)*(2*n+1)/6;
System.out.println("sum of natural n^2: "+S);
}}
OUTPUT:
enter number
10
sum of natural n^2: 385
/* with java logic and using for loop*/
import java.util.*;
class NSquare {
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+1)*(2*n+1)/6;
System.out.println("sum of natural n^2: "+S);
}}
OUTPUT:
enter number
10
sum of natural n^2: 385
/* with java logic and using for loop*/
import java.util.*;
class NSquare {
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);
}
}
System.out.println(sum);
}}
OUTPUT:
enter number
10
sum of natural n^2: 385
10
sum of natural n^2: 385
No comments:
Post a Comment