![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find out the GCD of two numbers using while loop in C language
Problem
Generate the greatest common divisor for any two numbers using C programming language.
Solution
Let the user enter any two numbers from the console. For those two numbers, let’s find the greatest common divisor.
The GCD of two numbers is the largest number that exactly divides both of them without a remainder.
The logic we use to find the GCD of two numbers is as follows −
while(b!=0) //check for b=0 condition because in a/b ,b should not equal to zero { rem=a % b; a=b; b=rem; } Print a
Program 1
#include<stdio.h> int main(){ int a,b,rem; printf("enter any two numbers:"); scanf("%d%d",&a,&b); while(b!=0) //check for b=0 condition because in a/b ,b should not equal to zero{ rem=a % b; a=b; b=rem; } printf("GCD of two numbers is:%d
",a); return 0; }
Output
enter any two numbers:8 12 GCD of two numbers is:4 Check: 8= 2 * 2 *2 12= 2 * 2 * 3 The Greatest common divisor of two numbers is : 2 * 2 =4
Program 2
In this example, let us find the GCD of two numbers using for loop −
#include <stdio.h> int main(){ int num1, num2, i, GCD; printf("enter two numbers: "); scanf("%d %d", &num1, &num2); for(i=1; i <= num1 && i <= num2; ++i){ if(num1%i==0 && num2%i==0) GCD = i; } printf("GCD of two numbers is:%d", GCD); return 0; }
Output
enter two numbers: 24 48 GCD of two numbers is:24
Advertisements