Contacts

Conditional operator in full form. Conditional operator in pascal. Full conditional statement

We continue to study the Pascal programming language. Let's consider the first algorithmic construction that is studied when learning a language - condition (branch). The article is intended for beginning programmers, as well as for computer science teachers. The tasks at the end of the article will help you consolidate your knowledge and test yourself.

The algorithmic construction CONDITION is used in cases where we are faced with a choice: to do one way or another.

The condition happens:

  1. Incomplete
  2. Complete

Incomplete condition

The block diagram of an incomplete condition looks like this:

Incomplete condition

IF CONDITION IS TRUE, THEN ACTION IN PROGRESS, OTHERWISE NOTHING HAPPENS

In Pascal, this algorithmic construction looks like this:

IF condition THEN action;

If the condition after IF true THEN.

What is a condition?

A condition is an expression that can be either true or false. The condition must contain logical operators <, >, =, <=, >=, <>(not equal).

For example:

if a=7 then writeln("Hello!"); end.

If the entered variable value a equals 7 , then on the screen we will see the word Hello! If it is not equal, then nothing will be displayed on the screen.

Let's look at another example:

var a:integer; begin readln(a); end.

if a=7 then writeln("Hello!"); writeln("See you");

Hello!
What will we see on the screen when we enter the number 7? We'll see:

See you

What will we see on the screen when we enter the number 7? We'll see:

What will we see on the screen when we enter the number 10? Why is that? Why See you

is displayed on screen anyway? Team

writeln("See you"); not applicable

var a:integer; to the If-Then construct if a=7 then writeln("Hello!"); writeln("See you"); // condition is highlighted in blue

end.

How can I make both actions belong to the If-Then construct? It is necessary to enclose these actions in the so-called: operator brackets

var a:integer;

begin... end; if a=7 then begin

writeln("Hello!");
Writeln("See you later");

end;
end.

Now, if we enter the number 10, we will not see anything on the screen.

Composite (complex) condition Sometimes you have to use a complex condition. To compose it, logical conjunctions are used: and or

  • or. If we use and,
  • or. then the compound condition will be true when all the simple conditions are true. or,

For example:

then a compound condition will be true when at least one simple condition is true. a>7 And<15 a

in Pascal it will be written<15)

those. both conditions must be true simultaneously for the compound condition to be true

(a=7) or (a>15)

The compound condition will be true if: either a=7, or a>17.

Task:

Using the If-Then construct, find the maximum among the three entered numbers.

Solution

var a, b, c:integer; begin readln(a); readln(b); readln(c); end.

if (a>b) and (a>c) then writeln("number ", a, " maximum");

if (b>a) and (b>c) then writeln("number ", b, " maximum");

if (c>a) and (c>b) then writeln("number ", c, " maximum");

  • Full condition The block diagram of the complete condition looks like this: IF condition THEN action_1 ELSE action_2; If.
  • Full condition condition is true, then the action after the word is performed Then

condition is false — , then the action after the word is performed.

Else. If the actions that are performed if the condition is true or false are multiple operator brackets are used if condition condition then begin if condition condition ................ action;

............... end

else

  1. end ; (no semicolon before else) Tasks for independent completion: The purchase amount is A
  2. rubles If
    • A
    • more than 1000 rubles, a 15% discount is provided. Display the purchase amount including the discount or a message stating that the discount is not provided.
  3. The areas of a circle and a square are known. Define: The purchase amount is Will a circle fit in a square? Will a square fit in a circle?
  4. Determine if a number is
  5. number divisor
    • b
    • Check whether the number entered from the keyboard belongs to the interval (-5;3). The purchase amount is
  6. A two-digit number is given. Define:
  7. does it include the number 3?
    • does it include a number?
    • Determine whether a triangle with sides a, b, c is isosceles
    • Three different numbers are given. Determine which one (first, second or third)

the biggest

the smallest Else. is average (the list of tasks will be updated) a>7 This lesson looks at the conditional operator in Pascal (). Explains how to use multiple conditions in one construct (

AND OR). Examples of working with an operator are considered

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 design.

Conditional operator block diagram:

Conditional operator in Pascal has the following syntax:

Abridged version:

if condition then statement;

