• Post Reply Bookmark Topic Watch Topic
  • New Topic

i didnot get output  RSS feed

 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class test {

public static void main(String args[]) {

test test1 = new test();

System.out.println(test1.xyz(100));

}

public int xyz(int num) {

if(num == 1) return 1;

else return(xyz(num-1) + num);

}

}

The output of this is 5050.
i didnt get how to solve .
I found this in mock paper of javaprepare.com
 
Ronnie Ho
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's from 100 + 99 + 98 + 97 + .... + 1
Think about it, I think you'll get it.
 
anand phulwani
Ranch Hand
Posts: 242
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nice question tried myself,tried dry run out of it by passing 10 instead of 100,this cleared my doubts

Thanks,
For a wonderful question,
Anand
 
Kayalvizhi Umashankar
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Easy way to compute that would be by applying the formula (n)(n+1)/2.

Kayal
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karu, xyz is called a recursive method. You will see that xyz calls itself with a reduced value for its parameter. Eventually xyz gets called with parameter 1 and simply returns the value 1 (no call to itself). In Java or C++ you will not see recursive programming very often, but it can be done as this example shows.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!