Join Whatsapp Channel for Ignou latest updates JOIN NOW

Write an algorithm to find the HCF (Highest Common Factor) of the two numbers entered by a user. Transform your algorithm into a C program, support your program with suitable comments

Algorithm to Find the HCF (Highest Common Factor) of Two Numbers

  1. Input: Two numbers, a and b.
  2. Initialize: hcf to 1.
  3. Loop: From i = 1 to the minimum of a and b:
  • If both a and b are divisible by i, set hcf to i.
  1. Output: The value of hcf.

C Program to Find the HCF of Two Numbers

#include <stdio.h>

// Function to find the HCF of two numbers
int findHCF(int a, int b) {
    int hcf = 1; // Initialize HCF to 1

    // Find the minimum of a and b
    int min = (a < b) ? a : b;

    // Loop from 1 to the minimum of a and b
    for (int i = 1; i <= min; i++) {
        // If both a and b are divisible by i, update hcf
        if (a % i == 0 && b % i == 0) {
            hcf = i;
        }
    }

    return hcf; // Return the HCF
}

int main() {
    int num1, num2;

    // Input two numbers from the user
    printf("Enter two numbers: ");
    scanf("%d %d", &num1, &num2);

    // Call the function to find the HCF
    int hcf = findHCF(num1, num2);

    // Print the HCF
    printf("The HCF of %d and %d is: %d\n", num1, num2, hcf);

    return 0;
}

Explanation:

  1. Function Definition (findHCF):
  • This function takes two integers a and b as input.
  • It initializes hcf to 1, which will store the highest common factor.
  • The variable min is set to the minimum of a and b to limit the loop.
  • The for loop iterates from 1 to min. For each i, it checks if both a and b are divisible by i. If so, it updates hcf to i.
  • Finally, the function returns the value of hcf.
  1. Main Function (main):
  • The main function prompts the user to enter two numbers.
  • It reads the input numbers using scanf.
  • It then calls the findHCF function to compute the HCF of the two numbers.
  • Finally, it prints the HCF.

This program uses a simple iterative method to find the HCF by checking all numbers from 1 to the minimum of the two given numbers.

error: Content is protected !!