• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Javaprepare Question

 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
<code>
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);
}
}
can somebody explain the output of this Code ..
Thanks
</code>
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
it returns the sum of all numbers between 1 and num (100 in this case) which is 5050. xyz calls itself recursively until the argument provided is 1 in which case the recursion is stopped. Each iteration is called with an argument of num-1, i.e. the first time with 100, the second time with 99, the third time with 98,... the num time with 1.
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ayan
This is a case of recursion. what happens is that the call to xyz the first time num has a value of 100 so it calls xyz again this time with a value of 99 and so on until it gets to 1. At that point the calls to xyz start to return up the stack of calls. the first one (the last one called) returns 1, the next returns 3, the next returns 6, then 10, then 15 and it keeps getting bigger as it moves up the stack until it gets to the first call to xyz. There it adds 1 to the value returned and returns the answer 5050.
hope that helps

------------------
Dave
Sun Certified Programmer for the Java� 2 Platform
 
Arsho, Ayan
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
<code>
Thank you very much Val , Dave !!
</code>
 
This looks like a job for .... legal tender! It says so right in this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic