/*Sum the odd numbers and the even numbers from 1 to an upperbound*/
public class OddAndEvenSum { // Save as "OddAndEvenSum.java" public static void main(String[] args) { int sumOdd = 0; // for accumulating odd numbers, init to 0 int sumEven = 0; // for accumulating even numbers, init to 0 int upperbound = 10; for (int number = 1; number <= upperbound; number++) { if (number % 2 == 0) { // even sumEven = sumEven + number; } else { // odd sumOdd = sumOdd + number; } } // print the result System.out.println("The sum of odd numbers is " + sumOdd); System.out.println("The sum of even numbers is " + sumEven); System.out.println("The difference is " + (sumOdd - sumEven)); } }
No comments:
Post a Comment