C# Program to find Factorial of a number
In this post today we are going to see two different program in first program we are going to find factorial of a number using for loop and in the other program we are going to find the factorial using do-while loop.And it will be a console application which accept a number from the user and give the factorial of number as output.
Before moving to actually making our factorial console application, let us take look on the two looping statements which we are going to use in our application
1.For Loop (Entry Control Loop)
1 2 3 4 | for(init;condition;increment) { //statements to be executed. } |
Condition is the part which will be checked to enter the for loop.If the condition is satisfied then and only then the statements inside the for loop are executed.Otherwise the statements are skipped.
After the control statements executed the control jump back to increment to update loop control variables.
Check More on Foor Loop:
2.Do-While Loop (Exit Control Loop)
1 2 3 4 5 6 | do { //statements increment } while(Condition) |
Here in do-while loop all the statements inside the loop are executed once and the condition is checked at the end of the loop.
Check More on Do-while Loop:
Now let's move towards making our console application.Select the new console application under Visual C#.You can name it what ever you like, i'm going to name it "Factorial App".
Now there is no need to add any extra name space.You can just start writing program in the main method.First we are going to make program using for loop.
Using For Loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int i=0; int fact = 1; Console.WriteLine("Enter Number"); i = Convert.ToInt16(Console.ReadLine()); do { fact = fact * i; i--; } while (i != 0); } } } |
Using Do-while loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { int i = 0; int fact = 1; Console.WriteLine("Enter Number"); i = Convert.ToInt16(Console.ReadLine()); for (int j = 0; j < i;j++ ) { fact = fact * i; } } } } |
Download options:
Code Download:
1.Using For loop:
2.Using Do-while loop
Comments
Post a Comment