Page 44 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 44

Unit 3: Recursion




          The output is given as below:                                                         Notes
          Enter a sentence: margorp emosewa
          awesome program
          This program prints “Enter a sentence: “ then, Reverse() function is called. This function stores
          the first letter entered by user and stores in variable c. If that variable is other than ‘\n’ [ enter
          character] then, again Reverse()function is called. Don’t assume this Reverse() function and the
          Reverse() function before is same although they both have same name. Also, the variables are
          also different, i.e., c variable in both functions are also different. Then, the second character is
          stored in variable c of second Reverse function. This process goes on until user enters ‘\n’. When,
          user enters ‘\n’, the last function Reverse() function returns to second last Reverse() function and
          prints the last character. Second last Reverse() function returns to the third last Reverse() function
          and prints second last character. This process goes on and the final output will be the reversed
          sentence.


                 Example 4: C Program to find HCF using recursion
          This program takes two positive integers from user and calculates HCF or GCD using recursion.
          Code to calculate H.C.F using recursion is given below:
          /* Example to calculate GCD or HCF using recursive function. */
          #include <stdio.h>
          int hcf(int n1, int n2);
          int main()
          {
           int n1, n2;
           printf(“Enter two positive integers: “);
           scanf(“%d%d”, &n1, &n2);
           printf(“H.C.F of %d and %d = %d”, n1, n2, hcf(n1,n2));
           return 0;
          }
          int hcf(int n1, int n2)
          {
           if (n2!=0)
           return hcf(n2, n1%n2);
           else
           return n1;
          }
          The output is given as below:
          Enter two positive integers: 366
          60

          H.C.F of 366 and 60 = 6




              Task  Illustrate the prime number program in c using recursion.





                                           LOVELY PROFESSIONAL UNIVERSITY                                   37
   39   40   41   42   43   44   45   46   47   48   49