In this tutorial you will learn about the Java Program to Find sum of even digits in a number and its application with practical example.
In this tutorial, we will learn to create a Java Program to Find sum of even digits in a number using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming. Basic Java programming.
- If-else statements in Java.
- For loop in Java.
Even number
Odd Number
Odd numbers that are not divisible by 2. and does not give remainder = Zero, when divided by 2, some the odd numbers are end in 1, 3, 5, 7, 9, 11……
Java Program to Find sum of even digits in a number
In this program we will learn to create a program that will find sum of even digits in a number. Firstly we declare required header file and variable and also initiates required values in variable. Next we take value from user at run time and then after we will find the sum of even digits in a number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
// Java implementation of the approach import java.util.*; import java.util.Scanner; class Even_sum{ // Function to reverse the number static int rev(int number) { int rev = 0; while (number != 0) { rev = (rev * 10) + (number % 10); number /= 10; } return rev; } // Function to find the sum of the even digit numbers static void Sum(int number) { number = rev(number); int Even = 0, odd=0, count = 1; while (number != 0) { // finding even number and adding them if (number % 2 == 0) Even += number%10; else odd += number % 10; number /= 10; count++; } System.out.println("Sum of even number in a digit = " + Even); } public static void main(String args[]) { int number; // taking values from user.. Scanner sc=new Scanner(System.in); System.out.println("enter any numbers"); number=sc.nextInt(); Sum(number); } } |
Output
In the above program, we have first declared and initialized a set variables required in the program.
- number= it will hold entered number.
- Even = it will hold sum or even digit.
- rev = for reversing a string.
Here we first declared and initialized set of variables required in the program. Then we will take a value from user.After that we pass the given number to function named Sum().where we going to calculate sum of all even digit in a given number .
Steps for adding even values.
- Take a number from user,.
- Declare a variable Even to store the sum of even value in a number.
- Reverse a Digit to find last digit of the number.
- Now check all the digit is even or not.
- If it even then adds it to Even variable, else go to next step
- Remove last digit of the number.
- Repeat this until the number becomes 0.
- And last print the sum of all even digit in a number.