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
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
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
#include
#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