Jump to content

[PASCAL] Factorial program


CouldnoT
 Share

Recommended Posts

 Factorial Program 

 

 

The while loop has no loop counter, and for that reason we have used the variable i to work as a loop counter. The loop counter value is initialized by the number for which we need to get its factorial, then we decrease it manually in each cycle of the loop. When i reaches 1, the loop will break.

 

Using while loop :

program factorial;

uses wincrt;

var
Fac, Num, i: Integer;

begin
 Write('Please input any number: ');
 Readln(Num);
 Fac:= 1;
 i:= Num;
 while i > 1 do
 begin
 Fac:= Fac * i;
 i:= i - 1;
 end;
if num > 1 then
    writeln('The factorial of the number is: ', Fac)
else
    writeln('The factorial of the number is 1'); 

 Readln;
end. 

 

Using for repeat until loop :

 

program factorial;

uses wincrt;


var 
num, x : Integer;

begin

write('Please input a number: ');
readln(num);

x:= 1;
num:= i;

repeat 
begin
    x:= x * i;
    i:= i - 1
end;
until (i = 1);

if num > 1 then
    writeln('The factorial of the number is: ', x)
else
    writeln('The factorial of the number is 1');  
readkey;
end.

 

Why Does Zero Factorial Equal One?

 

The reason for the definition of 0! = 1 has to do with the formulas that we use for permutations and combinations. This does not explain why zero factorial is one, but it does show why setting 0! = 1 is a good idea.

 

A combination is a grouping of elements of a set without regard for order. For example, consider the set {1, 2, 3}, wherein there is one combination consisting of all three elements. No matter how we arrange these elements, we end up with the same combination. We use the formula for combinations with the combination of three elements taken three at a time and see that 1 = C (3, 3) = 3!/(3! 0!), and if we treat 0! as an unknown quantity and solve algebraically, we see that 3! 0! = 3! and so 0! = 1.

 

There are other reasons why the definition of 0! = 1 is correct, but the reasons above are the most straightforward. The overall idea in mathematics is that when new ideas and definitions are constructed, they remain consistent with other mathematics, and this is exactly what we see in the definition of zero factorial is equal to one.

Edited by CouldnoT
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.