Sum of Even and Odd number in Java
Sum of Even Number:
In this tutorial, we will discuss how to calculate the sum of even numbers using a java programming language. It is too simple just some line program.
The sum of even numbers in mathematics
Example:
Even numbers 2,4,6,7,8,10.....
The sum of even number 2+4+6+8 = 20.
Now, Sum of even number using java:
Program:
import java.util.*;
public class MyClass {
public static void main(String args[]) {
System.out.println("Enter the Range: ");
Scanner f=new Scanner(System.in);
int x=f.nextInt();
int i,sum=0;
for(i=0;i<=x;i=i+2){
sum=sum+i;
}
System.out.println("Sum of Even number = " + sum);
}
}
Output:
Enter the Range:
8
Sum of Even number = 20
Sum of Odd Number:
After, the sum of the Even numbers, We discuss how to find the sum of the odd numbers using java language.
Also, the sum of odd numbers in mathematics
Example:
Odd numbers 2,4,6,7,8,10.....
The sum of Odd number 1+3+5+7 = 20.
Now, Sum of Odd numbers using java:
Program:
import java.util.*;
public class MyClass {
public static void main(String args[]) {
System.out.println("Enter the Range: ");
Scanner f=new Scanner(System.in);
int x=f.nextInt();
int i,sum=0;
for(i=1;i<=x;i=i+2){
sum=sum+i;
}
System.out.println("Sum of Even number = " + sum);
}
}
Output:
Enter the Range:
7
Sum of Even number = 16
0 Comments