WEEK4
WEEK4
LABORATORY MANUAL
Week 4
1. Write a C program that takes an integer as input, counts the number of digits in it
and displays the same, and then checks if the (sum of its digits + the product of its
digits) is equal to the original number. If the conditions are met, print the number;
otherwise, display zero.
Test example : 39: 3+9 + 3*9 = 12 + 27 = 39. Meets condition
--------------
CODE:
#include<stdio.h>
int main()
{
int c,check,a,f,n,sum=0,prod=1;
printf("Enter a number: ");
scanf("%d", &a);
f=a;
while(a>0)
{
n=a%10;
sum=sum+n;
prod=prod*n;
a=a/10;
c+=1;
}
printf("The number of digits in given number is %d \n", c);
check=sum+prod;
if(check==f)
printf("%d", check);
else
printf("0");
return 0;
}
--------------
Output :
Enter a number: 56578
The number of digits in given number is 5
0
--------------
--------------
Output :
Enter a number: 512
It is a Dudeney number
--------------
3. Write a C program to find the sum of all prime numbers in a given range.
Explanation
Prime numbers between 10 and 30: 11, 13, 17, 19, 23, 29
Their sum: 11 + 13 + 17 + 19 + 23 + 29 = 112
--------------
CODE:
#include<stdio.h>
int main()
{
int c=0,a,b,sum=0,i,j;
printf("Enter the lower range: ");
scanf("%d", &a);
printf("Enter the upper range: ");
scanf("%d", &b);
for(i=a;i<=b;i++)
{
for(j=1;j<=i;j++)
{
if(i%j==0)
c=c+1;
}
if(c==2)
sum=sum+i;
c=0;
}
printf("Sum of prime numbers in given range is %d ", sum);
return 0;
}
--------------
Output :
Enter the lower range: 5
Enter the lower range: 5
Sum of prime numbers in given range is 36
--------------
4. Write a C program to find the closest Fibonacci number to a given number.
Explanation
Suppose if 20 is entered as input
Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...
20 is between 13 and 21.
21 is closer to 20 than 13, so the program returns 21.
--------------
CODE:
#include<stdio.h>
int main()
{
int d,c,a=0,b=1;
printf("Enter a number: ");
scanf("%d", &d);
while(b<=d)
{
c=a+b;
if(c<d)
{
a=b;
b=c;
}
if(c>=d)
{
int x=c-d;
int y=d-b;
if(x > y)
{
printf("The closest number to %d is %d",d,b);
break;
}
else
{
printf("The closest number to %d is %d",d,c);
break;
}
}
}
return 0;
}
--------------
Output :
Enter a number: 9
The closest number to 9 is 8
--------------