• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

i didnot get output  RSS feed

 
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
 
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.
 
Ranch Hand
Posts: 243
  • 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
 
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
 
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!