Page 162 - DCAP407_DATA_STRUCTURE
P. 162
Unit 9: Recursion
# include <stdio.h>
/* power function definition */
int power (int x, int y)
{
/* Any value that is raised to zero is one */
if (y == 0) return 1;
/* Any value that is raised to 1 returns the same value */
if (y==1) return x;
/* power function calls itself */
return (x * power (x, y – 1));
}
/* Main function */
void main ()
{
/* Initialize integer variables x, y and z */
int x, y, z;
/* Clears the output screen */
clrscr();
/* Print enter the base value */
printf (“\n Enter the base value: “);
/* Accept the base value and store it in x*/
scanf (“%d”, &x);
/* Print enter the power */
printf (“\n Enter the Power: “);
/* Accept the exponent value and store it in y*/
scanf (“%d”, &y);
/* The power function is called with the arguments x and y*/
/* The value returned is assigned to z*/
z = power (x, y);
/* The value of z is printed*/
printf (“\n %d raised to %d is %d”, x, y, z);
/* Waits until a key is pressed */
getch ();
}
Output:
The result of power (5, 1) is 5.
The result of power (5, 2) is 25.
In this example:
1. First the stdio.h header file is included using the include keyword.
2. Then, a function named power is declared which holds integer variables x
and y.
3. In the function power(),
(a) First, using an ‘if’ condition, the value of y is checked. If y is equal to
zero, the value 1 is returned.
(b) Then, using an ‘if’ condition, the value of y is checked. If y is equal to 1,
the value of x is returned.
(c) Finally, power function calls itself to return x to the power (x, y-1).
4. Execution begins at the function main () which does not return any value.
LOVELY PROFESSIONAL UNIVERSITY 155