Program to Find HCF of Two Numbers in C
HCF :
HCF of two integers is defined as the largest integer by which both integers can exactly divide. It is also known as gcd of two integers.
Working of Program to find HCF :
In the program, we will take a value and use for loop and conditional statements to find the hcf of two integers.
Run
#include<stdio.h> int main() { int n = 10, m = 25, hcf; for(int i=1;i < n && i < m; i++){ if(n%i==0 && m%i==0){ hcf = i; } } printf("The hcf of two numbers is %d", hcf); return 0; }
Output :
The hcf of two numbers is 5
What Happened Above?
In the Above Program, we take two values and use for loop to traverse the different numbers form 1 till given numbers and use if condition to check integers can divide given numbers.
Example :
Let’s solve the same problem but this time we use the recursive method.
Run
#include<stdio.h> int hcf(int n, int m) { if (m != 0) return hcf(m, n % m); else return n; } int main() { // Write C code here int n = 10, m = 25; printf("The hcf of two numbers is %d", hcf(n,m)); return 0; }
Output :
The hcf of two numbers is 5
What Happened Above?
In the above program, we take two values and use recursion function HCF to find hcf of two given integers.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment