The Program in C# Program to Find LCM of any two numbers is given below:
using System;
namespace LCM
{
class Program
{
static void Main(string[] args)
{
int num1, num2, lcm;
Console.WriteLine("Hello Codeauri Family, enter the first number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
lcm = (num1 * num2) / GCD(num1, num2);
Console.WriteLine("Alright,The LCM of " + num1 + " and " + num2 + " is: " + lcm);
Console.ReadLine();
}
static int GCD(int a, int b)
{
if (b == 0)
return a;
else
return GCD(b, a % b);
}
}
}
Output:
Hello Codeauri Family, enter the first number:
2
Enter the second number:
3
Alright,The LCM of 2 and 3 is: 6
Pro-Tips💡
Here are the step by step execution of above program:
using System;
– This line is a using directive, which tells the compiler to use the System
namespace, which includes classes and methods used in the program.
namespace LCM
– The namespace declaration creates a namespace named LCM
to group classes and other code elements in a logical and organized manner.
class Program
– This is a class declaration, creating a class named Program
.
static void Main(string[] args)
– This is the main method of the program, the entry point for the program. When the program is executed, the code inside the Main
method is executed first.
int num1, num2, lcm;
– This line declares three integer variables: num1
, num2
, and lcm
.
Console.WriteLine("Enter the first number: ");
– This line writes a message to the console asking the user to enter the first number.
num1 = Convert.ToInt32(Console.ReadLine());
– This line reads the first number entered by the user, converts it to an integer using the Convert.ToInt32
method, and assigns it to the num1
variable.
Console.WriteLine("Enter the second number: ");
– This line writes a message to the console asking the user to enter the second number.
num2 = Convert.ToInt32(Console.ReadLine());
– This line reads the second number entered by the user, converts it to an integer using the Convert.ToInt32
method, and assigns it to the num2
variable.
lcm = (num1 * num2) / GCD(num1, num2);
– This line calculates the LCM by multiplying num1
and num2
and dividing the result by the GCD (Greatest Common Divisor) of num1
and num2
. The result is assigned to the lcm
variable.
Console.WriteLine("The LCM of " + num1 + " and " + num2 + " is: " + lcm);
– This line writes the result to the console.
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.