FINDING THE HIGHEST COMMON FACTOR BY USING C LANGUAGE

Kanchana Kariyawasam
2 min readOct 10, 2020

Hello everyone. Today I am going to present, how to use C LANGUAGE to finding the HCF of numbers that you wish to inputs. I would like to present it short and sweet. So, you can find the HCF of any numbers that you want.

In the below, you can see my coding part. You can copy & paste it to your IDE and check whether is my logic correct.

#include<stdio.h>
void main()
{
int size; // size of an array
printf(“Enter number of elements : “);
scanf(“%d”,&size);
int num[size]; // “num” is a name of an array
for(int i=0;i<size;i++)
{
printf(“Enter number %02d : “,i+1);
scanf(“%d”,&num[i]); // Input the values in array elements
}
// Searching a minimum value of an array
int min=num[0];
for(int i=1;i<size;i++)
{
if(num[i]<min)
{
min=num[i];
}
}
// Start the coding part of finding HCF
int x=1,hcf;
for(int j=0;j<=min;j++)
{
int count=0;
for(int i=0;i<size;i++)
{
if((num[i]%x)==0)
{
count++;
}
}
if(count==size)
{
hcf=x;
}
x++;
}
printf(“HCF : %d”,hcf); // print a HCF
}

Logic

  • To find the HCF, we want to find a minimum value. Because of that, I find minimum value in my code.
  • After that, there are some lines of the other logic part. In this case, x is assigned to 1. In the loop, we are searching whether all elements are divided by x without any remainder. If “yes”, then the count is incremented by 1.
  • After that, we are searching whether the count is equaled to the size of the array. If “yes”, then the HCF is equaled to x.
  • Furthermore, we are incrementing the x by 1 in the loop.
  • Likewise, this loop will continue until the “ j ” equals to the array size.
  • Finally, the HCF is equaled to the x that can divide all the array elements without any remainder.

So, I think you can get an idea about my code. If you think this is important, please give me a clap & share it with another person.

--

--

Kanchana Kariyawasam

Former Software Engineer Intern at Geveo-Australasia || Undergraduate of Faculty of Information Technology, University of Moratuwa.