
A Java program that reads an integer value from the user and displays i) the sum of all even integers between 1 and the input value, both inclusive. ii) The sum of all odd integers between 1 and the input value both inclusive
Example: User enters 7. Sum of even integers = 2+4+6 = 12 Sum of odd integers = 1+3+5+7=16

import java.util.*;
class AddEvenAndOdd {
public static void main(String[] args) throws Exception {
int sumevenNo = 0;
int sumoddNo = 0;
Scanner input=new Scanner(System.in);
System.out.print("Enter value of n: ");
int n=input.nextInt();
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
sumevenNo += i;
} else {
sumoddNo += i;
}
}
System.out.println("Sum of even numbers: "+sumevenNo);
System.out.println("Sum of odd numbers: "+sumoddNo);
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.