Computer Concept & Programming In C - Unit III - 13

Q.27. What do you mean by recursion ? Write a recursive function to calculate the factorial of a given integer.                                                     (AKTU. 2010 - 11)
Ans.      The word recursion means to re-occur. A recursive function is a function which calls itself within itself. To define a function recursively, it must have following characteristics.
(i) A function defined recursively should not give an infinite series of recursive calls to itself.
(ii) The function should provide direct solution for very small input size.
Factorial function can be defined recursively as follows
A recursive function to calculate the factorial of a given integer is as follows: 
long factorial (int n)
{
if (n < = 1)
    return 1;
else
   return (n*factorial (n - 1));
}

Q.28. Write a recursive C program to calculate the factorial of a given number by recursion.                                                                 (AKTU. 2009-10)
Ans. A recursive procedure / function is the one which calls itself for its own evaluation.
One of the example is program to print the factorial of a number.
# include <stdio.h>
# include <conio.h>
long fact (int);
void main ( )
{
    int n;
    clrscr ( );
    printf (“\n Enter number”);
    scanf (“ % d”, & n);
    printf (“\n Factorial = % ld”, fact(n));
    getch ( );
}
    long fact (int a)
{
    if (a < = 1)
    return 1;
    else
    return (a * fact (a - 1));
}

Q.29 Differentiate between WHILE....DO and DO.......WHILE loops.       (AKTU. 09-10)
Related Questions -
Q.     Differentiate between while and do-while statements.                 (AKTU. 2011 - 12)
Ans. The basic difference between the while.....do and the do......while loop is that.
The while......do loop is the entry controlled loop which means that if the condition is false at the very beginning i.e. at the outset then the while.....do loop does not execute even for one time where as the do......while loop is the exit controlled loop which executes at least for one time even if the condition is false at the outset.
Consider the example which follows.
 /* DO.......WHILE loop example */
# include <stdio.h>
# include <conio.h>
void main ( )
{
    int i = 0; /* False condition at outset */
    clrscr ( );
    do
{
    printf (“\n in this loop”);
    printf (“ i must not be 0”,);
    printf (“\n But”);
    printf (“ i = % d”, i);
}
    while (i ! = 0);
    getch ( );
}
 /* WHILE.......DO loop example */
# include <stdio.h>
# include <conio.h>
void main ( )
{
    int i = 0;
    clrscr ( );
    while (i ! = 0)
{
    printf (“ inside while.....do loop”);
}
    printf (“\n outside loop”);
    getch ( );
}
In the 2nd example above the statement printf (“ inside while ...do loop”); is not executed since i is 0 at the outset. In the 1st example above the printf statements inside do ......... while loop executes and the messages are printed.