small factorials -practice, section easy

my code shows timeout error help
#include<stdio.h>
int fact(int n);
int main()
{
int t=0, num,milgaya;
printf(“enter test cases”);
scanf("%d",&t);
while(t!=0)
{printf(“ener number “);
scanf(”%d”,&num);
printf(“of %d “,num);
milgaya = fact(num);
printf(”%d”,milgaya);
t–;
}
return 0;
}
int fact(int n)
{
int i=1,ans=0;
if (n!=1)
while (i!=n)
{
ans = n*i;
}

else
      ans = 1;

return (ans);
}

Please give submission link instead of pasting code.

You are not incrementing the value of “i” in while loop (Cause for timeout due to infinite loop) and ans = n * i erases previous computation, you wont get correct answer.

This should work.

int fac(int n){
    int ans = 1;
    for(int i = 2; i <= n; i++)
        ans *= i;
    return ans;
}
1 Like