Full version:

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 them according to the rules Pascal language must be enclosed in a block, starting with the function word begin and ending with the function word end . Such a block is usually called operator brackets, and this construction - compound operator:

Operator brackets and compound operator in Pascal:

if logical expression then begin statement1;

operator2; end else begin statement1;

IF operator2; end; Translation from English of the condition operator will make it easier to understand its use:
THEN ELSE IF


THAT
OTHERWISE

  • 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 1 Option 2

comparison in Pascal = Understand the work in detail

you can use the conditional operator in Pascal by watching the video tutorial:

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

Show solution: 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 withdrawing type variables in pascal, you can use the so-called
formatted output
, or notation with two colons:
y:6:2

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

Task 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? N years?

Logical operations in Pascal (in logical expression)

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

  • Logical operation (the list of tasks will be updated) (And), placed between two conditions, says that both of these conditions must be met at once (must be true). The logical meaning of the operation is “conjunction”.
  • Placed between two conditions, the sign This lesson looks at the conditional operator in Pascal ( (OR) says 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 - a sign of a logical operation that has the meaning of “strict disjunction” and indicates that it is necessary that one of the two conditions be fulfilled (true), and the other not satisfied (false).
  • Logical operation NOT before a logical expression or variable it means “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 8 var n: integer ;<10 ) then writeln ("истина" ) ; if (n>begin n: = 6 ;<10 ) then writeln ("истина" ) ; if (n>if (n>5 ) and (n<10 ) then writeln ("истина" ) ; if not (n>7 ) or (n

7)xor(n<10) then writeln("истина"); if (n>7) then writeln("true");<10) then writeln("истина"); if (n>end.<10) then writeln("истина"); if not(n>var n:integer; begin n:=6; if (n>5) and (n

comparison in Pascal = 7) or (n
7)xor(n 7) then writeln("true"); end.

The company recruits 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”). Peculiarity: can be roughly divided into two groups:

  1. simple;
  2. structured.

Simple Operators are operators that do not contain other operators. These include:

  • assignment operator (:=);
  • procedure statement;
  • unconditional jump operator (GOTO).

Structured statements are operators that contain other operators. These include:

  • compound operator;
  • conditional operators (IF, CASE);
  • loop operators (FOR, WHILE, REPEAT);
  • join operator (WITH).

Simple Operators

Procedure operator

Procedure operator serves to call a procedure.

Format: [procedure_name] (list of call parameters);

A procedure statement consists of a procedure identifier, immediately followed by a list of call parameters in parentheses. Pascal has procedures without parameters. In this case, when called, there is no list of parameters. Execution of a procedure statement leads to the activation of the actions described in its body. There are two types of procedures in Pascal:

  • Standard ones, which are described in the language itself and are part of the language;
  • User procedures that are created by the user.

To call standard procedures, you must connect in the USES section of the module (library) name, where this procedure is described. A number of procedures located in the SYSTEM module are always connected to the program automatically and their connection in the USES section is not necessary. Standard Pascal procedures are READ, WRITE, REWRITE, CLOSE, RESET.

READ ([file_variable], [input_list])

READ(x,y)

User procedures (non-standard) must be created before their use in the program and are located either in the description section of the program itself, or in separate program units of the module. If the procedure is in a module, then the name of that module must be mentioned in the USES application.

Unconditional GOTO operator

Format: GOTO [label];

GOTO is a reserved word in Pascal. [label] is an arbitrary identifier that allows you to mark a certain program statement and later refer to it. In Pascal, it is possible to use unsigned integers as labels. The label is placed before and separated from the marked operator (:). One statement can be marked with several labels. They are also separated from each other (:). Before using a label in the statement section, it must be described in the LABEL section (description section).

The GOTO action transfers control to the appropriate marked statement. When using tags, you must follow the following rules:

  • the label must be described in the descriptions section and all labels must be used;
  • if integers are used as labels, they are not declared.

Contradicts the principles of structured programming technology. Modern programming languages ​​do not include such an operator, and there is no need to use it. In addition, modern computers use the so-called conveyor method. If an unconditional jump operator is encountered in a program, then such an operator breaks the entire pipeline, forcing it to be created anew, which significantly slows down the computational process.

Structured statements

IF condition statements

The conditional operator is used in the program to implement the algorithmic structure - branching. In this structure, the computational process can continue in one of the possible directions. The choice of direction is usually carried out by checking some condition. There are two types of branching structures: fork and bypass structures.

In the Pascal language, the conditional IF operator is a means of organizing a branching computational process.

Format: IF [boolean_expression] Then [operator_1]; Else [operator_2];

IF, Then, Else are function words. [operator_1], [operator_2] - ordinary operations of the Pascal language. The Else part is optional (may be missing).

The IF statement works like this: first the result is checked logical expression. If the result is TRUE, then [statement_1] following the Then function word is executed, and [statement_2] is skipped. If the result is FALSE, then [statement_1] is skipped and [statement_2] is executed.

If the Else part is missing, then the IF statement is not in full form:

IF [boolean expression] Then [operator];

In this case, if the result is True (TRUE), then the [statement] is executed; if False (FALSE), then control is transferred to the statement following the IF statement.

There are 2 numbers A and B. Find the maximum number.

Compound operator

A compound statement is a sequence of arbitrary operations in a program, enclosed in so-called operator brackets (Begin-End).

Format: Begin [operators]; End;

Compound statements allow a group of statements to be represented as a single statement.

CASE selection statement

Designed to implement multiple branches, since the IF operator can implement only two directions of the computational process, it is not always convenient to use it to implement multiple branches. Multiple branching is implemented by the CASE statement.

Format: CASE [select_key] OF

[selection_constant_1]:[operator_1];

[selection_constant_2]:[operator_2];

[selection_constant_N]:[operator_N];

ELSE [operator];

CASE, OF, ELSE, END - function words. [select_key] is a parameter of one of the ordinal types. [selection_constants] - constants of the same type as the selection key that implement selection. [operator_1(N)] is an ordinary operator. ELSE may be missing.

The selection operator works as follows: before the operator operates, the value of the selection key parameter is determined. This parameter can either be expressed as a variable in the program or in some other way. Then the selection key parameter is sequentially compared with the selection constant. If the value of the selection key matches one of the selection constants, the operator following this constant is executed, and all other operators are ignored. If the selection key does not match any of the constants, the statement following Else is executed. Often Else is optional and if the selection key does not match any of the selection constants and in the absence of Else, control is transferred to the statement following the CASE statement.

The CASE statement does not have the explicit conditional checking that is typical for the IF statement. At the same time, the comparison operation is performed implicitly. CASE introduces dissonance into a Pascal program, since this statement ends with the service word End, which does not have a paired Begin.

Create an algorithm and program for a problem simulating the operation of a traffic light. When you enter the symbol of the first letter of the traffic light colors, the program should display a message about the corresponding color and actions.

The program works as follows: using the Read procedure, the letter symbol of the traffic light color is entered from the keyboard. If the letter ‘z’ corresponding to the green color is entered, then in the CASE statement the value entered in the selection list will find the selection constant ‘z’ and the message “Green color, movement is allowed” will be displayed. When you enter the symbol of the letters 'k' and 'zh', similar messages will be displayed. If you enter any other character, the message “Traffic light does not work” will be displayed, because in this case the Else part of the CASE statement works.

Loop statements

A cyclic algorithmic structure is a structure in which some actions are performed several times. There are two types in programming cyclic structures: loop with parameter and iterative loop.

In a cycle with a parameter there are always so-called cycle parameters: X, X n, X k, ∆X. Sometimes a loop with a parameter is called a regular loop. A characteristic feature is that the number of loops and repetitions can be determined before the loop is executed.

In an iterative loop, it is impossible to determine the number of loops before executing it. It is executed as long as the loop continuation condition is satisfied.

The Pascal language has three operators that implement cyclic computational structures:

  • counting operator FOR. It is intended to implement a loop with a parameter and cannot be used to implement an iterative loop;
  • loop operator with WHILE precondition;
  • loop operator with REPEAT postcondition.

The last two are focused on implementing an iterative loop, but they can also be used to implement a loop with a parameter.

FOR operator

Format: FOR [loop_parameter] := [n_z_p_ts] To [k_z_p_ts] Do [operator];

FOR, To, Do are function words. [cycle_parameter] - cycle parameter. [n_z_p_ts] - the initial value of the cycle parameter. [k_z_p_ts] - final value of the cycle parameter. [operator] - arbitrary operator.

