Wednesday, 15 April 2015

Need help understanding a recursive function in Xcode


in book "objective-c programming), did exercise wrote program in c (osx - command line) 99 bottles of beer song printed screen. here code:


code:
#include <stdio.h>    void singthesong(int numberofbottles)  {      if (numberofbottles == 0) {          printf("there simple bo more bottles of beer on wall.\n");      } else {          printf("%d bottles of beer on wall. %d bottles of  beer.\n",                 numberofbottles, numberofbottles);          int onefewer = numberofbottles - 1;          printf("take 1 down, pass around, %d bottles of beer on wall.\n",                 onefewer);          singthesong(onefewer); // function calls itself!          printf("put bottle in recycling, %d empty bottles in bin.\n",                 numberofbottles);      }  }    int main (int argc, const char * argv[])  {        singthesong(99);            return 0;  }
now, see how @ line
singthesong(onefewer); // function calls itself!
function starts on @ top, variable "numberofbottles reduced 1 98, , on way 0.
don't how once song gets point bottles off wall, function continues recycling, going 1 way 99. example, first time line printed put bottle in recycling, 1 empty bottles in bin, don't see how gets next line of output there 2 bottles in bin. think has stack, , popping off variable @ top of stack. right?

basically, when @ code, think (incorrectly) counts bottles on wall 99 way 0, print putting 1 bottle in bin, , program end.

understanding how last printf function recursive, , right jut keeps running until variables in stack gone?
 

recursion works this:
call , function, if parameters allow it, function call within, in case if number of beers >0.

function this,
print # of bottles of beer on wall.
remove 1 bottle.
take 1 down...
calls itself, @ point current function "freezes" bottom frame, , last line of code last 1 called. since put onto stack. can think of last line stack of papers.

put bottle in recycling layer them, first 1 being @ bottom last 1 @ top, when done layering, execute. starting top. recursion technique reverse order of something.
 


Forums Macs Mac Programming


  • iPhone
  • Mac OS & System Software
  • iPad
  • Apple Watch
  • Notebooks
  • iTunes
  • Apple ID
  • iCloud
  • Desktop Computers
  • Apple Music
  • Professional Applications
  • iPod
  • iWork
  • Apple TV
  • iLife
  • Wireless

No comments:

Post a Comment