Contact Learn C
Copy

Program 33:To Print GCD and LCM

Program 33:
 
#include<stdio.h>
main()
{
int num1,num2,temp1,temp2,gcd,lcm,x;
printf("Enter number 1\n");
scanf("%d",&num1);
printf("Enter number 2\n");
scanf("%d",&num2);

temp1=num1;
temp2=num2;

while(temp2!=0)
{
x=temp2;
temp2=temp1%temp2;
temp1=x;
}

gcd=temp1;
lcm=(num1*num2)/gcd;
printf("gcd is %d\n",gcd);
printf("Lcm is %d\n",lcm);

}
Explanation:
  1. The program starts with initializing
    • gcd → For storing the gcd result
    • num1,num2 → For storing two integers
    • lcm→ For storing the lcm.
    • temp1,temp2 → For storing num1 and num2 values temporarily
  2. printf("Enter number 1\n");
    scanf("%d",&num1);
    printf("Enter number 2\n");
    scanf("%d",&num2);
    
    For taking 2 integers to find gcd and lcm
  3. temp1=num1;
    temp2=num2;
    
    now temp variables sore values of 2 integers
  4. while(temp2!=0)
    {
    x=temp2;
    temp2=temp1%temp2;
    temp1=x;
    }
    • Let us assume num1=11,num2=13,then temp1=11,temp2=13
    • Let us start iteration:
      • step1: as temp2 is not zero → true so loop continues iteration
        • x=temp2→ x=13
        • temp2=11%13 →temp2=11
        • temp1=13
        • The final values are temp1=13,temp2=11
      • step2: as temp2!=0 → true so loop continues iteration
        • x=temp2→ x=11
        • temp2=13%11 →temp2=2
        • temp1=11
        • The final values are temp1=11,temp2=2
      • step3: as temp2!=0 → true so loop continues iteration
        • x=temp2→ x=2
        • temp2=11%2 →temp2=1
        • temp1=2
        • The final values are temp1=2,temp2=1
      • step4: as temp2!=0 → true so loop continues iteration
        • x=temp2→ x=1
        • temp2=2%1 →temp2=0
        • temp1=1
        • The final values are temp1=1,temp2=0
      • step4: as temp2!=0 → false so loop terminates
  5. gcd=temp1;
    lcm=(num1*num2)/gcd;
    printf("gcd is %d\n",gcd);
    printf("Lcm is %d\n",lcm);
    gcd=temp1 → gcd=1 from above. lcm=(11*13)/1 → lcm=143.
  6. Then the loop prints gcd and lcm.
Output:

Print GCD and LCM
Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide