Computer Science, asked by adityan93, 2 days ago

write a program to calculate and print the sum of even integers and odd integers of first 20 natural number in Java​

Answers

Answered by anindyaadhikari13
4

Solution:

The given problem is solved in Java.

public class Main{

   public static void main(String args[]){

       int i, evensum = 0, oddsum = 0;

       for(i = 1;i <= 20;i++){

           if(i % 2 == 0)

               evensum += i;

           else

               oddsum += i;

       }

       System.out.println("Sum of even numbers: " + evensum);

       System.out.println("Sum of odd numbers: " + oddsum);

   }

}

Explanation:

  • At first, we assume sum of even numbers = 0 and sum of odd numbers = 0
  • Then a loop is created. Variable i is the looping variable. Its initial value is 1. The loop iterates until i <= 20 is true.
  • Inside the loop, we check whether the value of i is even or not. If true, the value is added to evensum. If false, the value is added to oddsum. To check even, we use modulus operator. On dividing the number by 2, if the remainder is 0, the number is even else odd.
  • At last, the sum is displayed using println() method.

Output is attached.

Attachments:
Similar questions