Friday, May 3, 2013

Program to Find HCF of Two Numbers using Recursion

 Program to Find HCF of Two Numbers using Recursion

 The following C program using iteration finds the HCF of two entered integers. The HCF stands for Highest Common Factor.
Here is the source code of the C program to find the HCF of two entered integers. The C program is successfully compiled and run on a turbo cpp.
#include <stdio.h>
int hcf(int, int);
main()
{
int h, i, a, b;
printf("\nEnter values of two numbers: ");
scanf("%d %d", &a, &b);
h = hcf(a, b);
printf("\nHCF of numbers is: %d", h);
getch();
}
int hcf(int a, int b)
{
if (a%b == 0)
return b;
else
return hcf(b, a%b);
}

 what is recursive programming?
Recursive programming is a powerful technique that can greatly simplify some programming tasks. In summary, recursive programming is the situation in which a procedure calls itself, passing in a modified value of the parameter(s) that was passed in to the current iteration of the procedure. Typically, a recursive programming environment contains (at least) two procedures: first, a procedure to set up the initial environment and make the initial call to the recursive procedure, and second, the recursive procedure itself that calls itself one or more times.



Cautions For Recursive Programming
While recursive programming is a powerful technique, you must be careful to structure the code so that it will terminate properly when some condition is met. In the Fact procedure, we ended the recursive calls when N was less than or equal to 1. Your recursive code must have some sort of escape logic that terminates the recursive calls. Without such escape logic, the code would loop continuously until the VBA runtime aborts the processing with an Out Of Stack Space error. Note that you cannot trap an Out Of Stack Space error with conventional error trapping. It is called an untrappable error and will terminate all VBA execution immediately. You cannot recover from an untrappable error.


No comments:

Post a Comment