Menu
Topics Index
...
`

Recursion to get sum of the digits


If you need explanation Read this topic

If you need Answer Take test on this topic

Recursion to get sum of the digits
What will be the output of the following program?
public class SumOfDigit {
    public static void main(String args[]) {
        int x = sumOfDigits(1234567);
        int y = sumOfDigits(97842132);
        int z = sumOfDigits(254671524);
        int sum = sumOfDigits(x + y + z);
        System.out.println("Sum Of Digits " + sum);
    }
    public static int sumOfDigits(int number) {
        if (number / 10 == 0)
            return number;
        return number % 10 + sumOfDigits(number / 10);
    }
    public static int sumOfDigitsIterative(int number) {
        int result = 0;
        while (number != 0) {
        result = result + number % 10;
            number = number / 10;
        }
        return result;
    }
}

A. Sum Of Digits 1
B. Sum Of Digits 3
C. Sum Of Digits 9
D. Sum Of Digits 5
E. Some other output
F. Compilation Error or Runtime Error
Topic: Recursive In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

A

Posted by Nick Jokic    2014-07-03 08:32:44


E

Posted by Shiva Kumar    2014-07-03 08:33:09


Ans is E..the value of x,y,z after calling the function sumof digits will be 28,36,36 respectively..then sum value is 100 and 100%10==0 so the function returns number i.e., 100..so output is Sum of Digits 100

Posted by Badam Swathi    2014-07-03 08:35:27


Ans is A. first x value is assigned as 28 ans y and z values are 36 each. sum of x y and z results as 100 so after the modulus operations the result will be 1

Posted by Nikhil Sulibhavi    2014-07-03 08:39:54


E

Posted by Amit Sabat    2014-07-03 09:47:39


E

Posted by Rishav Seksaria    2014-07-03 10:44:18


Answer is A

Posted by Gaikwad Sony    2014-07-03 11:24:50


© meritcampus 2019

All Rights Reserved.

Open In App