ASSIGNMENT-4
1. Write a program in C to find the sum of the series 1!/1+2!/2+3!/3+4!/4+5!/5 using the
function
#include <stdio.h>
int sum(int num){
if(num==0||num==1){
num=1;
}
else
return num*sum(num-1);
}
int main()
{
int num;
int ans =0;
printf("enter the number=")
scanf("%d",&num);
for(int i=1;i<=num;i++){
ans=sum(i)/i;
ans+=ans;
}
printf("ans=%d\n",ans);
return 0;
}
2. Write a program in C to convert a decimal number to binary number using the function
#include <stdio.h>
void convert(int n){
int binaryNum[32];
// counter for binary array
int i = 0;
while (n > 0) {
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
printf("%d", binaryNum[j]);
}
int main()
{
int num;
scanf("%d",&num);
convert(num);
return 0;
}
OUTPUT:
67
1000011
3. Write a program in C to print the first 50 natural numbers using recursion.
#include <stdio.h>
int natural(int n){
if(n==1){
n=1;
printf("%d",n);
}
else{
printf("%d\t",n);
return natural(n-1)+1;
}
}
int main()
{
int num;
scanf("%d",&num);
natural(num);
// printf("%d",natural(num));
return 0;
}
OUTPUT:
5
54321
4. Write a program in C to find GCD of two numbers using recursion.
#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("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2));
return 0;
}
int hcf(int n1, int n2) {
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
OUTPUT:
Enter two positive integers: 6 7
G.C.D of 6 and 7 is 1.
5. Write a program in C to calculate the power of any number using recursion.
#include <stdio.h>
int power(int n1, int n2);
int main() {
int base, a, result;
printf("Enter base number: ");
scanf("%d", &base);
printf("Enter power number(positive integer): ");
scanf("%d", &a);
result = power(base, a);
printf("%d^%d = %d", base, a, result);
return 0;
}
int power(int base, int a) {
if (a != 0)
return (base * power(base, a - 1));
else
return 1;
}
6. Write a program in C to find the sum of digits of a number using recursion
#include <stdio.h>
int sum (int a);
int main()
{
int num, result;
printf("Enter the number: ");
scanf("%d", &num);
result = sum(num);
printf("Sum of digits in %d is %d\n", num, result);
return 0;
}
int sum (int num)
{
if (num != 0)
{
return (num % 10 + sum (num / 10));
}
else
{
return 0;
}
}
OUTPUT:
2022
6
7. Write a program in C to find the Hailstone Sequence of a given number upto 1. Hailstone
Sequence:
#include <stdio.h>
int HailstoneNumbers (int N)
{
int c;
printf ("%d\t", N);
if (N == 1 && c == 0)
{
return c;
}
else if (N == 1 && c != 0)
{ c++;
return c;
}
else if (N % 2 == 0)
{
c++;
HailstoneNumbers (N / 2);
}
else if (N % 2 != 0)
{ c++;
HailstoneNumbers (3 * N + 1);
}
}
int main ()
{
int N;
scanf ("%d", &N);
int x;
HailstoneNumbers (N);
return 0;
}
OUTPUT:
5
5 16 8 4 2 1