The loop parameter must be an ordinal variable. The start and end values ​​of the loop parameter must be of the same type as the loop parameter.

Let's consider the operator's work using its algorithm:

At the first step, the value of the cycle parameter takes [n_z_p_ts], then the cycle parameter is checked to be less than or equal to [k_z_p_ts]. This condition is the condition for continuing the loop. If executed, the loop continues its operation and the [statement] is executed, after which the loop parameter is increased (decreased) by one. Then, with the new value of the loop parameter, the condition for continuing the loop is checked. If it is fulfilled, then the actions are repeated. If the condition is not met, then the loop stops running.

The For operator is significantly different from similar operators in other programming languages. The differences are as follows:

  • body of the For operator. The statement may not be executed even once, since the loop continuation condition is checked before the loop body;
  • the cycle parameter change step is constant and equal to 1;
  • The body of the loop in the For statement is represented by one statement. If the action of the loop body requires more than one simple statement, then these statements must be converted into one compound statement using operator brackets (BEGIN-END);
  • A loop parameter can only be an ordinal variable.

Example of using the FOR operator: create a table for converting rubles to dollars.

WHILE statement (loop statement with precondition)

Format: WHILE [condition] Do [operator];

WHILE, Do - function words. [condition] - expression of logical type. [operator] - ordinary operator.

;

The While statement works as follows: first, the result of the logical condition is checked. If the result is true, then the statement is executed, after which it returns to checking the condition with the new value of the parameters in the logical expression of the condition. If the result is false, then the loop is terminated.

When working with While, you need to pay attention to its properties:

  • the conditions used in While are the loop continuation condition;
  • in the body of the loop, the value of the parameter included in the condition expression always changes;
  • The While loop may not execute even once, since the condition check in the loop continuation is performed before the loop body.

REPEAT statement (loop statement with postcondition)

Format: REPEAT [cycle_body]; UNTIL [condition];

The REPEAT statement works as follows: first, the statements in the body of the loop are executed, after which the result is checked for the logical condition. If the result is false, then it returns to executing the statements of the next loop body. If the result is true, then the operator exits.

The Repeat operator has the following features:

  • in Repeat, the loop termination condition is checked and if the condition is met, the loop stops working;
  • The body of the loop is always executed at least once;
  • the parameter for checking the condition is changed in the body of the loop;
  • The loop body statements do not need to be enclosed in operator brackets (BEGIN-END), while the role of operator brackets is performed by Repeat and Until.

Calculate y=sin(x), where xn=10, xk=100, step is 10.

When solving most problems, computational processes branch out. Selective statements are used to determine the further direction of program execution. This class includes the conditional operator and the selection operator.

The conditional operator, used to branch the algorithm into two directions, is one of the key tools not only in Pascal, but also in any other programming language.

The conditional statement can be in two forms: full and short.

Full form of the conditional statement

The full form of the conditional operator in Pascal is as follows:

  • if expression then
  • operator1
  • operator2

The expression element is a Boolean expression. If the expression evaluates to true, then operator1 (then branch) is executed, otherwise operator2 (else branch) is executed. Then, control is transferred to the operator following the conditional.

Consider a code fragment of a program that determines the minimum value of two numbers:

(Program code fragment)

  • if (a > b) then
  • minDig:= b
  • minDig:= a;
  • writeln(minDig);

If the value of variable a is greater than the value of variable b, then the assignment operator will be executed in the then branch (minDig will receive the value of b), otherwise - in the else branch (minDig will receive the value of a), then the value of the minDig variable will be printed.

In a conditional statement, there can be only one statement after then and after else. Therefore, if you need to use more than one operator, then a compound operator is used.

Short form of the conditional statement

The short form of the conditional operator is written as follows:

  • if expression then
  • operator

If the expression evaluates to true, then the statement is executed, otherwise the transition to the next program statement occurs. So, in the following fragment of program code, if the number x turns out to be odd, then its value will be increased by 1 (i.e., it will become even), otherwise the transition to displaying the value of x on the screen occurs.

"fork".
Branching out is an algorithm in which one of several is selected possible options computing process. Each such path is called branch of the algorithm.

