Page 43 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 43

Fundamentals of Data Structures




                    Notes          value of argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value
                                   of n is returned which is the sum numbers from 5 to 1.
                                   For better visualization of recursion in this example:
                                     sum(5)
                                     =5+sum(4)
                                     =5+4+sum(3)
                                     =5+4+3+sum(2)
                                     =5+4+3+2+sum(1)
                                     =5+4+3+2+1+sum(0)
                                     =5+4+3+2+1+0
                                     =5+4+3+2+1
                                     =5+4+3+3
                                     =5+4+6
                                     =5+10
                                     =15
                                   In this example when, n is equal to 0, there is no recursive call and recursion ends.


                                          Example 3: C program to reverse a sentence using recursion
                                   This program takes a sentence from user and reverses that sentence using recursion. This program
                                   does not use string to reverse the sentence or store the sentence.
                                   Code to reverse a sentence using recursion is given below.
                                   /* Example to reverse a sentence entered by user without using strings.
                                   */
                                   #include <stdio.h>
                                   void Reverse();
                                   int main()
                                   {
                                    printf(“Enter a sentence: “);
                                    Reverse();
                                    return 0;
                                   }
                                   void Reverse()
                                   {
                                    char c;
                                    scanf(“%c”,&c);
                                    if( c != ‘\n’)
                                    {
                                    Reverse();
                                    printf(“%c”,c);
                                    }
                                   }





          36                                LOVELY PROFESSIONAL UNIVERSITY
   38   39   40   41   42   43   44   45   46   47   48