Write a program to accept a number and check if it is a Mark number or not. A number is said to be Mark when the sum of the squares of each digit is an even number as well as the last digit of the sum and the last digit of the number given is the same. Example: n = 246 sum = 2 x 2 + 4 x 4 + 6 x 6 = 56 56 is an even number as well as last digit is 6 for both sum as well as the number.
Topic: Digit extraction — Mark number
Answer
import java.util.Scanner;
class MarkNumber { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number : "); int n = sc.nextInt();
int num = n, d, sum = 0;
while(num > 0) { d = num % 10; sum = sum + d * d; num = num / 10; }
System.out.println("Sum of squares of digits = " + sum);
if(sum % 2 == 0 && sum % 10 == n % 10) System.out.println(n + " is a Mark number"); else System.out.println(n + " is not a Mark number"); } }
Two conditions must BOTH hold, so they are joined with && in a single if — testing them separately with two ifs is a common way to lose marks.
Condition 1: the sum is even, tested as sum % 2 == 0. Condition 2: the last digit of the sum equals the last digit of the original number, tested as sum % 10 == n % 10. The operator % 10 is the standard way to pull off a last digit.
This is why the original number must be preserved. The extraction loop destroys num, so n is kept untouched and used in the final test and in the printed message. Candidates who loop on n itself find that n has become 0 by the time they need it.
Trace 246: digits come out 6, 4, 2 and sum = 36 + 16 + 4 = 56. 56 is even, and 56 % 10 = 6 matches 246 % 10 = 6, so it is a Mark number — the example checks out.
n int - the number entered by the user (kept unchanged) num int - working copy of n, reduced digit by digit d int - the digit currently extracted sum int - running total of the squares of the digits sc Scanner - object used to read input