1 / 8

CS1201: Programming Language 2

By : Nouf Almunyif. CS1201: Programming Language 2. Recursion. Recursion and Recursive Functions. Main calls another function…..normal A function calls another function2….normal A function calls itself ?! Possible?? YES  A recursive function is one that call itself. General form.

catrin
Download Presentation

CS1201: Programming Language 2

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. By: Nouf Almunyif CS1201: Programming Language 2 Recursion

  2. Recursion and Recursive Functions • Main calls another function…..normal • A function calls another function2….normal • A function calls itself ?! Possible?? • YES A recursive function is one that call itself.

  3. General form void recurse() { recurse(); //Function calls itself }

  4. Finding Factorial 5! = 5*4*3*2*1 5! 5! Final value=120 5!=5*24=120 returned 5*4! 5*4! 4!=4*6=24 returned 4*3! 4*3! 3!=3*2=6 returned 3*2! 3*2! 2!=2*1=2 returned 2*1! 2*1! 1 1 1

  5. Finding Factorial • #incloud <iostream>; • Using nampespace std; • Void main() { • intn,factorial,i; • cout << "Enter a positive integer: "; • cin >> n; • for (i = 1; i <= n; i++) • { if (i == 1) • factorial = 1; • Else • factorial = factorial * i; • } • cout << "The factorial of " << n << " is " << factorial << endl; • }

  6. Finding Factorial Recursively Enter a positive integer : 4 //Recursive factorial Function #include<iostream> Int factorial(intN); Void main() {int num; cout<<“Enter a positive integer:”; cin>>num; cout<<“factorial=“<<factorial(num); } Int factorial( int N) { if ( N <= 1) //the base case return 1; else return N * factorial (N - 1); } Factorial = 24 N=4 Retrun 4 *factorial(3) 6 4*6=24 N=3 Retrun 3 *factorial(2) 2 3*2 =6 N=2 Retrun 2 *factorial(1) 2*1 = 2 1 N=1 Retrun 1

  7. Example printing number counting doun void main() { int input; cout<<"enter positive number "; cin>>input; myMethod(input); } #include <iostream> using namespace std; voidmyMethod( int counter) { if(counter == 0) return; // no value returning just for EXIT the function else { cout<<counter<<endl; myMethod(--counter); return; // no value returning just for EXIT the function } }

  8. Exercise • write a recursion function to printint number counting up: 1,2,3,4,5 …. N. • Test your function and show the out put

More Related