What function word does the conditional statement begin with? Branching structure


"fork".
Branching out is an algorithm in which one of several possible options for the computational process is selected. 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 of curly braces demarcating the block is 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 between only two options. In order to select one of several options, you must use a nested if statement. For the same purpose, you can use the switch branch operator.

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

x = 2 print(x == 2) #True print(x == 3) #False print(x

Let's say we want to determine its absolute value (modulus) from a given number x. The program should print the value of variable x if x>0 or the value -x otherwise. The linear structure of the program is violated: depending on the validity of the condition x>0, one or another value must be output. The corresponding fragment of the Python program looks like ( Try it yourself. Click the buttonRUN) You can change the value of the variable x and see that the program output will always be a positive number:

x = -7 if x > 0: print(x) else: print(-x)

This program uses a conditional statement if(If ). After the word if, the condition to be checked is indicated ( x > 0), ending with a colon. After this comes a block (sequence) of instructions that will be executed if the condition is true, in our example this is displaying the value x. Then comes the word else, also ending with a colon, and a block of instructions that will be executed if the condition being tested is false, in this case the value -x will be printed.

This piece of Python code is intuitive to anyone who remembers that if in English it means "if", and else - "otherwise". The branch operator in this case has two parts, the operators of each of which are written indented to the right relative to the branch operator. A more general case isselection operator- can be written using the following syntax:

If Condition:
Instruction block 1
else:
Instruction block 2

Instruction block 1 will be executed if The condition is true. If Condition is false, will be executed Instruction block 2.

A conditional statement may lack the word else and a subsequent block. This instruction is called incomplete branching. For example, if given a number x and we want to replace it with the absolute value of x, then this can be done as follows:

1 2 3 if x< 0 : x = -x print(x)

In this example, the variable x will be assigned the value -x, but only if x<0. А вот инструкция print(x) будет выполнена всегда, независимо от проверяемого условия.

Let me remind you once again (since this is very important for the Python language) indentation is used in the Python language to highlight a block of instructions related to an if or else statement. All instructions that belong to the same block must have the same amount of indentation, that is, the same number of spaces at the beginning of the line. It is recommended to use 4 spaces indentation and it is not recommended to use a tab character as indentation.

This is one of the significant differences between the Python syntax and the syntax of most languages, in which blocks are distinguished by special words, for example, nts... cc in Idol, begin... end in Pascal or (curly) brackets in C.

Logical operators

Sometimes you need to check not one, but several conditions at the same time. For example, you can check whether a given number is even using the condition (n % 2 == 0) (the remainder of n divided by 2 is 0), and if you need to check that two given integers n and m are even, you need to check the validity of both conditions: n % 2 == 0 and m % 2 == 0, for which they need to be combined using the and operator (logical AND): n % 2 == 0 and m % 2 == 0.

There are standard logical operators in Python: logical AND, logical OR, logical negation (NOT).

Logical AND is a binary operator (that is, an operator with two operands: left and right) and has the form and . The and operator returns True if and only if both of its operands are True.

Logical OR is a binary operator and returns True if and only if at least one operand is True. The “logical OR” operator has the form or .

Logical NOT (negation) is a unary (that is, with one operand) operator and has the form not followed by a single operand. Boolean NOT returns True if the operand is False and vice versa.

Example. Let's check that at least one of the numbers a or b ends in 0:

if a % 10 == 0 or b % 10 == 0:

Let's check that the number a is positive and b is non-negative:

if a > 0 and not (b< 0):

Or instead of not (b< 0) записать (b >= 0).

Multiple Branch Instruction

Sometimes it is necessary to choose not from two alternative execution paths, but from several, for example, depending on whether a certain value is positive, negative or equal to zero, one of three actions should be performed. In this case, you can use the multiple branch instruction. An example of using the multiple branch instruction:

1 2 3 4 5 6 7 8 9 x= 2 if x==1 : print "one" elif x==2 : print "two" elif x==3 : print "three" else: print "another number"

