C++ program to find gcd of an array. - coderforcoders

Search

Wednesday, 13 March 2019

C++ program to find gcd of an array.

#include<iostream>
using namespace std;
class gcdArray{
public :
int numbers[25],size,gcd;
int i,j,flag,max=0;
public :
void getgcd()
{
for(i=0;i<size;i++)
{
if(numbers[i]==0)
{
cout<<"array can not have zero\n";
return;
   }
  }
for(i=0;i<size;i++)
if(numbers[i]>max)
max=numbers[i];
for(i=1;i<=max;i++)
{
flag=0;
for(j=0;j<size;j++)
{
if((numbers[j]%i)!=0)
{
flag=1;
  }
  }
if(flag==0)
gcd=i;
  }
cout<<"The GCD of array elements is "<<gcd<<endl;
}
};
int main()
{
 int i;
 gcdArray obj1;
 cout<<"Please enter array size\n";
 cin>>obj1.size;
 cout<<"Please enter array elements\n";
 for(i=0;i<obj1.size;i++)
 cin>>obj1.numbers[i];
 obj1.getgcd();
 return 0;
}

Output 1:
Please enter array size
3
Please enter array elements
24 36 48
The gcd of array elements is 12

Output 2:
Please enter array size
3
Please enter array elements
6 9 0
array can not have zero

Output 3:
Please enter array size
5
Please enter array elements
8 10 12 14 1
The gcd of array elements is 1

Output 4:
Please enter array size
1
Please enter array elements
7
The gcd of array elements is 7

No comments:

Post a Comment