Programming training is on the way fromsimple to complex. Having mastered data types and language operators, they pass to cyclic constructs. There are innumerable tasks for cycles: from the output of numbers to the column to the calculation of sums on complex formulas. Nevertheless, the beginning programmers still have a question: "How to calculate the factorial in Pascal?"
You can implement the task in at least three ways. They differ by the operators used.
Before proceeding to the construction of algorithms andwriting programs, should study the theory. In mathematics, the factorial is the product of the integer for which the expression is calculated, by a positive integer less than it.
An example will help to understand the definition. Let it be required to find the factorial for number 3. Solution: 3! = 3 * 2 * 1 = 6.
The action of the exclamation mark, which is placed after the number, is indicated. An important note: the factorial is defined only for positive integers. At the same time, concepts for zero are introduced: 0! = 1.
To read the expression for large values manually is a long occupation. To speed up the process of computing, use computer programs. Next, we discuss ways to find the factorial in Pascal.
The code below shows the version of the program.
The example uses a compound construction with a condition that is written before the body of the loop. Syntax of the record:
while {condition} do {operator_sequence};
The code is executed as follows: the program checks the validity of the expression {condition}, in the case of a positive check, passes to {operator_sequence}.
Returning to the program, you need to pay attention to the following lines:
The following proposes to calculate the factorial in "Pascal" with the help of the operator repeat.
Construction cycle: repeat {operator_sequence} until {condition};
To understand how the program works, consider it line by line:
The latter program also makes it possible to calculate the factorial in "Pascal" and is the most compact in size. Cause - Operator Used for, for which the increase in the counter i is specified in the cycle parameters.
Operator record: for {initial_value} to {final_value} do {operator_sequence}.
The code works as follows (the numbers indicate the lines of the listing):
Even for numbers from the first ten, the factorial has a value greater than the data type allows integer. Therefore, the program in "Pascal" will show an error message. To fix it simply - you need to replace the data type for the result variable by longint or use types to store real values.
</ p>