Calculate LCM using recursion in C Language

calculate-lcm-using-recursion-in-c-language

LCM using recursion in C Program Description:

Write a program to calculate the LCM using recursion in C programming language. The program will accept two integers from the user and calculates the LCM. We will use the recursion to calculate the LCM.

Example Input and Output:

Input:

Enter two numbers to calculate LCM: 4 9

Output:

The LCM of 4 and 9 is : 36

Prerequisites:

It is recommended to know the basics of the Functions in C language and Recursion in C language.

LCM using recursion in C Program Explanation:

  1. Take the two numbers from the user and store them in number1 and number2 variables respectively.
  2. Check if any of the number1 or number2 is a negative number using (number1 <= 0 || number2 <= 0) condition. Display an error message if the user provides a negative number.
  3. create a function called computeLCM, The computeLCM function takes two integer variables as input ( min, max) and calculates the LCM using recursion. Here is the explanation of computeLCM function.
    • We should pass the minimum(smaller) value as the first parameter and the maximum(larger) value as the second parameter to the computeLCM function. ( computeLCM(int min, int max))
    • Create a static variable called lcm, The lcm variable holds the calculated LCM value.
    • Update the lcm variable by adding the max value. lcm += max;
    • The base condition for the recursion is lcm%min == 0. So the recursion will continue until the base condition is satisfied.
    • If the base condition is not true, Then make a recursive call to the computeLCM function with min and max.
  4. The minimum and maximum numbers must be supplied as the first and second arguments, respectively to computeLCM function. Use the (number1 > number2) condition to determine whether number1 or number2 is a large value.
  5. Call the computeLCM function from the main() function. – lcm = computeLCM(min, max);. Store the return value in lcm variable.
  6. Display the result on the console.

LCM using recursion in C Program:

Here is the program to calculate the LCM of the two numbers recursively in c programming language.

Program Output:

Compile and Run the program.

Test Case 1: Positive Numbers:

calculate-lcm-using-recursion-in-c-language-program-output

Test Case 2: Negative Numbers:

As we can see from the above output, The program is providing the excepted output.

Recursion Practice Programs:

Functions Practice Programs:

Venkatesh

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

Leave a Reply