Welcome...

Monday, 6 January 2014

C program to find whether a given number is a strong number or not

A strong number is a number whose sum of factorials of the individual numbers is equal to the number itself. For example, consider the number 145. In this number 1! + 4! + 5! is equal to the number 145 itself. So, 145 is an example for strong number.

/*Program to find whether a given number is strong number or not*/
#include<stdio.h>
#include<conio.h>
main()
{
    int num,tnum,sum;
    clrscr();
    printf("Enter a positive integer:");
    scanf("%d",&num);
    tnum = num;
    sum = 0;
    while(num!=0)
    {
        sum += fact(num%10);
        num = num/10;
    }
    if(sum==tnum)
    {
        printf("Given number is a strong number");
    }
    else
    {
        printf("Given number is not a strong number");
    }
    getch();
}
/*Logic to calculate the factorial of individual numbers*/
int fact(int n)
{
    int f;
    if(n==1)
    f=1;
    else
    f = n*fact(n-1);
    return f;
}


Sample input and output:

Enter a positive integer: 145
Given number is a strong number

Sunday, 5 January 2014

C program to print the first n terms of a fibonacci series

/* C program to generate the first n terms of the Fibonacci sequence */
#include<stdio.h>
#include<conio.h>
main()
{
    int n, count;
    int a = 0,b = 1,temp = 0;
    clrscr();
    printf("Enter the number of terms: ");
    scanf("%d",&n);
    if(n == 1)
    {
        printf("%d",0);
    }
    else if(n == 2)
    {
        printf("%d %d ",0,1);
    }
    else
    {
        printf("%d %d ",a,b);
        /*Logic to generate terms in a fibonacci series*/
        for(count = 2; count < n; count++)
        {
            temp = a+b;
            a = b;
            b = temp;
            printf("%d ",b);
        }
    }
    getch();
}


Sample input and output:

Enter the number of terms: 10
0 1 1 2 3 5 8 13 21 34

C program to print perfect numbers in the range 1 - user defined number

A perfect number is a positive integer which is equal to the sum of its divisors except the number itself. Examples of perfect numbers are: 6 and 28.

Below is a C program which allows a user to enter a number as input and print all the perfect numbers in the range 1 to the given number:

/*Program to print perfect numbers in the range 1 - user defined number*/
#include<stdio.h>
#include<conio.h>
main()
{
    int i,j,num,sum;
    clrscr();
    printf("Enter a number:");
    scanf("%d",&num);
    printf("\nPerfect numbers in the range 1 - %d are:\n",num);
    for(i=1;i<=num;i++)
    {
        sum = 0;
        /*Logic to check whether a number is perfect number or not*/
        for(j=1;j<i;j++)
        {
            if(i%j==0)
            {
                sum = sum + j;
            }
        }
        if(sum==i)
        {
            printf("%d\t",i);
        }
    }
    getch();
}


Sample input and output:

Enter a number: 100
Perfect numbers in the range 1 - 100 are:
6          28