GCD of Two Numbers in C 4 Ways Explained with Examples

The GCD (Greatest Common Divisor) of two numbers is the largest number that divides both of them without leaving a remainder. For example, the GCD of 12 and 18 is 6. In C, there are multiple ways to find GCD using a for loopwhile looprecursion, and the Euclidean algorithm. Let's go through each one.

What Is GCD?

GCD is also known as HCF (Highest Common Factor). It is the greatest number that exactly divides two or more numbers.

  • GCD of 12 and 8 is 4
  • GCD of 100 and 75 is 25
  • If one number is 0, the GCD is the other number
  • To check GCD of two numbers first we need to read input from user. i.e ask user to enter two numbers
  • Store those two numbers in two integer variables
  • Check if number is factor of given two numbers by iterating in for loop.

gcd of two numbers in c


  1. #include <stdio.h>
  2. // program to check gcd of two numbers in c 
  3. // write a c program to find gcd of two integers
  4. // www.instanceofjava.com
  5. int main()
  6. {
  7.     int number1, number2, i, gcd;
  8.     // read input from user
  9.     printf(" please enter any two numbers: ");
  10.     scanf("%d %d", &number1, &number2);

  11.     for(i=1; i <= number1 && i <= number2; ++i)
  12.     {
  13.         // checking  if i is divisible by both numbers / factor of both numbers
  14.         if(number1%i==0 && number2%i==0)
  15.             gcd = i;
  16.     }

  17.     printf("GCD of %d and %d is %d", number1, number2, gcd);

  18.     getch();
  19. }


Output:

gcd of two integers in c




  1. #include <stdio.h>
  2. // Function to compute Greatest Common Divisor using Euclidean Algorithm
  3. int gcd(int a, int b) {
  4.     while (b != 0) {
  5.         int temp = b;
  6.         b = a % b;
  7.         a = temp;
  8.     }
  9.     return a;
  10. }

  11. int main() {
  12.     int num1, num2;

  13.     // enter  two numbers from the user
  14.     printf("Enter two numbers to find their GCD: ");
  15.     scanf("%d %d", &num1, &num2);

  16.     // Ensure numbers are positive
  17.     if (num1 < 0) num1 = -num1;
  18.     if (num2 < 0) num2 = -num2;

  19.     // Calculate and display the GCD
  20.     int result = gcd(num1, num2);
  21.     printf("The GCD of %d and %d is: %d\n", num1, num2, result);

  22.     return 0;
  23. }


Explanation:

  1. Input:
    • The user enters two numbers.
  2. Logic:
    • The findGCD function uses the Euclidean algorithm:
      • Replace aa with bb and bb with a%ba \% b until b=0b = 0.
      • The final value of aa is the GCD.
  3. Output:
    • The program prints the GCD of the two input numbers.




#1. GCD of Two Numbers Using for Loop

We loop from 1 to the smaller of the two numbers. Every time both numbers are divisible by i, we update gcd. The last value stored is the greatest common divisor.

#include <stdio.h>

int main() {
    int n1, n2, i, gcd;

    printf("Enter two integers: ");
    scanf("%d %d", &n1, &n2);

    for (i = 1; i <= n1 && i <= n2; ++i) {
        if (n1 % i == 0 && n2 % i == 0)
            gcd = i;
    }

    printf("GCD of %d and %d is %d", n1, n2, gcd);
    return 0;
}

Output:

Enter two integers: 12 18
GCD of 12 and 18 is 6

#2. GCD of Two Numbers Using while Loop (Subtraction Method)

This approach uses the idea that if we keep subtracting the smaller number from the larger one, eventually both values become equal  and that equal value is the GCD.

#include <stdio.h>

int main() {
    int n1, n2;

    printf("Enter two positive integers: ");
    scanf("%d %d", &n1, &n2);

    while (n1 != n2) {
        if (n1 > n2)
            n1 -= n2;
        else
            n2 -= n1;
    }

    printf("GCD = %d", n1);
    return 0;
}

Output:

Enter two positive integers: 48 18
GCD = 6

#3. GCD Using the Euclidean Algorithm (Most Efficient)

The Euclidean algorithm is the most efficient method. It works by repeatedly replacing the larger number with the remainder of dividing the two numbers until the remainder becomes 0. The last non-zero value is the GCD.

#include <stdio.h>

int main() {
    int n1, n2, temp;

    printf("Enter two integers: ");
    scanf("%d %d", &n1, &n2);

    while (n2 != 0) {
        temp = n2;
        n2 = n1 % n2;
        n1 = temp;
    }

    printf("GCD = %d", n1);
    return 0;
}

Output:

Enter two integers: 56 98
GCD = 14

#4. GCD Using Recursion

We can implement the Euclidean algorithm recursively. The base case is when a becomes 0  at that point we return b.

#include <stdio.h>

