JeffGrigg

EvenSum

Jun 15th, 2017
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.06 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. class EvenSum {
  4.  
  5.     public static void main(String[] args) {
  6.         System.out.println("Enter the number up to which you want to sum:");
  7.         Scanner sc=new Scanner(System.in);
  8.         int topNumber = sc.nextInt();
  9.         int sum = sumOfEvenNumbersUpTo(topNumber);
  10.         System.out.println("The sum of Even numbers up to and including " + topNumber + " is " + sum);
  11.     }
  12.  
  13.     protected static int sumOfEvenNumbersUpTo(final int topNumber) {
  14.         int sum = 0;
  15.         for (int thisNumber = 1; thisNumber <= topNumber; ++thisNumber) {
  16.             final boolean isAnEvenNumber = thisNumber % 2 == 0;
  17.             if (isAnEvenNumber) {
  18.                 sum = sum + thisNumber;
  19.             }
  20.         }
  21.         return sum;
  22.     }
  23.  
  24.     public static int sumOfEvenNumbersUpToB(final int topNumber) {
  25.         if (topNumber > 0) {
  26.             final int evenTopNumber = topNumber - topNumber % 2;
  27.             return (evenTopNumber * evenTopNumber / 2 + evenTopNumber) / 2;
  28.         } else {
  29.             return 0;
  30.         }
  31.     }
  32. }
Add Comment
Please, Sign In to add comment