In multiple branching, there must be one if statement followed by a block, one or more elif statements followed by blocks, and possibly an else statement followed by a block. All conditions are checked one by one and the block of instructions that follows the condition whose value is true will be executed. If several conditions are true, then only the block of instructions that follows the first of these conditions will be executed (and the remaining conditions will not even be checked). If all conditions are false, then the else block, if any, will be executed.

Nested Conditional Statements

Inside a conditional instruction block there can be any other instructions, including a conditional instruction. Such instructions are called nested. The syntax for a nested conditional statement is:

If condition1: ... if condition2: ... else: ... ... else: ...

Instead of ellipses, you can write arbitrary instructions. Pay attention to the size of the indents before the instructions. A block of nested conditional instructions is separated by a large indentation. The level of nesting of conditional instructions can be arbitrary, that is, inside one conditional instruction there can be a second one, and inside it another one, etc.

Example. We have two non-zero variables x and y, we want to determine in which quarter of the coordinate plane the point with coordinates (x,y) is located

x=4 y=-6 if x>0: print ("x>0") if y>0: print ("y>0") print ("I (first)") else: print ("y 0: print ("y>0") print ("II (second)") else: print ("y

Exercise

Change the values ​​of the variables so that all conditions are True, and the program results in displaying numbers from 1 to 6. Try it yourself. Click the button SOLUTION to see the finished code (But it's better to try it yourself first). NEEDED hint - write in the comments!))

number = 10 second_number = 10 first_array = second_array = if number > 15: print("1") if first_array: print("2") if len(second_array) == 2: print("3") if len(first_array) + len(second_array) == 5: print("4") if first_array and first_array == 1: print("5") if not second_number: print("6") number = 16 second_number = 0 first_array = second_array = if number > 15: print("1") if first_array: print("2") if len(second_array) == 2: print("3") if len(first_array) + len(second_array) == 5: print( "4") if first_array and first_array == 1: print("5") if not second_number: print("6") test_object("number") test_object("second_number") test_object("first_array") test_object("second_array ") success_msg("Super!")

The article is written based on materials:

  • http://informatics.mccme.ru/
  • https://server.179.ru
  • https://www.learnpython.org
  • http://www.intuit.ru/


Laboratory work

On the topic of: " Condition operator if - else "


1. Purpose and syntax

The if-else condition statement is used to select the direction of the program's operation depending on the conditions prevailing at a given point in the program at the time of its execution.

General form of writing a conditional operator

if ( <условие>)

<блок операторов 1>;

<блок операторов 2>;

If at the time of execution<условие>true, the program transfers control<блоку операторов 1>and, further, to the first statement outside the if-else construct. Wherein<блок операторов 2>is not executed. Otherwise, if<условие>false, executed<блок операторов 2>, A<блок операторов 1>skipped. Corresponding block diagram


Curly braces in the syntax of the if-else statement are used to highlight blocks 1 and 2 in the text. Try to place the closing brace below the opening brace to improve the readability of the program code. For the same purpose, the text inside the curly braces must be shifted to the right by several positions.

Any Boolean expression that evaluates to true or false can be used as a condition in if-else statements. Below is a table showing the simplest comparison operations between integers and real numbers

Example 1. It is required to write a program that converts temperature on the Celsius scale T C (°C) to temperature on the Kelvin scale T K (K). The T C value is entered by the user from the keyboard.

Solution. We use the well-known conversion formula – T K = T C – T 0, where T 0 = –273 °C is the temperature of absolute zero. We will consider the entered T C to be incorrect if it is less than T 0 .

// – KelvinvsCelsius–

#include // for streaming I/O

#include // for console I/O (getch)

#pragma argsused

floatT0 = -273; // declare and initialize T0

floatTc, Tk; // declare real Tc and Tk

cout<<» VvediteTc=»; // выводим приглашение

cin>>Tc; // request Tc

if ( Tc < T 0) // check condition Tc

cout<<» Tc < T0!»; // условие истинно, выводим на

} // error message screen

Tk = Tc-T0; // condition is false, calculate

cout<< «Tk =» << Tk; // Tk и выводим на экран

getch(); // delay before pressing a key

return 0; // end the program

Type the above code, compile it and run the program. Examine the results of operation at various values ​​of T C .

2. Shortened recording options

In programming, it is common to find that some action is required in response to existing conditions (for example, if incorrect input data is received from the user, then issue an error message and exit the program). In such cases, C++ programs may use a shorthand notation of the conditional statement with the missing else block. The general form of such a record

if ( <условие>)

<блок операторов>;

Here, if the condition is true, control is transferred to the block of statements in curly braces. If the condition is false, this block is skipped. The corresponding block diagram differs from the previous one in the absence of one “arm”


Another shorthand option is used when any of the if or else blocks consist of only one statement. In this case, the absence of curly braces delimiting this block is allowed.

if ( <условие>)

operator 1;

operator 2;

Here, operators 1 and 2 can be not only simple one-line arithmetic operations or I/O operators, but also complex multi-line constructs, such as other (nested) conditional statements or loop operators, which will be discussed below.

3. Nested statements

Conditional statements can be nested within each other, in accordance with the software algorithm that they implement. An arbitrary degree of their “nesting” is allowed.

If one if-else statement is nested within another, then the first statement is included in the second fully, and not just any one of its if or else parts. Partial overlap of their individual blocks is unacceptable.

In the example above, one of the statements (shown in bold) is nested within another. Entry B) is incorrect due to the fact that the else block of the inner conditional statement partially overlaps with both the if and else blocks of the outer statement.

