Professional Documents
Culture Documents
Grade: AA / AB / BB / BC / CC / CD /DD
AIM:
a) Write a program to find the GCD of two numbers using recursion.
b) Write a program to find the LCM of two numbers by using a) above.
____________________________________________________________________
Expected OUTCOME of Experiment:
Design modular programs using functions and the use of structure and union (CO4)
___________________________________________________________________
Books/ Journals/ Websites referred:
Problem Definition:
Input: Input:
24,28 24,25
Output: Output:
GCD: 4 GCD: 1
Input: Input:
6,12 6,7
Output: Output:
LCM: 12 LCM: 42
Algorithm:
Q1)
Algorithm in steps:
2. Otherwise, call the GCD function recursively with the second number and the
Q2)
Algorithm in steps:
1. Calculate the GCD of the two numbers using the provided GCD function. Let's
3. If the GCD is 1, return the product of the two numbers as the LCM.
4. If the GCD is greater than 1, calculate the LCM using the formula: lcm(a, b) =
Implementation details:
Q1)
#include <stdio.h>
int hcf(int n1, int n2);
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("GCD is:%d.",hcf(n1, n2));
return 0;
}
int hcf(int n1, int n2) {
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
Q2)
Q2.
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
int main() {
int num1, num2;
printf("Enter two integers: ");
scanf("%d%d", &num1, &num2);
printf("GCD is:%d\n",gcd(num1, num2));
printf("LCM is:%d\n",lcm(num1, num2));
return 0;
}
Output(s):
Conclusion:
From this experiment, I learnt how to calculate the GCD and LCM of two integers
using recursive functions in C. Besides this, I also learnt a lot about programming from
the virtual lab post lab question.
https://cse02-iiith.vlabs.ac.in/exp/functions/simulation.html
Implementation:
Q1)
#include <stdio.h>
#include <conio.h>
int main()
{
int a[1000],i,n,min,max,sum=0;
printf("Enter size of the array : ");
scanf("%d",&n);
printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
min=max=a[0];
for(i=1; i<n; i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("minimum of array is : %d",min);
printf("\nmaximum of array is : %d",max);
for (i = 0; i < n; i++)
{
sum += a[i]; // Add each element to the sum
}
// Display the sum of all elements stored in the array
printf("\nSum of all elements is : %d\n\n", sum);
return 0;
}