Click here to Skip to main content
15,880,469 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Calculate the Factorial of an Integer in C#

Rate me:
Please Sign up or sign in to vote.
2.25/5 (6 votes)
3 Oct 2011CPOL 17K   5
Use Recursion.int factorial(int n){ if(n<0) return -1; if(n==0 || n==1) return 1; return n * factorial(n-1);}
Use Recursion.
C#
int factorial(int n)
{
 if(n<0)
  return -1;
 if(n==0 || n==1)
  return 1;

 return n * factorial(n-1);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 good Pin
mandar130519-Oct-11 0:25
mandar130519-Oct-11 0:25 
GeneralGuys, please. This is a tail-recursion and it won't be any s... Pin
ckbz18-Oct-11 21:13
ckbz18-Oct-11 21:13 
GeneralReason for my vote of 1 Besides, recursion for the sake of r... Pin
victorbos18-Oct-11 3:23
victorbos18-Oct-11 3:23 
Reason for my vote of 1
Besides, recursion for the sake of recursion is never a good idea
GeneralReason for my vote of 1 The time has long since passed when ... Pin
Chris Maunder4-Oct-11 2:47
cofounderChris Maunder4-Oct-11 2:47 
GeneralA standard and simple solution, my 5. However, the original ... Pin
Ed Nutting3-Oct-11 20:24
Ed Nutting3-Oct-11 20:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.