int gcd(int a, int b) {
    if (a == 0)
        return b;
    return gcd(b % a, a);
}

int main() {
    int n1, n2;

    printf("Enter two integers: ");
    scanf("%d %d", &n1, &n2);

    printf("GCD of %d and %d is %d", n1, n2, gcd(n1, n2));
    return 0;
}

Output:

Enter two integers: 36 60
GCD of 36 and 60 is 12

Comparison of All Methods

Method Approach Best For
for loop Check every divisor from 1 to min(n1, n2) Beginners
while loop (subtraction) Repeatedly subtract smaller from larger Easy to understand
Euclidean algorithm Modulo-based replacement until remainder is 0 Best performance
Recursion Euclidean algorithm using function calls Clean, concise code

Key Points to Remember

  • GCD is also called HCF (Highest Common Factor)
  • If either number is 0, the GCD is the other number
  • The Euclidean algorithm is the fastest and most widely used method
  • For negative numbers, convert to positive before computing GCD
  • GCD is used in simplifying fractions, cryptography, and LCM calculations

All four approaches give the same result the choice depends on your use case. For interviews and competitive programming, go with the Euclidean algorithm or recursion. For beginners just learning loops, the for loop method is the easiest to follow.

C program to check whether the triangle is right angled triangle

 c program to check whether the triangle is right angled triangle

  • To check right angle triangle or not first we need to check sum of all three angles 
  • If sum of all three angles is 180 then we it should satisfy second condition also
  • Second condition is on of the angle should be 90.
  • if both the conditions are passed then we can say it is a right angle triangle.
  • Now lets write a c program to check triangle is right angle triangle or not.
right angle triangle in c


  1. #include<stdio.h>
  2. // write a c program too check traingle is right angle triasngle or not
  3. //www.instanceofjava.com
  4. int main()
  5. {
  6.      int angle1,angle2,angle3;
  7.      printf("Enter Three Angles of Triangle");
  8.      printf("\n-------------------------------\n");
  9.      printf("Enter Angle1  : ");
  10.      scanf("%d", &angle1);
  11.      printf("\nEnter  Angle2 : ");
  12.      scanf("%d",&angle2);
  13.      printf("\nEnter  Angle2  : ");
  14.      scanf("%d",&angle3);
  15.      printf("--------------------------------\n");
  16.      if(angle1+angle2+angle3==180) 
  17.      {
  18.          
  19.           if(angle1==90 || angle2==90 || angle3==90)
  20.           {
  21.                printf("\nTriangle is Right Angle Triangle\n"); //
  22.           }
  23.          
  24.      }
  25.      else
  26.      {
  27.           printf("\nIts Not a Triangle ");
  28.      }
  29.     getch();
  30. }


Write a c program to check a number is palindrome or not:


check palindrome number in c

  • If reverse number of a number is same then we can say its a palindrome number
  • we already know logic to reverse a number using remainder logic
  • read input from the user and store it in a variable
  • check reverse number of given number 
  • compare original number and reverse number if both are same then we can say it's a palindrome number 
  • C Program to Check Whether a Number is Palindrome or Not


Write a c program to check a number is palindrome or not:

  1. #include <stdio.h>
  2. int main() {
  3.     int n, revnumber = 0, ramindernum, number;
  4.     printf("Enter number: ");
  5.     scanf("%d", &n);
  6.     number = n;

  7.     // reversed integer is stored in reversedN
  8.     while (n != 0) {
  9.         ramindernum = n % 10;
  10.         revnumber = revnumber * 10 + ramindernum;
  11.         n /= 10;
  12.     }

  13.     //  if number  and revnumber are same then its a palindrome
  14.     if (number == revnumber)
  15.         printf("%d is a palindrome.", number);
  16.     else
  17.         printf("%d is not a palindrome.", number);

  18.     getch();
  19. }


Output:

palindrome in c



C program to print pyramid pattern of numbers

 #1: C program to print pyramid pattern of n stars

  1. #include <stdio.h>
  2. //c program to print pyramid pattern of numbers
  3. // www.instanceofjava.com
  4. int main(){
  5.    int number,k,m;

  6.     printf("Number of lines of star pattern  ");
  7.     scanf("%d", &number);

  8.     printf("\n");

  9.     for(  k = 1; k <= number; k++ )
  10.     {
  11.         for( m = 1; m <= k; m++)
  12.         {
  13.             printf("*");
  14.         }
  15.         printf("\n");
  16.     }

  17.    getch();
  18. }

Output:
pattern program in c language



#2: C program to print pyramid pattern of n Numbers

  1. #include <stdio.h>
  2. //c program to print pyramid pattern of numbers
  3. // www.instanceofjava.com
  4. //pyramid pattern in c
  5. //write a c
  6.  program to print following pattern
  7. int main(){
  8.    int number,k,m;

  9.     printf("Number of lines of star pattern  ");
  10.     scanf("%d", &number);

  11.     printf("\n");

  12.     for(  k = 1; k <= number; k++ )
  13.     {
  14.         for( m = 1; m <= k; m++)
  15.         {
  16.            printf("%-5d ", m);
  17.         }
  18.         printf("\n");
  19.     }

  20.    getch();
  21. }

