C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

LCM using function

LCM (Least Common Multiple) The program given is an Iterative Approach (loop-based, without recursion) using a User-Defined Function.

C Program: LCM using function (Iterative Method)

C

#include <stdio.h>

 

// Function declaration

int findLCM(int a, int b);

 

int main() {

    int num1, num2, result;

 

    // Input two positive integers

    printf("Enter two positive integers: ");

    scanf("%d %d", &num1, &num2);

 

    // Validate input

    if (num1 <= 0 || num2 <= 0) {

        printf("Please enter positive integers only.\n");

        return 0;

    }

 

    // Function call

    result = findLCM(num1, num2);

 

    // Display result

    printf("LCM of %d and %d is %d\n", num1, num2, result);

 

    return 0;

}

 

// Function definition

int findLCM(int a, int b) {

    int lcm;

 

    // Start from the greater number

    lcm = (a > b) ? a : b;

 

    // Loop until LCM is found

    while (1) {

        if (lcm % a == 0 && lcm % b == 0)

            return lcm;   // Return when both divide evenly

        lcm++;

    }

}

Output

 
OUTPUT 1 :
Enter two positive integers: 12 18
LCM of 12 and 18 is 36

OUTPUT 2 :
Enter two positive integers: 5 7
LCM of 5 and 7 is 35

Explanation

  1. Function findLCM(int a, int b)
    • Starts from the greater number.
    • Checks divisibility for both numbers.
    • Returns the smallest number that satisfies both conditions.
  2. Why Use a Function?
    • Improves modularity and code reuse.
    • Keeps main() cleaner and easier to read.
  3. Logic Recap
    • LCM is the smallest common multiple of two numbers.
    • Example:

                     LCM(12, 18)

                     → 36 (since 36 % 12 == 0 and 36 % 18 == 0)