How To Find GCD of Two Numbers In C Program

 

1. C Program to Find GCD of Two Numbers Using For loop

In this program, the compiler will ask the user to enter the two numbers that the user wants to find it’s GCD. After the user enters the program start executing and prints the output on the screen.

C

Output:

gcd program in c

Explanation:

1st Iteration: for(i=1;i<=min;i++) i.e for(i=1;1<=4;i++) and if(n1%i==0 && n2%i==0) i.e (4%1==0 && 6%1==0) is TRUE then the value of GCD becomes 1 i.e GCD=1.

2nd Iteration: for(i=2;i<=min;i++) i.e for(i=2;2<=4;i++) and if(n1%i==0 && n2%i==0) i.e (4%2==0 && 6%2==0) is TRUE then the value of GCD becomes 2 i.e GCD=2.

3rd Iteration: for(i=3;i<=min;i++) i.e for(i=3;3<=4;i++) and if(n1%i==0 && n2%i==0) i.e (4%3==0 && 6%3==0) is FALSE then the below statements are not executed.

4th Iteration: for(i=4;i<=min;i++) i.e for(i=4;4<=4;i++) and if(n1%i==0 && n2%i==0) i.e (4%4==0 && 6%4==0) is FALSE then the below statements are not executed.

5th Iteration: as i is incremented so the value of i becomes 5 and the loop is exited because of 5>4. So finally the value of GCD becomes 2.

2. C Program to Find GCD of Two Numbers Using While loop

In this program, we will use while loop instead of for loop. Don’t be afraid of changing loop logic behind the program is same.

C

Output:

gcd program in c

3. GCD of two numbers Using Temporary Variable

In this program, we will use the Temporary Variable to calculate GCD of the entered number by the user.

C

Output:

program of gcd in c

4. GCD of both Positive and Negative Number

In this program when the user enters the negative number then that negative number is first converted into positive then the GCD is printed on the screen.

C

Output:

program of gcd in c

5. Gcd of Two Numbers using Recursion

Recursion is the method in which the function calls itself symmetrically or asymmetrically. Now we will see how GCD program is written Using Recursion.

C

Output:

using recursion

6. GCD program using function

In this program, we will use a function called gcd() and find the gcd of two numbers using the function. Now let us see how the function works.

C

Output:

using function

7. C Program to find GCD of n Numbers Simultaneously

Till now we find GCD using two numbers but in this program, we will ask the user to enter n numbers and their gcd will be printed on the screen after execution.

C

Output:

c program to find gcd of n numbers

in the above program, we entered 6 numbers simultaneously and press 0 to end the numbers. Finally, we get GCD of all numbers i.e 5.

No comments