Home Lifestyle Find Sum of Even Digits in a Given Number in Java Program

Find Sum of Even Digits in a Given Number in Java Program

204
0

Find Sum of Even Digits in a Given Number in Java Program- Java program to find the sum of digits of a given number. Now in this post, we will write a Java program to find the sum of even digits in a given number.

Procedure to find the sum of even digits in a given number,

<img decoding=
  • Take a number
  • Declare a variable evenDigitSum to store the sum value and initialize it with 0
  • Find the last digit of the number
  • Check that the last digit is even or not
  • If it even then adds it to evenDigitSum variable, else go to next step
  • Remove the last digit of the number
  • Repeat 3 to 6 steps until the number becomes 0

Program to find the sum of digits of a given number in java

import java.util.Scanner;

public class SumOfEvenDigitsProgram {

  public static int findEvenDigitSum(int number) {

    // declare variables
    int lastDigit = 0;
    int evenDigitSum = 0;

    // loop to repeat the process
    while(number!=0) {

       // find last digit
       lastDigit = number%10;

       // check last digit even?
       if(lastDigit % 2 == 0) 
           // add it to sum
           evenDigitSum += lastDigit;
       }

       // remove last digit of number
       number = number / 10;
    }

    // return sum value
    return evenDigitSum;
  }

  public static void main(String[] args) {

     // declare variables
     int number = 0;
     int sumOfEvenDigits = 0;

     // create Scanner class object 
     // for reading the values
     Scanner scan =  new Scanner(System.in);

     // read inputs
     System.out.print("Enter an integer number:: ");
     number = scan.nextInt();

     // find sum of digits of number
     sumOfEvenDigits = findEvenDigitSum(number);

     // display result
     System.out.println("The sum of even digits of"+
       " the number "+number+" = "+ sumOfEvenDigits);

     // close Scanner class object
     scan.close();
  }
}

output



Enter an integer number:: 1245
The sum of even digits of the number 1245 = 6

Enter an integer number:: 123456789
The sum of even digits of the number 123456789 = 20

Types of Sorting Algorithms:

Additional Reading

READ MORE

If you found this post useful, don’t forget to share this with your friends, and if you have any query feel free to comment it in the comment section.

Thank you 😊 Keep Learning !

Previous articleSum of N Natural Numbers in Java Language
Next articleSum of Odd Digits of a Number in Java Language

LEAVE A REPLY

Please enter your comment!
Please enter your name here