Lesson summary “Programming branches in Pascal” in computer science


Incomplete and complete options

Only the most elementary algorithms can work without branching. An incomplete option is ideal in the case when some action must be performed only if a condition is met, a complete option when there is an alternative branch of procedures. In Pascal, the conditional operator has the following syntax, consisting of three parts:

  1. “If” (“if”) - after this the condition is written. It is noteworthy that parentheses are not generally used, but they will not affect compilation. If you intend to study C in the future, you should develop the habit of using them.
  2. Immediately after the described condition comes “then” and a block of several commands (from the next line), separated by operator brackets begin and end. These system words can be omitted if only one procedure is called, that is, the operator is not compound.
  3. The fragment missing from the incomplete version is “else” . Completely similar to the previous part.

Operations placed after “then” are relevant for the correct content of “if” (result “True”), after “else” - for incorrect content (“False”).

Content

Programming Branches in Pascal

Branch operator in Pascal

The Pascal language has a branch operator

. Another name for it is the conditional operator. The format of a complete branch statement is as follows:

if
then else
Here if

- “if”,
then
- “then”,
else
- “otherwise”.

Programming full and incomplete branching

Compare the entry for the BID1 algorithm from the previous paragraph with the corresponding program.

alg
BID1
things
A, B, C
start
input A, B
if
A>B
then
C:=A
otherwise
C:=B
sq
output C
end
Program
BID1;
var
A, B, C: real;
begin
readln(A, B);
if
A>B
then
C:=A
else
C:=B;
writeln(C) end.

Very similar to translation from Russian into English. Please note the following difference: the program does not have a special function word to indicate the end of a branch. Here, the end of a branch statement is indicated by a semicolon. (Of course, leaving an empty line in the program is not at all necessary. This is done here only for the sake of clarity.)

A simple form of a Boolean expression is the relational operator

. As in AY, all types of relations are allowed in Pascal (their signs are indicated below):

> (more);= (equal); (not equal).

Now let’s program the BID2 algorithm in Pascal, which uses incomplete branching.

alg
BID2
things
A, B, C
start
input A, B C:=A
if
B > A
then
C:=B
sq
output C
end
Program
BID2;
var
A, B, C: real;
begin
readln(A, B);
C:=A; if
B>A
then
C:=B;
write(C) end.

Again everything is very similar. The else branch may not be present in a branch statement.

Programming Nested Branches

Let us write a program in Pascal for determining the largest of three numbers, the block diagram of which is shown in Fig. 3.10. The structure of this algorithm is nested branches. The algorithm in AY (BIT2) is given in the previous paragraph.

Rice. 3.10. Flowchart of an algorithm with nested branches

Program

BIT2;
var
A, B, C, D: real;
begin
readln(A, B, C);
if
A>B
then if
A>C
then
D:=A
else
D:=B
else if
B>C
then
D:=B
else
D:=C;
writeln(D) end.
Notice that before else

There is no semicolon. The entire branching part of the algorithm structure ends at the semicolon after the D:=C operator.

Let's create a program for ordering the values ​​of two variables.

alg
SORTING
things
X, Y, From
start
input X, Y
if
X>Y
then
C:=X X:=YY:=C
sq
output X, Y
end
Program
SORTING;
var
X, Y, C : real;
begin
readln(X, Y) ;
if
X>Y
then begin
С : =X;
X:=Y; Y:=C end
;
write(X,Y) end.

This example illustrates the following Pascal rule: if there are several consecutive operators on any branch of the branch operator, then they must be written between the service words begin

and
end
. This type of design:

begin
end
is called a compound statement

. Therefore, in the general form described above, branches and can be simple (single) and compound statements.

Logical operations

Finally, let's create another, third version of the program for determining the largest number out of three.
Program
BIT3;
var
A,B,C,D: real;
begin
readln(A,B,C);
if
(A>=B)
and
(A>=C)
then
D:=A;
if
(B>=A)
and
(B>=C)
then
D:=B;
if
(C>=A)
and
(C>=B)
then
D:=C;
writeln(D) end.
It is not difficult to understand the meaning of this program. Three consecutive incomplete branches are used here. And the branch conditions are complex logical expressions

, including the logical operation
and
(AND). You've encountered logical operations while working with databases and spreadsheets.

