Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Saturday, 19 September 2020

Program to find the HCF of two numbers in C#

In this blog, we will learn How to find the HCF of two numbers in C#. If you are looking for Programs asked in C# Interview, check the below link:


HCF Stands for Highest Common Factor. It is also called the Greatest Common Measure (GCM) and Greatest Common Divisor (GCD). For finding the HCF, we need to find the greatest number which divides two or more numbers.


Check the below C# program, for calculating the HCF of two numbers in C#. I have mentioned comments as well for easy understanding.

int num1, num2, loopCheck, hcf=0;

//Prompt user to add two number for which HCF needs to find

Console.WriteLine("Enter First Number");

num1 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter Second Number");

num2 = Convert.ToInt32(Console.ReadLine());

//set the min value out of the numbers entered by the user

loopCheck = num2 > num1 ? num1 : num2;

//Loop the data from 1 to the loopCheck value

for (int i = 1; i <= loopCheck; i++)

{

    //If Modulus of both number will be Zero than store it in hcf variable

    if (num1 % i == 0 && num2 % i == 0)

    {

        hcf = i;

    }

}

//Show the output to the User

Console.Write("HCF of {0} and {1} is: {2}", num1, num2, hcf);

//Console.ReadLine() t

Output:

I hope this will help you with your interview preparation or exam.
Thanks

0 comments:

Post a Comment

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook

Blog Archive