Define a class to overload the function print as follows: void print() - to print the following format: 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 void print(int n) - To check whether the number is a lead number. A lead number is the one whose sum of even digits is equal to the sum of odd digits. e.g. 3669 odd digits sum = 3 + 9 = 12 even digits sum = 6 + 6 = 12 3669 is a lead number.
Topic: Method overloading — pattern and Lead number
Answer
class PrintOverload { void print() { for(int i = 1; i <= 5; i++) { for(int j = 1; j <= 4; j++) System.out.print(i + " "); System.out.println(); } }
void print(int n) { int num = n, d, esum = 0, osum = 0;
while(num > 0) { d = num % 10; if(d % 2 == 0) esum = esum + d; else osum = osum + d; num = num / 10; }
System.out.println("Sum of even digits = " + esum); System.out.println("Sum of odd digits = " + osum);
if(esum == osum) System.out.println(n + " is a Lead number"); else System.out.println(n + " is not a Lead number"); }
public static void main(String args[]) { PrintOverload ob = new PrintOverload(); ob.print(); ob.print(3669); } }
Two methods named print(), distinguished by the parameter list — one takes nothing, the other an int. That is method overloading.
The pattern: look at what changes and what stays fixed. Every row has FOUR values, and the value printed is the ROW number. So the inner loop is a plain count to 4 and the thing printed is i, not j. Contrast this with patterns where the value changes across the row — reading which variable is printed is the whole skill.
The Lead number: extract digits with the standard %10 and /10 loop, and test each with d % 2 to decide which running total it joins. One pass gathers both sums.
Note the second method uses a working copy num so that n survives for the final message — the loop would otherwise leave n at 0.
Trace 3669: digits come out 9, 6, 6, 3. Odd sum = 9 + 3 = 12, even sum = 6 + 6 = 12, so the sums match and 3669 is a Lead number, exactly as the question states.
i, j int - loop variables for the rows and columns of the pattern n int - the number to be tested (kept unchanged) num int - working copy of n, reduced digit by digit d int - the digit currently extracted esum int - running total of the even digits osum int - running total of the odd digits ob PrintOverload - object used to invoke the methods