The Program in C# Program to find HCF (Highest Common Factor) of two numbers is given below:
using System;
namespace HCF
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family, enter the first number here: ");
int a = int.Parse(Console.ReadLine());
Console.WriteLine("Similarly, enter the second number: ");
int b = int.Parse(Console.ReadLine());
int hcf = 1;
int min = Math.Min(a, b);
for (int i = 2; i <= min; i++)
{
if (a % i == 0 && b % i == 0)
{
hcf = i;
}
}
Console.WriteLine("Okay, The HCF of {0} and {1} is: {2}", a, b, hcf);
Console.ReadLine();
}
}
}
Output:
Hello Codeauri Family, enter the first number here:
5
Similarly, enter the second number:
7
Okay, The HCF of 5 and 7 is: 1
Pro-Tips💡
Here are the step by step execution of above program:
- The program begins by importing the “System” namespace, which provides access to various types and methods that are used in the program.
- The code defines a namespace named “HCF”. The namespace is a way to organize and group related classes.
- Within the namespace, the class named “Program” is defined. The Main method is defined inside this class and serves as the entry point for the program.
- The Main method first asks the user to input the first number, which is stored in the integer variable named “a”.
- The Main method then asks the user to input the second number, which is stored in the integer variable named “b”.
- The Main method then declares an integer variable named “hcf” and initializes it to 1. This variable will store the HCF of the two numbers.
- The Main method then finds the minimum of the two numbers “a” and “b” using the Math.Min method, and stores the result in the integer variable named “min”.
- The Main method then uses a for loop to iterate from 2 to “min”.
- Within the for loop, the Main method checks if the current iteration variable “i” is a factor of both “a” and “b” by checking if both “a % i == 0” and “b % i == 0”.
- If “i” is a factor of both “a” and “b”, the Main method updates the value of “hcf” to “i”.
- The Main method then prints the HCF of the two numbers to the console.
- The Main method finally waits for the user to press the enter key, which allows the console window to remain open until the user closes it.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.