Subscribe

RSS Feed (xml)

Monday, October 26, 2009

Write a C program to find gcd of each of the two consecutive elements of an array. write a function GCD(a,b) that would take two consecutive elements of the array as arguments and return the GCD.

#include(stdio.h) // Note place '<' & '>' in place of '(' & ')'
int gcd(int,int);
void main()
{
  int a[10],n,i,b[10];
  int x,y;
  clrscr();
  printf("Enter the size of the array:");
  scanf("%d",&n);
  printf("\nEnter the array elements:");
  for(i=0; i< n ;i++)
    scanf("%d",&a[i]);
 for(i=0; i< n-1 ;i++)
  {
     x=a[i];
     y=a[i+1];
     b[i]=gcd(x,y);
    printf("\nG.C.D of %d and %d is : %d",x,y,b[i]);
  }
getch();
}
int gcd(int a,int b)
{
  int rem;
  for(;;)
  {
    rem=a%b;
    if(rem==0)
       break;
    a=b;
    b=rem;
  }
 return b;
}

1 comment:

  1. Hi Sriram,

    Once see the below program for GCD.....

    I think you like it....

    #include

    main(){
    int first, second;
    printf("Enter two numbers: ");
    scanf("%d%d",&first,&second);
    while(second > 0){
    if(first > second)
    first = first - second;
    else
    second = second - first;
    }
    printf("GCD: %d",first);
    getch();
    }

    ReplyDelete