1. Write a C program to check whether a given number (N) is a perfect number or not?
[Perfect Number - A perfect number is a positive integer number which is equals to the sum of its proper positive divisors. For example 6 is a perfect number because its proper divisors are 1, 2, 3 and it’s sum is equals to 6.]
int main()
{
int n,i=1,sum=0;
printf("Enter a number: ");
scanf("%d",&n);
while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
printf("%d is a perfect number",i);
else
printf("%d is not a perfect number",i);
return 0;
}
Here is Output
Enter a number: 6
6 is a perfect number
Enter a number: 87
87 is not a perfect number
2. Write a C program to count total number of digits of an Integer number (N).
int main()
{
int num,tNum,cnt;
printf("Enter a number: ");
scanf("%d",&num);
cnt=0;
tNum=num;
while(tNum>0){
cnt++;
tNum/=10;
}
printf("Total numbers of digits are: %d in number: %d.",cnt,num);
return 0;
}
Here is the output
Enter a number: 30001
Total numbers of digits are: 5 in number: 30001.
3. Write a C program to check whether the given number(N) can be expressed as Power of Two (2) or not. For example 8 can be expressed as 2^3.
int main()
{
int num;
int tempNum,flag;
printf("Enter an integer number: ");
scanf("%d",&num);
tempNum=num;
flag=0;
/*check power of two*/
while(tempNum!=1)
{
if(tempNum%2!=0){
flag=1;
break;
}
tempNum=tempNum/2;
}
if(flag==0)
printf("%d is a number that is the power of 2.",num);
else
printf("%d is not the power of 2.",num);
return 0;
}
Here is the output
Enter an integer number: 8
8 is a number that is the power of 2.
4. Write a C program to find sum of following series where the value of N is taken as input
1+ 1/2 + 1/3 + 1/4 + 1/5 + .. 1/N
int main()
{
double number, sum = 0, i;
printf("\n Enter the number : ");
scanf("%lf", &number);
for (i = 1; i <= number; i++)
{
sum = sum + (1 / i);
if (i == 1)
printf("\n 1 +");
else if (i == number)
printf(" (1 / %lf)", i);
else
printf(" (1 / %lf) + ", i);
}
printf("\n The sum of the given series is %.2lf", sum);
return 0;
}
Here is the output
Enter the number: 6
1 + (1 / 2.000000) + (1 / 3.000000) + (1 / 4.000000) + (1 / 5.000000) + (1 /
6.000000)
The sum of the given series is 2.45