You are here: Home / Topics / Sum of Even and Odd using For Loop in Java

Sum of Even and Odd using For Loop in Java

Filed under: Java on 2023-08-18 06:37:55

This program will print sum of Even numbers and odd numbers separately.

// sum of even odd using while loop

class OddEvenSum {

   public static void main(String[] args) {

       int i;
       int sum = 0;
       int sum1 = 0;
       for (i = 0; i <= 10; i++) {
           if (i % 2 == 0) {
               sum = sum + i;
           } else {
               sum1 = sum1 + i;
           }
       }
       System.out.println("sum of even nos is : " + sum);
       System.out.println("sum of odd nos is : " + sum1);
   }
}


Output:

sum of even nos is : 30
sum of odd nos is : 25

About Author:
Y
Yatendra Sir     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.