Recall that the and operation is called logical multiplication or conjunction.
Its result is true if both operands are true. Obviously, if A>=B and A>=C, then A has the greatest value, etc. Pascal contains all three basic logical operations: and
- AND (conjunction),
or
- OR (disjunction),
not
- NOT (negation).

Complex logical expressions

Note that relations connected by logical operations are enclosed in parentheses. This is how you should always do it! For example, you need to determine whether among the numbers A, B, C there is at least one negative one. The following branch operator solves this problem:

if

(A
then
write( 'YES')
else
write( 'NO ');

An expression true for a negative number can also be written like this:

not

(A>=0)

Questions and tasks

1. How to program complete and incomplete branching in Pascal?

2. What is a compound operator? When is a compound operator used in a branch operator?

3. Run all the programs given in this paragraph on your computer.

4. Make at least three versions of a program for determining the smallest of three given numbers.

5. Create a program for sorting in ascending order of values ​​in three variables: A, B, C.

6. Create a program for calculating the roots of a quadratic equation using the given values ​​of its coefficients.

Principles for constructing conditions

The first thing you need to know is relational operators. In Pascal their types are described as follows:

  • >— strict “more”;
  • >= — non-strict “greater than”;
  • < — strict “less”;
  • <= - non-strict “less”;
  • = - comparison for equality, differs from assignment by the absence of a colon;
  • <> - comparison for inequality.

The simplest one-part conditions are not separated by brackets. Any variable or number can appear on either side of the operator. For more complex cases, logical operations are needed:

  • The conjunction "AND". True only when both conditions are true. In natural language it will be called “and”.
  • Disjunction "OR". False only with two values ​​of "False". Can be interpreted as "or".
  • Strict disjunction "XOR". Checks for the combination of truth and falsehood.
  • Negation "NOT". Changes the result to the opposite - a semantic “not”.

Parts of a combined condition separated by logical operators must be separated by quotation marks. Otherwise, the program may compile but not work as intended. It is important to understand that a branching scheme can be set to as many levels as desired - conditional statements can be used within their own blocks, and they can be nested in a loop.

Examples of problems

There are many examples of the use of conditional statements, because they are an indispensable part of many algorithms. For example, solving the problem of finding the maximum in an array is reduced to a loop with incomplete branching in the body: the variable initialized by the first member is rewritten only if it is strictly less than an array element or a number entered by the user.

If the question is asked about the length of the path of a cyclist who rides at a speed of 15 kilometers per hour for the first 3 hours and 8 kilometers per hour the rest of the time, it means that the program code will have a complete structure. For time t less than or equal to 3, the formula “s := 15*t” is relevant, for a larger value - “s := 15*3 + 15*(t-3)”.

A program that determines whether a number x is in the range from 25 to 50 can be described in one line: if (x >= 25) AND (x <= 50) then writeln ('includes'). The number x, depending on the conditions, can be entered by the user or read from the array. Some problems require additional calculations. They can be specified directly when comparing, since relational operators have lower priority. For example, when checking a number for parity, the condition “x mod 2 = 0” is relevant.

Incomplete branches require mastery of relational operators. For complete ones, logical operations are needed. Although conditional operators are studied in computer science lessons in the 8th grade, they are the basis of all algorithms. This applies to almost all programming languages: Pascal, C©, Java and others.

Conditional operator in Pascal

Before considering this topic, linear algorithms in Pascal were mainly used, which are typical for very simple problems when actions (operators) are performed sequentially, one after another. More complex algorithms involve the use of a branching construct.

Conditional operator block diagram:


The conditional statement in Pascal has the following syntax:

Abridged version:

if condition then statement;

if condition then statement;
Full version:

if condition then statement else statement;

if condition then statement else statement;

The conditional operator in Pascal - if - serves to organize the progress of a task in such a way that the sequence of execution of operators changes depending on some logical condition. A logical condition can take one of two values: either true or false, respectively, it can be either true or false.

Compound operator

If, under a true condition, it is necessary to execute several statements, then, according to the rules of the Pascal language, they must be enclosed in a block , starting with the service word begin and ending with the service word end. Such a block is usually called operator brackets , and this construction is called a compound operator :

Operator brackets and compound operator in Pascal:

if logical expression then begin statement1; operator2; end else begin statement1; operator2; end;

if logical expression then begin statement1; operator2; end else begin statement1; operator2; end;

Translation from English of the condition operator will make it easier to understand its use:

IFTHENELSE
IFTHATOTHERWISE


The condition (in a logical expression) uses relational operators. Consider Pascal's list of relational operators:

  • more >
  • less
  • greater than or equal to in Pascal >=
  • less than or equal to in Pascal
  • comparison in Pascal =
  • not equal in Pascal

Example: find the largest of two numbers

Option 1Option 2

understand in detail how the conditional operator works in Pascal by watching the video tutorial:

Example: calculate the value of the variable y using one of two branches

Show solution:

1 2 3 4 5 6 7 8 9 10 11var x,y:real; begin writeln('enter x'); read(x); if x>0 then y:=ln(x) else y:=exp(x); writeln ('y=', y:6:2) {the resulting number will occupy 6 positions and will have 2 decimal places} end.

var x,y:real; begin writeln('enter x'); read(x); if x>0 then y:=ln(x) else y:=exp(x); writeln ('y=', y:6:2) {the resulting number will occupy 6 positions and will have 2 decimal places} end.

Notice how y is output in this example. When outputting real type variables in pascal, you can use the so-called formatted output , or notation with two colons: y:6:2 - the digit after the first colon (6) indicates how many characters the number will occupy when displayed on the screen - the digit after the second colon (2) indicates how many decimal places of the real number will be output

Thus, using such notation in pascal practically allows you to round to hundredths, thousandths, etc.

Task 0. Calculate the value of the variable y using one of two branches:

Task 1. Two numbers are entered into the computer. If the first is greater than the second, then calculate their sum, otherwise - the product. After this, the computer should print the result and the text PROBLEM SOLVED

Problem 2. The dragon grows three heads every year, but after it turns 100 years old, only two. How many heads and eyes does a dragon have that is N years old?

Logical operations in Pascal (in logical expression)

When you need to use a double condition in Pascal, you will need logical operations.

  • The logical operation AND (AND), placed between two conditions, says that both of these conditions must be fulfilled at once (must be true). The logical meaning of the operation is “conjunction”.
  • Placed between two conditions, the OR indicates that it is sufficient if at least one of them is satisfied (one of the two conditions is true). The logical meaning of the operation is “disjunction”.
  • In Pascal, XOR is a logical operation sign that has the meaning of “strict disjunction” and indicates that it is necessary that one of two conditions be fulfilled (true) and the other not satisfied (false).
  • The logical operation NOT before a logical expression or variable has the meaning of “negation” or “inversion” and indicates that if a given variable or expression is true, then its negation is false and vice versa.

Important: Each simple condition must be enclosed in parentheses.

Example : Let's look at examples of logical operations in logical expressions in Pascal

1 2 3 4 5 6 7 8var n:integer; begin n:=6; if (n>5) and (n<10) then writeln('true'); if (n>7) or (n<10) then writeln('true'); if (n>7) xor (n<10) then writeln('true'); if not(n>7) then writeln('true'); end.

var n:integer;
begin n:=6; if (n>5) and (n<10) then writeln('true'); if (n>7) or (n<10) then writeln('true'); if (n>7) xor (n<10) then writeln('true'); if not(n>7) then writeln('true'); end. Example: A company is recruiting employees from 25 to 40 years of age inclusive. Enter the person’s age and determine whether he is suitable for this company (display the answer “suitable” or “not suitable”). Feature: you need to check whether two conditions are met simultaneously.

Option 1Option 2

Example: Given an integer number A. Check the truth of the statement: “The number A is odd.”

Open solution:

1 2 3 4 5 6 7 8 9 10 11var a,b: integer; begin write('Enter A: '); read(a); b := a mod 2; if b>0 then writeln('true') else writeln ('false') end.

var a,b: integer;
begin write('Enter A: '); read(a); b := a mod 2; if b>0 then writeln('true') else writeln ('false') end. Task 3. Given an integer A. Check the truth of the statement: “The number A is positive.”

Task 4. A person enters a number into the computer. If it is in the range from 28 to 30, then you need to print the text HIT, if it is greater than or equal to 30, then OVER, if it is in the interval from 0 to 28, then UNDERFLY, if the number is less than zero, DO NOT HIT YOURSELF

Rating
( 1 rating, average 4 out of 5 )
Did you like the article? Share with friends: