Search code examples
c++syntax-errordeclarationgreatest-common-divisor

Greatest common divider program not working as expected


I've to write a program in C++ to accept 2 integers and find their G.C.D (Greatest Common Divisor) using a function with a return statement.

Here is what I've written:

int gcd(int x, int y)

#include<iostream.h>
#include<conio.h>

void main()
{
   clrscr();
   int q, x, y, ans;
   cout<<"Enter 2 nos."<<endl;
   cin>>x>>y;
   q = gcd(x,y)
   cout<<"The GCD is: "<<q<<endl;
   getch();
}

int gcd(int x, int y)
{
   int ans;
   int i;
   for(i = 0; i<=x && i<=y; i++)
   {
      if(x%i==0 && y%i==0)
      ans = i;
   }
   return ans;
}

On compiling my code, I'm getting a declaration syntax error.

Could someone please point out in which line my error is and how I should fix it?


Solution

  • int gcd(int x, int y)
    

    Missing a ;


    q = gcd(x,y)
    

    Missing a ;


    #include<iostream.h>
    

    Maybe you meant

    #include <iostream>
    

    if(x%i==0 && y%i==0)
    

    Integer division by zero, in the first iteration when i = 0.


    main must return int.


    Aditional considerations:

    getch() and clrscr() are deprecated functions and conio.h is Windows specific, you should consider not using it.