Problem:
Write a short Java method that takes an integer n and returns the sum of the
squares of all positive integers less than or equal to n.
Solution:
package com.basics;
import java.util.Scanner;
public class SumOfSquares {
static int number;
public static void main(String[] args) {
SumOfSquares findSum = new SumOfSquares();
findSum.getTheNumber();
System.out.println("the sum of the squares of all positive integers less than or equal to n is: " + findSum.findSum(number));
}
public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the number");
number = scanner.nextInt();
scanner.close();
}
public int findSum(int number){
int sum = 0;
for (int i = 1; i <= number; i++) {
sum = sum + (i * i);
}
return sum;
}
}
Output:
enter the number
4
the sum of the squares of all positive integers less than or equal to n is: 30
Write a short Java method that takes an integer n and returns the sum of the
squares of all positive integers less than or equal to n.
Solution:
package com.basics;
import java.util.Scanner;
public class SumOfSquares {
static int number;
public static void main(String[] args) {
SumOfSquares findSum = new SumOfSquares();
findSum.getTheNumber();
System.out.println("the sum of the squares of all positive integers less than or equal to n is: " + findSum.findSum(number));
}
public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the number");
number = scanner.nextInt();
scanner.close();
}
public int findSum(int number){
int sum = 0;
for (int i = 1; i <= number; i++) {
sum = sum + (i * i);
}
return sum;
}
}
Output:
enter the number
4
the sum of the squares of all positive integers less than or equal to n is: 30
No comments:
Post a Comment