1 / 8

Examples of recursive functions

Examples of recursive functions. Towers of hanoi. We have 3 pegs(1, 2, 3)!the purpose is moving n disks from peg 1 to peg 3 with help of peg 2! At no time, a larger disk should’nt be placed above a smaller disk!:D

yoland
Download Presentation

Examples of recursive functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Examples of recursive functions

  2. Towers of hanoi • We have 3 pegs(1, 2, 3)!the purpose is moving n disks from peg 1 to peg 3 with help of peg 2! • At no time, a larger disk should’nt be placed above a smaller disk!:D • Write a program to solve this problem.Use a recursive function with 4 parameters: • The number of disks to be moved • The peg on which these disks are initially placed • The peg to which this stack of disk is to be moved • The peg to be used as a temp holding area

  3. An example of n = 3 13 12 32 13 21 23 13

  4. Move n-1 disks from peg 1 to peg 2, using peg 3 as a temp holding area. • Move the last disk(the largest) from peg 1 to peg 3. • Move the n-1 disks from peg 2 to peg 3, using peg 1 as a temp holding area. Now the world is over!:D What is the solution?!

  5. #include<iostream> using namespace std; int mystery(int a, int b); int main(){ int a, b; cout<<"Enter 2 numbers!:"<<endl; cin>>a>>b; cout<<"The result is : "<<mystery(a, b)<<endl; return 0; } int mystery(int a, int b){ if(b == 1) return a; return a + mystery(a, b -1); } What does this simple program do?

  6. Can main() be called recursively in your system?! • Take a static variable and increment it! • Then call main() at main()! • What happened? • Think til next session!;) Recursive main! int count; /* count is global */

  7. Please write your names, Std # and emails in a sheet for me.pleas some one accept this task • Feel free ask/suggest anything you want! • Please put “C++ Course::” in the begging of your subjects. • My Emails again: • m.eslami2@gmail.com • eslami@ce.sharif.edu Some notations!

  8. Thanks! Any question?

More Related