Example 2. The user enters three integers a, b, c from the keyboard. It is necessary to display the largest of these numbers.

Solution. One of the possible algorithms for solving this problem is shown in the following block diagram.


The scheme can be implemented programmatically using nested if-else statements

// – Selecting the largest of 3 numbers –

#include

#include

#pragma argsused

int main (int argc, char* argv)

float a, b, c; // declare three variables

cout<< «Vvedite a –»; // вводимзначения a, b, c

cout<< «Vvedite b –»;

cout<< «Vvedite c –»;

if (a>b) // if a > b

if (a>c) // if a > c

cout<<» max = «<

else // otherwise, i.e. if a<= с

cout<<» max = «<

else // otherwise, i.e. if a<= b

if (b>c) // and if b > c

cout<<» max = «<

else // otherwise, i.e. if b<= а

cout<<» max = «<

getch(); // delay before pressing any key

Analyze the block diagram of this algorithm and its software implementation. Modify the algorithm and program code to find the smallest of three numbers.

4. Compound logical expressions

The condition in an if-else statement can be expressed as more than just a comparison of two numeric values. For example, double conditions are very common, which in mathematics are written as “a< b < c». Запись означает, что значение b лежит в диапазоне между значениями a и c. В программе такие условия должны быть переформулированы с использованием простых операций сравнения и логических операций «И», «ИЛИ», «НЕ»

