Extra Practice for Recursion
Recursion is simply the calling of a function by itself. We know that we can call a function from within a function ,That function could the function itself. Recursion is very powerful and very easy to understand but hard to program and debug.
Q? /* CALCULATE FACTORIAL OF AN INTEGER NUMBER USING RECURSIVE FUNCTION */
/* PROGRAM # 42 */ /* Recursion:A function calling itself*/ /* CALCULATE FACTORIAL OF AN INTEGER NUMBER USING RECURSIVE FUNCTION */ #include <stdio.h> int factorial(int num); main( ){ int var, result; printf("Enter a number: "); scanf("%d",&var); result=factorial(var); printf("\n%d! equals %5d", var, result); } /* Recursive function gets an integer number, calls itself until num gets 0 ,returns the result */ int factorial(int num){ if (num == 0) return 1; else return num * factorial(num - 1);
How is the recursion working? We discuss this by a way of an example. In the previous program, if the user inputs 4 as the value of the var then the following would happen: Main program calls factorial(4) factorial(4) calls factorial(3) factorial(3) calls factorial(2) factorial(2) calls factorial(1) factorial(1) calls factorial(0) factorial(0) returns 1 factorial(1) returns 1 1 factorial(2) returns 2 1 1 factorial(3) returns 3 2 1 1 factorial(4) returns 4 3 2 1 1
A recursive function -10 int multiply (int m, int n) { int answer; if (n == 1) answer = m; else answer = m + multiply (m, n-1); return (answer); }
/* PROGRAM #57 */ /* num3=num1*num2-num3 */ #include<stdio.h> void point(int var, int *ptr2, int *ptr3); main( ){ int num1=1, num2=2, num3=3; int *pnum2, *pnum3; printf(“num1, num2 and num3 are: %d %d %d\n”, num1, num2, num3); pnum2=&num2; pnum3=&num3; point(num1, pnum2, pnum3); /* Call the function point and display the result */ } /* Function point, uses pointers to do the calculation*/ void point(int var, int *ptr2, int *ptr3){ int tmp1, tmp2; tmp1=var* (*ptr2); tmp2=tmp1- (*ptr3); *ptr3=tmp2; RUN: num1, num2 and num3 are: 1 2 3 num1, num2 and num3 are: 1 2 -1
GAME?-8 /* Problem: This is just a silly program playing with pointers */ #include <stdio.h> int main (void) { /* a and e are integers */ int a, e; /* b is a pointer to an integer */ int* b; /* c is a pointer to a pointer to an integer */ int** c; /* d is a pointer to a pointer to a pointer to an integer */ int*** d; a = 25; /* a contains the integer 25 */ b = &a; /* b contains the address of a */ c = &b; /* c contains the address of b */ d = &c; /* d contains the address of c */ /* Do you understand that ***d is actually a? */ e = ***d * 2; printf ("%d", e); return (0); }