Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- class EvenSum {
- public static void main(String[] args) {
- System.out.println("Enter the number up to which you want to sum:");
- Scanner sc=new Scanner(System.in);
- int topNumber = sc.nextInt();
- int sum = sumOfEvenNumbersUpTo(topNumber);
- System.out.println("The sum of Even numbers up to and including " + topNumber + " is " + sum);
- }
- protected static int sumOfEvenNumbersUpTo(final int topNumber) {
- int sum = 0;
- for (int thisNumber = 1; thisNumber <= topNumber; ++thisNumber) {
- final boolean isAnEvenNumber = thisNumber % 2 == 0;
- if (isAnEvenNumber) {
- sum = sum + thisNumber;
- }
- }
- return sum;
- }
- public static int sumOfEvenNumbersUpToB(final int topNumber) {
- if (topNumber > 0) {
- final int evenTopNumber = topNumber - topNumber % 2;
- return (evenTopNumber * evenTopNumber / 2 + evenTopNumber) / 2;
- } else {
- return 0;
- }
- }
- }
Add Comment
Please, Sign In to add comment