In particular, the expression “a< b < c» сформулируем как «a меньше b, и b меньше c». На С++ это будет записано как (a

if((a

Example 3. On an empty chessboard there is a white pawn in position (n, m), and a black bishop in position (k, l). Here the first coordinate is the column number of the chessboard, the second is the row number (both vary in the range from 1 to 8). Assess the current situation according to three options

The pawn is under attack

The elephant is under attack

The bishop and pawn are “safe”.

Solution. Let's take into account that the pawn can attack the two positions closest to it diagonally forward, and the bishop attacks both of its diagonals completely. From here the conditions can be formulated

· “((k = n+1) OR (k = n‑1)) AND (l = m+1)” – pawn attack on bishop,

· “(k+l = n+m) OR (k-l = n-m)” – bishop attack on pawn,

· otherwise the pieces are safe.

// – Chess composition –

#include

#include

int main (int argc, char* argv)

cout<<«Koordinaty beloi peshki:«<

cout<<» vvedite n –»;

cout<<» vvedite m –»;

cout<<«Koordinaty chernogo slona:«<

cout<<» vvedite k –»;

cout<<» vvedite l –»;

if(((k==n+1)||(k==n‑1))&&(l==m+1)) // bishop attacked

cout<

if((k+l==n+m)||(k-l==n-m)) // pawn attacked

cout<

else // no attack

cout<

It happens that programs need to organize branching. In this case, the process of solving a problem occurs on the basis of the fulfillment or non-fulfillment of some condition.

In the Pascal language, the selection of an action, depending on some condition, can be implemented using the construction

if... then... else... if... then...

2. What is the full form of the conditional jump operator if in Pascal?

Full form of the conditional jump operator if :

if condition then operator1 else operator2;

The action of the operator is as follows: first, the value of the expression is calculated condition . If it is true (equal to TRUE ), then the statement that follows the word is executed then (operator1). If the value is false (FALSE), then the statement that follows the word is executed else(operator2 ).

Operators operator1 And operator2 can be compound, that is, contain several lines of code. Such operators are placed in operator brackets begin...end. This need arises if after reserved words then or else you need to specify several operators.

In this case, the general form of the conditional jump operator may have, for example, the following form:

if condition then begin // several operators ... end else begin // several operators ... end ;

3. What is the abbreviated form of the conditional jump operator?

The short form of the conditional jump operator does not contain a block else and has the form:

if condition then operator;

In this case, the operator works as follows. First, the value of the logical (Boolean) expression is calculated condition . If the result of a logical expression condition true (equal TRUE), then the operator that follows the word is executed then. If the result is FALSE , then the statement that follows the statement is executed if(in the statement if...then nothing is done).

If, when a condition is met, several operators need to be executed, then the general form of the conditional jump operator can be as follows:

if condition then begin // two or more operators ... end ;

4. Examples of using the conditional jump operator, which has a full representation form.

Example 1. Fragment of a program for finding the maximum value between two real numbers.

var a,b:real; // a, b - variables for which the maximum is sought max:real; // maximum ... begin ... // a, b - are specified if a>b then max:=a else max:=b; ... end ;

Example 2.

A fragment of program code that solves this problem:

... var x,f:real; begin ... // x - specified if -5 then f:= x*x+8 else f:= -x*x*x+2 ; // in the variable f - the result ... end ;

5. Examples of using the conditional jump operator, which has a shortened form of representation.

Example 1. Code snippet that finds the minimum value between two real numbers x And y .

... var min:real; ... begin ... // x, y - given min:= x; if min then min:= y; ... end ;

Example 2. Calculate the value of a function according to a condition. Suppose we need to find the value of a function:

var x, f:real; begin ... // x - specified if x<-6 then f:=3 *x*x-x; if (-6 <=x) and(x<=5 ) then f:=sqrt(7 -x); if x>5 then f:=8 *x-3 ; ... end ;

Conditional statements allow you to select certain parts of the program for execution depending on certain conditions. If, for example, the program uses real variables x and z, and at some stage of solving the problem it is necessary to calculate z=max(x, y), then the desired result is obtained by executing either the assignment operator z:=x or the assignment operator z:=y. Since the values ​​of the variables x and y are unknown in advance, but are determined during the calculation process, the program must provide both of these assignment operators. However, one of them should actually be executed. Therefore, the program must contain an indication of in which case one or another assignment operator should be selected for execution.

It is natural to formulate this instruction using the relation x>y. If this relation is valid for the current values ​​of x and y (takes the value true), then the operator z:=x must be selected for execution; otherwise, the operator z:=y must be chosen for execution (if x=y it does not matter which operator is executed, so executing the operator z:=y in this case will give the correct result).

To specify this kind of branching computational processes in programming languages, there are conditional statements. Let's consider the full conditional operator Pascal:

if B then S1 else S2

Here if(If), then(that) and else(otherwise) are function words, IN is a logical expression, and S1 And S2– operators.

The execution of such a conditional operator in Pascal is reduced to the execution of one of the operators S1 or S2 included in it: if the condition specified in the operator is satisfied (the logical expression B evaluates to true), then the operator S1 is executed, otherwise the operator S2 is executed.

The algorithm for solving the above-mentioned problem of calculating z= max(x, y) can be specified in the form Pascal's conditional operator

if x>y then z:= x else z:=y

When formulating algorithms, a very typical situation is when at a certain stage of the computational process some actions need to be performed only if a certain condition is met, and if this condition is not met, then at this stage no actions need to be performed at all. The simplest example of such a situation is to replace the current value of a variable x with the absolute value of this value: if x<0, то необходимо выполнить оператор присваивания x:= - x; если же x>=0, then the current value of x should remain unchanged, i.e. At this stage there is no need to perform any actions at all.

In such situations, a shortened form of writing a conditional operator in Pascal is convenient:

if B then S

Rule for performing abbreviated Pascal's conditional operator quite obvious: If the value of logical expression B is true, That operator S is executed; V otherwise no other actions are performed.

In the Pascal programming language, in the conditional statement between then And else, and also after else According to the syntax, there can only be one operator. If, when a given condition is fulfilled (or not met), a certain sequence of actions must be performed, then they must be combined into a single, compound operator, i.e. enclose this sequence of actions in operator brackets begin... end (it is important!). If, for example, at x< y надо поменять местами значения этих переменных, то conditional operator would be written as follows in Pascal:

if x then begin r:=x; x:=y; y:=r end

Availability of shortened form Pascal's conditional operator requires great care when using. For example, the conditional statement

if B1 then if B2 then S1 else S2

allows, generally speaking, two different interpretations:

  • How Pascal's complete conditional operator kind

if B1 then begin
if B2 then S1 end
else S2

  • How Pascal's shorthand conditional operator kind

if B1 then begin
if B2 then S1 else S2 end

According to Pascal's rules, the second interpretation takes place, i.e. every word is considered else matches the first word preceding it then. To avoid possible mistakes and misunderstandings, it is recommended that in all such cases, clearly highlight the desired form Pascal's conditional operator by placing it in operator brackets.

Pascal's selection operator

Pascal's selection operator allows you to select one of several possible program continuations. The parameter by which the selection is made is the selection key - an expression of any ordinal type.

The structure of the selection operator in Pascal is:

Case<ключ_выбора>of
<список_выбора>
end

Here case, of, else, end– reserved words (case, from, otherwise, end);

  • <ключ_выбора>- expression of ordinal type;
  • <список_выбора>- one or more structures of the form:
    • <константа_выбора>: <оператор>;
  • <константа_выбора>- a constant of the same type as the expression
    • <ключ_выбора>;

<операторы>- arbitrary Pascal operators.

Pascal's selection operator works as follows. First, the value of the expression is calculated<ключ_выбора>, and then in sequence<список_выбора>a constant equal to the calculated value is found. The statement that follows the found constant is executed, after which the select statement terminates. If no constant is found in the select list that matches the calculated value of the select key, control is transferred to the statements following the else word. Else part<оператор_иначе>can be omitted, then if the required constant is not in the selection list, no action will be performed, and the selection operator will simply complete its work.

For example, let’s create a program that, based on the number of the day of the week, displays its name on the screen:

Example program using Case of

Program dni_nedeli;
Var n: byte;
Begin
Readln(n);
Case n of
1: writeln("Monday");
2: writeln("Tuesday");
3: writeln("environment");
4: writeln("Thursday");
5: writeln("Friday");
6: writeln("Saturday");
7: writeln("Sunday");
else writeln("day of the week with number", n,"no");
  end;
end.

It should be remembered that all constants from the selection list must be different.

Any of the select list statements may be preceded by more than one select constant, separated by commas. For example, the following program will display "Yes" when you enter one of the characters "y" or "Y", and "No" when you enter "n" or "N".

Example program using Case of with multiple variables

Var ch: char;
Begin
Readln(ch);
Case ch of
N, n: writeln("Yes ");
Y, y: writeln("No ");
End;
End.

Obviously, the programs discussed above can be written using nested or sequential conditional statements, but in such problems, using the selection statement is simpler. The main difference between a conditional statement and a select statement is that in a conditional statement, the conditions are checked one by one, but in a select statement, the value of the select key directly determines one of the possibilities.







2024 gtavrl.ru.