w3resource logo


C Programming Exercises

C Exercises: Find the LCM of two numbers

Secondary Nav

C Recursion : Exercise-13 with Solution

Write a program in C to find the LCM of two numbers using recursion.
Test Data :
Input 1st number for LCM : 4
Input 2nd number for LCM : 6
Expected Output :

The LCM of 4 and 6 :  12 

C Code:

#include <stdio.h>
int lcmCalculate(int a, int b);
 
int main()
{
    int n1, n2, lcmOf;
	printf("\n\n Recursion : Find the LCM of two numbers :\n");
	printf("----------------------------------------------\n");
    printf(" Input 1st number for LCM : ");
    scanf("%d", &n1);
    printf(" Input 2nd number for LCM : ");
    scanf("%d", &n2);
// Ensures that first parameter of lcm must be smaller than 2nd
    if(n1 >  n2)
        lcmOf = lcmCalculate(n2, n1);//call the function lcmCalculate for lcm calculation
    else
        lcmOf = lcmCalculate(n1, n2);//call the function lcmCalculate for lcm calculation
    printf(" The LCM of %d and %d :  %d\n\n", n1, n2, lcmOf);
    return 0;
}
int lcmCalculate(int a, int b)//the value of n1 and n2 is passing through a and b
{
    static int m = 0;
    //Increments m by adding max value to it
    m += b;
//  If found a common multiple then return the m.
    if((m % a == 0) && (m % b == 0))
    {
        return m;
    }
    else
    {
        lcmCalculate(a, b);//calling the function lcmCalculate itself
    }
}

Flowchart :

Flowchart: Find the LCM of two numbers.

-->

C Practice online:

#include <stdio.h>
int lcmCalculate(int a, int b);
 
int main()
{
    int n1, n2, lcmOf;
	printf("\n\n Recursion : Find the LCM of two numbers :\n");
	printf("----------------------------------------------\n");
    printf(" Input 1st number for LCM : ");
    scanf("%d", &n1);
    printf(" Input 2nd number for LCM : ");
    scanf("%d", &n2);
// Ensures that first parameter of lcm must be smaller than 2nd
    if(n1 >  n2)
        lcmOf = lcmCalculate(n2, n1);//call the function lcmCalculate for lcm calculation
    else
        lcmOf = lcmCalculate(n1, n2);//call the function lcmCalculate for lcm calculation
    printf(" The LCM of %d and %d :  %d\n\n", n1, n2, lcmOf);
    return 0;
}
int lcmCalculate(int a, int b)//the value of n1 and n2 is passing through a and b
{
    static int m = 0;
    //Increments m by adding max value to it
    m += b;
//  If found a common multiple then return the m.
    if((m % a == 0) && (m % b == 0))
    {
        return m;
    }
    else
    {
        lcmCalculate(a, b);//calling the function lcmCalculate itself
    }
}

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program