Search code examples
cloopsfactorial

My c program is not giving any result.pls help everyone


i have written a program which is not giving proper result.

main()
{
    int i=1,n,s=1;
    printf("enter the value of n");
    scanf("%d",&n);

    while(i<=n) 
    {
         s=s*i;
         i++;
         if (i==n+1)
         {
             break; 
         }
    }
    printf("factorial of n=",s);
}

it is giving the result as shown in the picture below. enter image description here


Solution

  • Write

    printf("factorial of n=%d\n",s);
                           ^^
    

    And this code snippet

         if (i==n+1)
         {
             break; 
         }
    

    is redundant and may be removed.

    You could write the loop simpler. For example

    while ( n > 1 ) s *= n--;
    

    without a need to use one more variable i.