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
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
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++;
}
}
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
#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.
#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;
}
#include <stdio.h>
int main()
{
int num, result;
#include <stdio.h>
int HailstoneNumbers (int N)
{
int c;
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