Skip to content

Latest commit

 

History

History
26 lines (20 loc) · 669 Bytes

File metadata and controls

26 lines (20 loc) · 669 Bytes

Sum Squares

WAP to print the sum of the series 1^2+2^2+3^2 up to n terms

Solution

import java.util.Scanner;

public class SumSquares {
    public static int sum (int n) {
        if (n <= 0) return 0;
        else return (n*n) + sum(n-1);
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("/* ===== Sum of squares of n natural numbers ===== */");
        System.out.print("\nEnter the number n: ");
        int n = input.nextInt();
        System.out.println("sum of squares of " + n + " natural numbers = " + sum(n));
    }
}