A sign of a branching algorithm is the presence of condition checking operations. The most common way to test a condition is to use the if statement.

if can be used in full or incomplete fork form.

In case of incomplete fork if Condition true, then BlockOperations1 executed if Condition false, then BlockOperations1 is not executed.

In case of a complete fork if Condition true, then true BlockOperations1 , otherwise executed BlockOperations2 .

BlockOperations may consist of one operation. In this case, the presence curly braces, which bound the block, are optional.

Example in C:

1
2
3
4
5
6
7
8
9
10
11
12
13
14


#include
int main()
{
int k; // declare an integer variable k
printf("k= " ); // display a message
scanf("%d" , &k); // enter variable k
if (k >= 5) // if k>5
printf("%d >= 5" , k); // print "VALUE >= 5"
else // otherwise
printf("%d< 5" , k); // print "VALUE< 5"
getchar(); getchar();
return 0;
}


Execution result

The if statement can be nested.

Example in C:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#define _CRT_SECURE_NO_WARNINGS // to be able to use scanf
#include
#include
int main() (
int key;
system("chcp 1251" );
system("cls" ); // clear the console window
printf();
scanf("%d" , &key);
if (key == 1) // if key = 1
printf( "\nFirst item selected"); // display a message
else if (key == 2) // otherwise if key = 2
printf( "\nSecond item selected"); // display a message
else // otherwise
printf(); // display a message
getchar(); getchar();
return 0;
}

Execution result





When using a nested form of an if statement, the else option is associated with the last if statement. If you want to link an else option to a previous if statement, the inner conditional statement is enclosed in curly braces:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#define _CRT_SECURE_NO_WARNINGS // to be able to use scanf
#include
#include // to use the system function
int main() (
int key; // declare the whole variable key
system("chcp 1251" ); // switch to Russian in the console
system("cls" ); // clear the console window
printf( "Enter item number, 1 or 2: ");
scanf("%d" , &key); // enter the value of the key variable
if (key != 1) ( // if key is not equal to 1
if (key == 2) // if key is 2
printf( "\nSecond item selected"); // message output
} // if key is neither 1 nor 2, then nothing is output
else // otherwise if key is 1
printf( "\nFirst item selected"); // message output
getchar(); getchar();
return 0;
}


Execution result





Ternary operations

Ternary conditional operator has 3 arguments and returns its second or third operand depending on the value of the Boolean expression given by the first operand. Syntax of ternary operator in C language

Condition? Expression1: Expression2;


If fulfilled Condition, then the ternary operation returns Expression1, otherwise - Expression2 .

Ternary operations, like conditional operations, can be nested. Parentheses are used to separate nested operations.

The above example using ternary operators can be represented as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#define _CRT_SECURE_NO_WARNINGS // to be able to use scanf
#include
#include // to use the system function
int main() (
int key; // declare the whole variable key
system("chcp 1251" ); // switch to Russian in the console
system("cls" ); // clear the console window
printf( "Enter item number, 1 or 2: ");
scanf("%d" , &key); // enter the value of the key variable
key == 1 ? printf( "\nFirst item selected") :
(key == 2 ? printf( "\nSecond item selected") :
printf( "\nThe first and second items are not selected"));
getchar(); getchar();
return 0;
}

Switch statement (multiple choice statement)

The if statement allows you to choose only between two options. In order to select one of several options, you must use a nested if statement. You can use the switch branch operator for the same purpose.

General recording form

switch (IntegerExpression)
{
case Constant1: BlockOperations1;
break ;
case Constant2: BlockOperations2;
break ;
. . .
case Constant: BlockOperationsn;
break ;
default: DefaultOperationBlock;
break ;
}

The switch statement is executed as follows:

  • calculated IntegerExpression in parentheses of the switch statement;
  • the resulting value is compared with the labels ( Constants ) in case options, the comparison is performed until a label corresponding to the evaluated value of the integer expression is found;
  • performed BlockOperations corresponding label case ;
  • if the corresponding label is not found, then DefaultOperationBlock , described in the default option.

The default alternative may not be present, in which case no action will be taken.
Option break;

exits the switch statement and moves to the next statement. If the break option is absent, all statements will be executed, starting with the one marked with this label and ending with the statement in the default option.

Constants in case options must be of integer type (can be characters).