Menu
Topics Index
...
`

Recursive For Output


If you need explanation Read this topic

If you need Answer Take test on this topic

Recursive For Output
What will be the output of the following program?
class RecursiveFor
{
    public static void main(String[] args)
    {
        int out = 15;
        for (int i = 4; i < 6; i++)
        {
            for (int j = 7; j >= 5; j--)
            {
                if (i == j) continue;
                if (i > j)
                {
                    out += main(i, j);
                }
                else
                {
                    out += main(j, i);
                }
            }
        }
        System.out.println("out = " + out);
    }

    private static int main(int a, int b)
    {
        if (a - b == 0)
        {
            return 2;
        }
        return a + main(a - 1, b);
    }
}

A. out = 78
B. out = 71
C. out = 80
D. Compilation Error
E. Goes into infinite loop
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 is the answer

Posted by Asad Ahmed    2014-12-15 09:05:38


A

Posted by Sathish Govindaraj    2014-12-15 12:13:24


ans a The idea of calling one function from another immediately suggests the possibility of a function calling itself. The function-call mechanism in Java supports this possibility, which is known as recursion. initially out is initialized with 15. nested for loop is used here for perform recursive operation. i=4,i<6,i++ condition true inner for loop j=7,j>=5,j-- condition satisfied. if condition checks i and j values. here i!=j i>j==4>7 failed so else part get executed out+=Main(j,i) func called with i,j arguments.this function return 7+main(6,4) recursion 13+main(5,4) 18+main(4,4) j==i return 2 . totally 20 is returnd.nw out=15+20=35 j=6,j>=5,j-- 4>6 faild else part executed. 6,4 is passed as main arg . 6+main(5,4) 11+main(4,4) it returns 11+2=13 so nw out=35+13=48 j=5,j>=5,j-- ,main func returns 7 so out value becom 55,thnj==i continue,execution skipped,nw outr loop i=5,i<6,i++,condition satisfied innerr for loop.j=7,j>=5,j--,here main called with 7,5.recursive operations follows 7+main(6,5),13+main(5,5),func returns 15,nw out is 55+15=70,nw i=5,j=6 so main (6,5) returns 6+main(5,5)=8,finally out value =78.nw i=6 condition goes out of loop.sop get printd.

Posted by Maheshwari Natarajan    2014-12-15 16:18:21


This dose is now closed and the winners are Maheshwari Natarajan,  for 'First Correct Comment', Maheshwari Natarajan,  for 'Best Comment' and Asad Ahmed for the 'Popular Comment'. The 'lucky liker' is Ankur Verma. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2014-12-16 04:35:02


© meritcampus 2019

All Rights Reserved.

Open In App