Friday, November 18, 2011

Greatest Common Divisor (GCD) - Recursive Non Recursive

Write C programs that use both recursive and non-recursive functions - To find the GCD (greatest common divisor) of two given integers.


#include<stdio.h>
#include<conio.h>
#include<math.h>
unsigned int GcdRecursive(unsigned m, unsigned n);
unsigned int GcdNonRecursive(unsigned p,unsigned q);
int main(void)
{
  int a,b,iGcd;
  clrscr();
  printf("Enter the two numbers whose GCD is to be found: ");
  scanf("%d%d",&a,&b);
  printf("GCD of %d and %d Using Recursive Function is %d\n",a,b,GcdRecursive(a,b));
  printf("GCD of %d and %d Using Non-Recursive Function is %d\n",a,b,GcdNonRecursive(a,b));
  getch();
}
/* Recursive Function*/
unsigned int GcdRecursive(unsigned m, unsigned n)
{
 if(n>m)
        return GcdRecursive(n,m);
 if(n==0)
         return m;
 else
     return GcdRecursive(n,m%n);
}
/* Non-Recursive Function*/
unsigned int GcdNonRecursive(unsigned p,unsigned q)
{
 unsigned remainder;
 remainder = p-(p/q*q);
 if(remainder==0)
     return q;
 else
     GcdRecursive(q,remainder);
}

Factorials with Recursive Non Recursive

Write C programs that use both recursive and non-recursive functions - To find the factorial of a given integer.

#include<stdio.h>
#include<conio.h>
unsigned int recr_factorial(int n);
unsigned int iter_factorial(int n);
void main()
{
  int n,i;
  long fact;
  clrscr();
  printf("Enter the number: ");
  scanf("%d",&n);
  if(n==0)
    printf("Factorial of 0 is 1\n");
  else
  {
printf("Factorial of %d Using Recursive Function is %d\n",n,recr_factorial(n));
printf("Factorial of %d Using Non-Recursive Function is %d\n",n,iter_factorial(n));
   }
   getch();
}
/* Recursive Function*/
unsigned int recr_factorial(int n) {
    return n>=1 ? n * recr_factorial(n-1) : 1;
}
/* Non-Recursive Function*/
unsigned int iter_factorial(int n) {
    int accu = 1;
    int i;
    for(i = 1; i <= n; i++) {
    accu *= i;
    }
    return accu;
}

Calculate the Sum


Write a C program to calculate the following Sum:Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!*/
#include <stdio.h>
#include <math.h>
void main()
{
int counter,f_coun;
float sum=0,x,power,fact;
clrscr();
printf("<-----------------------PROGRAM FOR SUM OF EQ. SERIES----------------------->");
printf("\n\n\tEQUATION SERIES : 1- X^2/2! + X^4/4! - X^6/6! + X^8/8! - X^10/10!");
printf("\n\n\n\tENTER VALUE OF X : ");
scanf("%f",&x);
for(counter=0, power=0; power<=10; counter++,power=power+2)
{
fact=1;
//CALC FACTORIAL OF POWER VALUE
for(f_coun=power; f_coun>=1; f_coun--)
        fact *= f_coun;
//EQ. FOR SUM SERIES
sum=sum+(pow(-1,counter)*(pow(x,power)/fact));
}
printf("SUM : %f",sum);
getch();
}