Problem:
Write a short Java method that takes an integer n and returns the sum of all
positive integers less than or equal to n.
Solution:
package com.basics;
import java.util.Scanner;
public class FindSum {
static int number;
public static void main(String[] args) {
FindSum findSum = new FindSum();
findSum.getTheNumber();
System.out.println("the sum 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;
}
return sum;
}
}
Output:
enter the number
10
the sum of all positive integers less than or equal to n is: 55
Write a short Java method that takes an integer n and returns the sum of all
positive integers less than or equal to n.
Solution:
package com.basics;
import java.util.Scanner;
public class FindSum {
static int number;
public static void main(String[] args) {
FindSum findSum = new FindSum();
findSum.getTheNumber();
System.out.println("the sum 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;
}
return sum;
}
}
Output:
enter the number
10
the sum of all positive integers less than or equal to n is: 55
No comments:
Post a Comment