Tuesday, October 4, 2011

C program to evaluate factorials upto 100 (100!)


Well, this program can be extended to find values of factorial of numbers more than 100. It uses an array of size equal to maximum no. of digits of factorial value(100 in this case). (We can only find factorial of upto 13 with unsigned long, after that we are left with no choice, hence the program solves this problem)

#include<stdio.h>
int fact[160];
main()
{
    int n,carry,i,size;;
    carry=0;
    size=159;
    fact[0]=1;
    scanf("%d",&n);
    while(n>0)
    {
        i=0;
        do
        {
            fact[i]*=n;
            fact[i]+=carry;
            carry=fact[i]/10;
            fact[i]=fact[i]%10;
        }while(i++ != 158);

        n--;
    }

    for(i=159;i>=0;i--)
    {
        if(fact[i]==0)
        size--;
        else
        break;
    }
    for(i=size;i>=0;i--)
    printf("%d",fact[i]);
    printf("\n");


}

Sunday, October 2, 2011

Data Alignment and performance optimization: C source code, concept


/*Check out the following code. This code is an example of data alignment in C. Read out more at http://www.codeguru.com/forum/showthread.php?t=276622  */
#include<stdio.h>

struct stud1
{
    double fee;
    char branch_code;
    float marks;
    int b1;
    int b2;

};

struct stud2
{

    char branch_code;
    double fee;
    float marks;
    int b1;
    int b2;

};

struct stud3
{

    char branch_code;
    float marks;
    int b1;
    int b2;
    double fee;

};
main()
{
    printf("%d %d %d",sizeof(struct stud1),sizeof(struct stud2),sizeof(struct stud3));
}
//Compile it, and check the output. If you are surprised, have a look at http://www.codeguru.com/forum/showthread.php?t=276622