Write a Java program to find the sum of all even numbers between 1 to n. Suppose, if the value of n is 10 then we will calculate the sum of all the even numbers between 1 to 10.

Java Programs

Java Program to Find Factorial of a Number

A even number is a number which is divisible by 2. For example - 2, 4, 6, 8 etc.

i) Take a value of n as input from a user.

ii) Run a loop from 1 to n and check whether a number is divisible by 2. If it's a divisible by 2 then add the value.

20

The sum of all even numbers between 1 to 20 is 110

Program to add two numbers in Java

Java Programs

Java Program to Find Factorial of a Number

**What is Even Number ?**A even number is a number which is divisible by 2. For example - 2, 4, 6, 8 etc.

**Logic to Find the Sum of all even numbers**i) Take a value of n as input from a user.

ii) Run a loop from 1 to n and check whether a number is divisible by 2. If it's a divisible by 2 then add the value.

## Java Program to Find the Sum of All Even Numbers

import java.util.*; public class EvenNumbers { public static void main(String[] args) { int n, sum = 0; System.out.println("Enter a number"); Scanner in = new Scanner(System.in); n = in.nextInt(); //Sum of all even numbers between 1 to n for(int i = 2; i <= n; i++) { /*If number is divisible by 2, *then it's a even number */ if(i % 2 == 0) { sum = sum + i; } } System.out.println("The sum of all even numbers between 1 to " + n + " is " + sum); } }

**Output :****Enter a number**

20

The sum of all even numbers between 1 to 20 is 110

Program to add two numbers in Java

## 0 comments:

## Post a Comment