adding even numbers only java code example
Example 1: Java program to find the sum of all even numbers from 1 to 10
int sum = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
sum = sum + i;
}
}
System.out.println("Sum of all even from 1 to 10 is: " + sum);
Example 2: how to output sum of even numbers in java between two user values
import java.util.*;
public class chapter5no9
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int firstNum;
int secondNum;
int sumEven;
System.out.println("Please enter an integer: ");
firstNum = console.nextInt();
System.out.println("Please enter another integer less than the first integer: ");
secondNum = console.nextInt();
if (firstNum < secondNum)
{
System.out.print("Your second number is greater than the first. So Please re-enter: ");
secondNum = console.nextInt();
}
else
{
System.out.print("Odd Numbers: ");
firstNum++;
while (firstNum > secondNum)
{
if (secondNum % 2 != 0)
{
System.out.print(" " + secondNum);
}
secondNum++;
}
System.out.println();
System.out.print("Sum of Even Numbers: ");
firstNum++;
while (firstNum > secondNum)
{
if (secondNum % 2 != 0)
{
System.out.print(" " + secondNum);
}
secondNum++;
}
}
}
Example 3: java program to add two numbers using method
import java.util.Scanner;
public class AddTwoNumbers
{
public static void main(String[] args)
{
int num1, num2, sum;
Scanner sc = new Scanner(System.in);
System.out.println("First number : ");
num1 = sc.nextInt();
System.out.println("Second number : ");
num2 = sc.nextInt();
sum = addTwo(num1, num2);
System.out.println("Sum : " + sum);
sc.close();
}
public static int addTwo(int a, int b)
{
int sum = a + b;
return sum;
}
}