Last Updated:

Factorial in Pascal

How do I find the factorial of any given positive number? You'll be able to calculate the factorial of a number using the example I'll give below.

In this example, you will learn how to calculate the factorial of a number by using a for loop. Therefore, this example uses a nested for loop function in pascal. this pascal program generates a factorial.

Recursive

Recursive

Iteratively

 

Iteratively

 

The factorial of the positive number n is given by:

factorial n (n!) = 1*2*3*4....n

Example:

programFactorialOfAnyNumber;
var
i,a,b,j:integer; {initialize variables}
begin
writeln('Enter any number:'); { Display a message for the next action}
readln(j); {accept keyboard input}
fori := 1 tojdo {loop through the store of values in the variable j}
begin
a:=i*a; {incremnet as this is the loop of storing the result in a variable}

for a:=1 to a do { loop result}
begin
b:=a; {save general response to variable b}
end; {end of loop statement}
end; {end of loop statement}

writeln('Factorial ',j,' is = ',b); { Result on screen}
readln(); {Error message}
end. { End of program}

This program takes a positive integer from the user and calculates the factorial using a for loop.