Topics Index

Creating Recursive Method

If you need explanation Read this topic

If you need Answer Take test on this topic

Creating Recursive Method
What will be the output of the following program?
public class Recursion {
    public static void main(String[] args) {
        int a = 35;
        int b = 67;
        int st = loop(a, b);
    public static int loop(int b, int a) {
        if (b % 13 == 0) {
            return b + a;
        return loop(b++, a / 2);

A. 43
B. 106
C. Some other output
D. 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.

here ans is option:D
here it is a concept of recursion
excution starts from main() in main function  creating two variables a=35,b=67 and calling function name loop with argumentsa,b=>loop(a,b);
but in function defination loop(int b,int a) here  from function call were passing arguments a,b(actual) and that values are stored in b,a(formal)
in loop(b=35,a=65)
excution starts and there condition if b divides with 13 return b+a but here b was not divides with 13 thats why condition fails it will not enter into if block
and go another statement loop(b++,a/2)=>loop(35,67/2) means same function call itself (recurison) (note b++ means here value was not incremented because it was post incremented it will increment only when function calling completed)
but once again arguments are same values and b not divide by 13 and once agin function call and it will continues upto stack overflow go to infinte loop  it give run time error
option is D

Posted by Goutham Singarapu    2015-03-09 15:46:50

Ans is A.
In the program, the method loop() will be called recursively until the value of b is divided by 13 with remainder 0.. By the time the remainder  of b and 13 gives 0 the value of a becomes 4, so the sum of a and b gives 39 + 4 = 43..

Posted by Gopinath Manchikanti    2015-03-09 16:08:43

This dose is now closed and the winners are Goutham Singarapu,  for 'First Correct Comment', Goutham Singarapu, Sai Ram,  for 'Best Comment' and Sai Ram for the 'Popular Comment'. The 'lucky liker' is PaWan Mulchandani. Please login into Merit Campus using facebook, to claim your recharge. Go to to raise the recharge.

Posted by Merit Campus    2015-03-10 07:08:04

© meritcampus 2019

All Rights Reserved.

Open In App