• Breaking News

    Funny Coder

    Funny coder is an open source web for interested programmer. It is a programming environment.It's a way where you can code with fun.

    Friday, April 22, 2016

    Find Factorial program in C language


    Factorial program in C language with error solving

    /*
    Name   : C source program Find Factorial program in C language
    Author : Funny Coder(Maniruzzman Akash)
    It's a free code. You can use it anywhere
    */

    #include <stdio.h>
    int main()
    {
        int num, total;
        int factorial = 1;      
        printf("\nEnter an integer: ");
        scanf("%d",&num);
        if (num < 0){
        printf("\nPlease enter a positive number ..!!\nTry Again..\n");
    }else{
           for(total = 1; total <= num; total++)  
           {
              factorial *= total;            
     /* fac= fac*total */
           }
        printf("\nFactorial = %d\n",factorial);
        }
        return 0;
    }

    Look at the solution of this problem. First if the number is bigger than a problem will be occured. Look at the output:


    And the error now. If I enter a big number like 20 for factorial then look at this :




    So what's the solution :

    /*
    Name   : C source program
    Author : Funny Coder(Maniruzzman Akash)
    It's a free code. You can use it anywhere
    */

    #include <stdio.h>
    int main()
    {
        int num, total;
        unsigned long long int factorial = 1;         
        printf("\nEnter an integer: ");
        scanf("%d",&num);
        if (num < 0){
        printf("\nPlease enter a positive number ..!!\nTry Again..\n");
    }else{
           for(total = 1; total <= num; total++)    
           {
              factorial *= total;              /* fac= fac*total */
           }
        printf("\nFactorial = %lu\n",factorial);
        }
        return 0;
    }
    And Now the output is absolutely right. See:




    Here second code we've just used unsigned and long long for big integer number. Because an integer number range is 32676 or more..







    No comments:

    Post a Comment

    Fashion

    Beauty

    Travel