Output:

pyramid pattern in c


prime number program in javascript

  • JavaScript prime number program
  • In this example will learn about how to find the number is prime or not.
  • WHATS IS PRIME NUMBER
  • A number greater than 1 with exactly two factors is called prime number.
  • Number which is divisible by 1 and itself is prime number. If it is divisible by any other number(other than 1 and itself) then it's not a prime number.
    • Consider an example of number 5 ,Which has only two factors  1 and 5. This means 5 is a prime number. Lets take one more example Number 6, which has more than two factors, i.e 1,2,3. This means 6 is not a prime number.
    • The first ten prime numbers are 2,3,5,7,11,13,17,19,23,29.
    • Note: It should be noted that 1 is non-prime number, because in the above defination already mentioned A number greater than 1 with 2 factors called prime number..

  • Here we have simple program to print the prime numbers in java script.
JavaScript program to check a number is prime number or not.

  1. <html>
  2.     <head>
  3. <script>
  4.     // javascript program to check the number is prime or not.
  5.     // prime number program in javascript
  6.     // javascript prime number program
  7.     // take input from the user
  8. const x = parseInt(prompt("Enter a number to check prime or not: "));
  9. let isPrimeNumber=true;

  10. // check if number is equal to 1
  11. if (x  === 1) {
  12.     alert("1 is neither prime nor composite number.");
  13. }

  14. // checking  if  number is greater than one or not

  15. else if (x  > 1) {

  16.     // iterating from 2 to number -1 (leaving 1 and itself )
  17.     for (let i = 2; i < x ; i++) {
  18.         if (x  % i == 0) {
  19.             isPrimeNumber = false;
  20.             break;
  21.         }
  22.     }

  23.     if (isPrimeNumber) {
  24.         alert(`${x } is a prime number`);
  25.     } else {
  26.         alert(`${x } is not a prime number`);
  27.     }
  28. }

  29. // check if number is less than 1
  30. else {
  31.     console.log("The number is not a prime number.");
  32. }
  33. </script>
  34.     </head>
  35.     <body>

  36.     </body>
  37. </html>




Output:
javascript prime number
javascript prime number program


Python range function recursive


Recursion:
  • The process of calling a function by itself is called recursion and the function which calls itself is called recursive function.
  • Recursion is used to solve various mathematical problems by dividing it into smaller problems. This method of solving a problem is called Divide and Conquer. In programming, it is used to divide complex problem into simpler ones and solving them individually.
  • In order to prevent infinite recursive call,we need to define proper exit condition in a recursive function.



  • Python program to show recursive function

    • n=4
    • def  a(n):
    •  if n==0:
    •     return 0
    •  else:
    • print(n)
    • Return a(n-1)


    • Python range for float numbers
    • Limitation of  python’s range() function
    • The main limitation of Python’s range() is it works only with integers. Python range() doesn’t support the float type i.e., we cannot use floating-point or non-integer number in any of its argument.
    • For example,  Let’s see the following source code
    • for num in range(0, 5.5, 0.1):
    •   print (num)
    • If you try to execute above code Python will raise a TypeError: ‘float’ object cannot be interpreted as an integer.


    • Now, Let see how to generate the range for float numbers? There are various ways to do this Let see one by one with the examples.
    • Use numpy’s arange() function to generate the range for float numbers in Python.
    • We can use the numpy module of Python programming language to get the range of floating-point numbers.

    • NumPy library has various numeric functions and mathematical functions to operate on multi-dimensional arrays and matrices.
    • NumPy has the arange() function to get the range of a floating-point number.
    • arange() function has the same syntax and functionality as python range() function.
    • Additionally, it also supports floating-point numbers in any of its argument.
    • i.e., we can pass float number in the start, stop and step arguments.

    Syntax of numpy’s arange() function: –
    • arange (start, stop, step)
    • Let demonstrate the use with the following example.































    Else statement in python with example program

    Else Statement in Python:


    • The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement.
    • We can use the else statement with if statement to execute a block of code when the condition is false

    if (condition):

        # Executes this block if

        # condition is true

    else:

        # Executes this block if

        # condition is false


    #1: Python program to illustrate If else statement
    1.  i = 2;
    2. if i< 1:
    3.     print ("i is smaller than 1")
    4.     print ("i'm in if Block")
    5. else:
    6.     print ("i is greater than 1")
    7.     print ("i'm in else Block")
    8. print ("i'm not in if and not in else Block")

    Output:
    1. I is greater than 1
    2. I'm in else Block
    3. I'm not in if and not in else Block



    Select Menu