Условная инструкция if then else обеспечивает единственный выбор

Главная / Программирование /
Visual Basic / Тест 2

Упражнение 1:


Номер 1

Используя полный синтаксис условной инструкции If…Then…Else создать пример нахождения минимального из двух значений а1 и а2

Ответ:

(1) If a1 = a2 Then Min = a2 Else: Min = a1 End If 

(2) If a1 < a2 Then Min = a2 Else Min = a1 End If 

(3) If a1 < a2 Then Min = a1 Else: Min = a2 End If 


Номер 2

Используя краткий синтаксис условной инструкции If...Then...Else создать пример нахождения максимального из двух значений b1 и b2

Ответ:

(1) If b1 > b2 Then Max = b1 Else: Max = b2 End If 

(2) If b1 < b2 Then Max = b2 Else: Max = b1 End If 

(3) If b1 < b2 Then Max = b1 Else Max = b2 End If 


Номер 3

Какое из утверждений является верным?

Ответ:

(1) условная инструкция If…Then…Else обеспечивает единственый выбор 

(2) наличие ElseIf позволяет анализировать дополнительные условия 

(3) Else используется для обработки противоположных ситуаций 

(4) если нужно проверять некоторое условие при наличии другого условия, то используются вложенные инструкции 


Упражнение 2:


Номер 1

Создать массив целых (использовать цикл For…Next) из 40 элементов; m(i) = i^4 + 11 Вычислить сумму первых 28 элементов. Выбрать правильный ответ

Ответ:

(1) 2721819 

(2) 3142370 

(3) 3098566 


Номер 2

Создать массив целых (использовать цикл For…Next) из 30 элементов; m(i) = i^3 + 15. Вычислить сумму первых 18 элементов. ация массива начинается с 0. Выбрать правильный ответ

Ответ:

(1) 23679 

(2) 18981 

(3) 23765 


Номер 3

Создать массив целых (использовать цикл For…Next) из 21 элементов; m(i) = i^2 + 17, i=0,...20 Вычислить сумму последних 15 элементов. Выбрать правильный ответ

Ответ:

(1) 3528 

(2) 3070 

(3) 3112 


Упражнение 3:


Номер 1

Создать массив целых (использовать цикл For…Next) из 21 элемента; m(i) = i^3 + 17. Вычислить сумму первых 16 элементов. Выбрать правильный ответ

Ответ:

(1) 13984 

(2) 14526 

(3) 14672 


Номер 2

Создать масив случайных вещественных чисел m(i) = Rnd(). Использовать инструкцию Randomize(3). (Инструкция Randomize(number) использует некоторое число для инициализации генератора случайных чисел функции Rnd()). Сравнить, равны ли с точностью 0,001 элемент m(1) и число 0.859

Ответ:

(1) False 

(2) True 


Номер 3

Создать массив данных типа String из 20 элементов; m(i) = Chr(97 + i)  Является ли символ "g" элементом массива?

Ответ:

(1) False 

(2) True 


Упражнение 4:


Номер 1

В каком случае используется цикл Do Until…Loop с завершением:

Ответ:

(1) если цикл продолжает повторяться все время, пока некоторое условие остается истинным 

(2) если вместо условия продолжения вычислений формулируется условие его завершения 


Номер 2

Создать массив из 50 элементов m(i) =i  Вычислить сумму его элементов с использованием Do While…Loop и Do Until…Loop

Ответ:

(1) сумма есть 1195 

(2) сумма есть 1275 


Номер 3

Создать массив из 5 целых m(i) = i^2. Вычислить сумму, используя Do While…Loop и Do Until…Loop. Как формулируется условие для Do While и для Do Until?

Ответ:

(1) Do While i > 5 

(2) Do While i < 5 

(3) Do While i < 6 

(4) Do Until i = 5 

(5) Do Until i = 6 


Упражнение 5:


Номер 1

Какие из записей при использовании структуры выбора Select Case являются верными?

Ответ:

(1) Case Is > 0 

(2) Case = 0 


Номер 2

Какие из записей при использовании структуры выбора Select Case являются верными?

Ответ:

(1) Case Is > "c" 

(2) Case [a – d] 

(3) Case RED 


Номер 3

Какие из записей при использовании структуры выбора Select Case являются верными?

Ответ:

(1) Case "Madrid" 

(2) Case Is = 2 

(3) Case 1a 


Упражнение 6:


Номер 1

Отметить, где правильно проводится вызов процедуры Proc1?

Ответ:

(1) If k > 70 Then Proc1 

(2) Call Proc1(20, 15) 


Номер 2

Отметить, где правильно проводится вызов процедуры Proc1?

Ответ:

(1) Call Proc1 21, 32 

(2) Call Proc1 


Упражнение 7:


Номер 1

Какая из процедур Property присваивает значение свойству?

Ответ:

(1) Property Let 

(2) Property Get 


Номер 2

Синтаксис вызова какой из процедур Property представлен здесь:
Переменная = [объект].свойство?

Ответ:

(1) Property Let 

(2) Property Get 


Номер 3

Описание какой из процедур Property дано ниже: 
Property имя_процедуры() As тип_данных

Ответ:

(1) Property Let 

(2) Property Get 


Упражнение 8:


Номер 1

Что возвращает выражение:
Chr(Asc(ch) + 1)  здесь Dim ch As String   ch = "kk"

Ответ:

(1) значение типа Integer, представляющее код символа  

(2) значение типа String, содержащее символ,
соответствующий указанному коду 


Номер 2

Что возвращает выражение:
Chr(Asc(ch1) + 2)   здесь     Dim ch1 As String

Ответ:

(1) значение типа Integer, представляющее код символа 

(2) значение типа String, содержащее символ,
соответствующий указанному коду 


Номер 3

Что возвращает выражение:
Asc(ch1)   здесь    Dim ch1 As String

Ответ:

(1) значение типа Integer, представляющее код символа  

(2) значение типа String, содержащее символ,
соответствующий указанному коду 


Упражнение 9:


Номер 1

Каков должен быть вывод в поле списка элементов массива, элемент которого определяется как: m(j) = Int(Rnd*1000), сформированного  в процедуре For … Next    (j =1 To 25)

Ответ:

(1) List1.List(j) = m(j) 

(2) List1.List(j – 1) = m(j) 

(3) m(j) = List1.List(j) 


Номер 2

Где должны быть присвоены значения переменной х1 для обеспечения старта процедуры Private Sub Timer1_Timer():
Image1.Left = Int(80*Rnd()*x1)
End Sub

Ответ:

(1) в процедуре Timer1_Timer() 

(2) в любой процедуре проекта 


Номер 3

Где соблюден синтаксис использования метки?

Ответ:

(1) Label44 = "Spanien" 

(2) Label44.Caption = "Spanien" 


Упражнение 10:


Номер 1

Функция Fac вычисляет значение факториала числа. Какая инструкция является правильной?

Ответ:

(1) x = Fac(Val(Text1.Text)) 

(2) x = Fac(Text1.Text) 


Номер 2

Может ли инструкция If…Then…Else реализовать:

Ответ:

(1) единственный выбор 

(2) двойной выбор 

(3) множественный выбор 


Номер 3

Куда попадает элемент массива mass(1) после выполнения фрагмента:
For j =1 To 5
List1(1).List(j-1) = mass(j)
…
Next

Ответ:

(1) в нулевой элемент массива списка на 1 позицию списка 

(2) в первый элемент массива списка на 1 позицию списка 

(3) в первый элемент массива списка на нулевую позицию списка 


If-then-else flow diagram
A nested if–then–else flow diagram

In computer science, conditionals (that is, conditional statements, conditional expressions and conditional constructs) are programming language commands for handling decisions. Specifically, conditionals perform different computations or actions depending on whether a programmer-defined Boolean condition evaluates to true or false. In terms of control flow, the decision is always achieved by selectively altering the control flow based on some condition (apart from the case of branch predication).
Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at runtime. Conditional statements are the checkpoints in the programe that determines behaviour according to situation.

Terminology[edit]

In imperative programming languages, the term «conditional statement» is usually used, whereas in functional programming, the terms «conditional expression» or «conditional construct» are preferred, because these terms all have distinct meanings.

If–then(–else)[edit]

«if-then-else» redirects here. For the album, see If Then Else.

The if–then construct (sometimes called if–then–else) is common across many programming languages. Although the syntax varies from language to language, the basic structure (in pseudocode form) looks like this:

If (boolean condition) Then
   (consequent)
Else
   (alternative)
End If

For example:

If stock=0 Then
   message= order new stock
Else
   message= there is stock
End If

In the example code above, the part represented by (boolean condition) constitutes a conditional expression, having intrinsic value (e.g., it may be substituted by either of the values True or False) but having no intrinsic meaning. In contrast, the combination of this expression, the If and Then surrounding it, and the consequent that follows afterward constitute a conditional statement, having intrinsic meaning (e.g., expressing a coherent logical rule) but no intrinsic value.

When an interpreter finds an If, it expects a Boolean condition – for example, x > 0, which means «the variable x contains a number that is greater than zero» – and evaluates that condition. If the condition is true, the statements following the then are executed. Otherwise, the execution continues in the following branch – either in the else block (which is usually optional), or if there is no else branch, then after the end If.

After either branch has been executed, control returns to the point after the end If.

History and development[edit]

In early programming languages, especially some dialects of BASIC in the 1980s home computers, an if–then statement could only contain GOTO statements (equivalent to a branch instruction). This led to a hard-to-read style of programming known as spaghetti programming, with programs in this style called spaghetti code. As a result, structured programming, which allows (virtually) arbitrary statements to be put in statement blocks inside an if statement, gained in popularity, until it became the norm even in most BASIC programming circles. Such mechanisms and principles were based on the older but more advanced ALGOL family of languages, and ALGOL-like languages such as Pascal and Modula-2 influenced modern BASIC variants for many years. While it is possible while using only GOTO statements in if–then statements to write programs that are not spaghetti code and are just as well structured and readable as programs written in a structured programming language, structured programming makes this easier and enforces it. Structured if–then–else statements like the example above are one of the key elements of structured programming, and they are present in most popular high-level programming languages such as C, Java, JavaScript and Visual Basic .

The «dangling else» problem[edit]

The else keyword is made to target a specific if–then statement preceding it, but for nested if–then statements, classic programming languages such as ALGOL 60 struggled to define which specific statement to target. Without clear boundaries for which statement is which, an else keyword could target any preceding if–then statement in the nest, as parsed.

if a then if b then s else s2

can be parsed as

if a then (if b then s) else s2

or

if a then (if b then s else s2)

depending on whether the else is associated with the first if or second if. This is known as the dangling else problem, and is resolved in various ways, depending on the language (commonly via the end if statement or {...} brackets).

Else if[edit]

By using else if, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped.

if condition then
   -- statements
elseif condition then
   -- more statements
elseif condition then
   -- more statements;
...
else
   -- other statements;
end if;

For example, for a shop offering as much as a 30% discount for an item:

if discount < 11% then
   print (you have to pay $30)
elseif discount<21% then
   print (you have to pay $20)
elseif discount<31% then
   print (you have to pay $10)
end if;

In the example above, if the discount is 10%, then the first if statement will be evaluated as true and «you have to pay $30» will be printed out. All other statements below that first if statement will be skipped.

The elseif statement, in the Ada language for example, is simply syntactic sugar for else followed by if. In Ada, the difference is that only one end if is needed, if one uses elseif instead of else followed by if. PHP uses the elseif keyword[1] both for its curly brackets or colon syntaxes. Perl provides the keyword elsif to avoid the large number of braces that would be required by multiple if and else statements. Python uses the special keyword elif because structure is denoted by indentation rather than braces, so a repeated use of else and if would require increased indentation after every condition. Some implementations of BASIC, such as Visual Basic,[2] use ElseIf too. Similarly, the earlier UNIX shells (later gathered up to the POSIX shell syntax[3]) use elif too, but giving the choice of delimiting with spaces, line breaks, or both.

However, in many languages more directly descended from Algol, such as Simula, Pascal, BCPL and C, this special syntax for the else if construct is not present, nor is it present in the many syntactical derivatives of C, such as Java, ECMAScript, and so on. This works because in these languages, any single statement (in this case if cond…) can follow a conditional without being enclosed in a block.

This design choice has a slight «cost». Each else if branch effectively adds an extra nesting level. This complicates the job for the compiler (or the people who write the compiler), because the compiler must analyse and implement arbitrarily long else if chains recursively.

If all terms in the sequence of conditionals are testing the value of a single expression (e.g., if x=0else if x=1else if x=2…), an alternative is the switch statement, also called case-statement or select-statement. Conversely, in languages that do not have a switch statement, these can be produced by a sequence of else if statements.

If–then–else expressions[edit]

Many languages support if expressions, which are similar to if statements, but return a value as a result. Thus, they are true expressions (which evaluate to a value), not statements (which may not be permitted in the context of a value).

Algol family[edit]

ALGOL 60 and some other members of the ALGOL family allow if–then–else as an expression:

  myvariable := if x > 20 then 1 else 2

Lisp dialects[edit]

In dialects of Lisp – Scheme, Racket and Common Lisp – the first of which was inspired to a great extent by ALGOL:

;; Scheme
(define myvariable (if (> x 12) 1 2))   ; Assigns 'myvariable' to 1 or 2, depending on the value of 'x'
;; Common Lisp
(let ((x 10))
  (setq myvariable (if (> x 12) 2 4)))  ; Assigns 'myvariable' to 2

Haskell[edit]

In Haskell 98, there is only an if expression, no if statement, and the else part is compulsory, as every expression must have some value.[4] Logic that would be expressed with conditionals in other languages is usually expressed with pattern matching in recursive functions.

Because Haskell is lazy, it is possible to write control structures, such as if, as ordinary expressions; the lazy evaluation means that an if function can evaluate only the condition and proper branch (where a strict language would evaluate all three). It can be written like this:[5]

if' :: Bool -> a -> a -> a
if' True x _ = x
if' False _ y = y

C-like languages[edit]

C and C-like languages have a special ternary operator (?:) for conditional expressions with a function that may be described by a template like this:

condition ? evaluated-when-true : evaluated-when-false

This means that it can be inlined into expressions, unlike if-statements, in C-like languages:

my_variable = x > 10 ? "foo" : "bar";  // In C-like languages

which can be compared to the Algol-family if–then–else expressions (in contrast to a statement) (and similar in Ruby and Scala, among others).

To accomplish the same using an if-statement, this would take more than one line of code (under typical layout conventions), and require mentioning «my_variable» twice:

if (x > 10)
    my_variable = "foo";
else
    my_variable = "bar";

Some argue that the explicit if/then statement is easier to read and that it may compile to more efficient code than the ternary operator,[6] while others argue that concise expressions are easier to read than statements spread over several lines containing repetition.

Small Basic[edit]

x = TextWindow.ReadNumber()
If (x > 10) Then
    TextWindow.WriteLine("My variable is named 'foo'.")
Else
    TextWindow.WriteLine("My variable is named 'bar'.")
EndIf

First, when the user runs the program, a cursor appears waiting for the reader to type a number. If that number is greater than 10, the text «My variable is named ‘foo’.» is displayed on the screen. If the number is smaller than 10, then the message «My variable is named ‘bar’.» is printed on the screen.

Visual Basic[edit]

In Visual Basic and some other languages, a function called IIf is provided, which can be used as a conditional expression. However, it does not behave like a true conditional expression, because both the true and false branches are always evaluated; it is just that the result of one of them is thrown away, while the result of the other is returned by the IIf function.

Tcl[edit]

Main article: Tcl

In Tcl if is not a keyword but a function (in Tcl known as command or proc). For example

if {$x > 10} {
   puts "Foo!"
}

invokes a function named if passing 2 arguments: The first one being the condition and the second one being the true branch. Both arguments are passed as strings (in Tcl everything within curly brackets is a string).

In the above example the condition is not evaluated before calling the function. Instead, the implementation of the if function receives the condition as a string value and is responsible to evaluate this string as an expression in the callers scope.[7]

Such a behavior is possible by using uplevel and expr commands:

Uplevel makes it possible to implement new control constructs as Tcl procedures (for example, uplevel could be used to implement the while construct as a Tcl procedure).[8]

Because if is actually a function it also returns a value:

The return value from the command is the result of the body script that was executed, or an empty string if none of the expressions was non-zero and there was no bodyN.[9]

Rust[edit]

In Rust, if is always an expression. It evaluates to the value of whichever branch is executed, or to the unit type () if no branch is executed. If a branch does not provide a return value, it evaluates to () by default. To ensure the if expression’s type is known at compile time, each branch must evaluate to a value of the same type. For this reason, an else branch is effectively compulsory unless the other branches evaluate to (), because an if without an else can always evaluate to () by default.[10]

// Assign my_variable some value, depending on the value of x
let my_variable = if x > 20 {
    1
} else {
    2
};

// This variant will not compile because 1 and () have different types
let my_variable = if x > 20 {
    1
};

// Values can be omitted when not needed
if x > 20 {
    println!("x is greater than 20");
}

Arithmetic if[edit]

Up to Fortran 77, the language Fortran has an «arithmetic if» statement which is halfway between a computed IF and a case statement, based on the trichotomy x < 0, x = 0, x > 0. This was the earliest conditional statement in Fortran:[11]

IF (e) label1, label2, label3

Where e is any numeric expression (not necessarily an integer); this is equivalent to

IF (e .LT. 0) GOTO label1
IF (e .EQ. 0) GOTO label2
GOTO label3

Because this arithmetic IF is equivalent to multiple GOTO statements that could jump to anywhere, it is considered to be an unstructured control statement, and should not be used if more structured statements can be used. In practice it has been observed that most arithmetic IF statements referenced the following statement with one or two of the labels.

This was the only conditional control statement in the original implementation of Fortran on the IBM 704 computer. On that computer the test-and-branch op-code had three addresses for those three states. Other computers would have «flag» registers such as positive, zero, negative, even, overflow, carry, associated with the last arithmetic operations and would use instructions such as ‘Branch if accumulator negative’ then ‘Branch if accumulator zero’ or similar. Note that the expression is evaluated once only, and in cases such as integer arithmetic where overflow may occur, the overflow or carry flags would be considered also.

Object-oriented implementation in Smalltalk[edit]

In contrast to other languages, in Smalltalk the conditional statement is not a language construct but defined in the class Boolean as an abstract method that takes two parameters, both closures. Boolean has two subclasses, True and False, which both define the method, True executing the first closure only, False executing the second closure only.[12]

var = condition 
    ifTrue: [ 'foo' ]
    ifFalse: [ 'bar' ]

JavaScript[edit]

JavaScript uses if-else statements similar to those in C languages. A Boolean value is accepted within parentheses between the reserved if keyword and a left curly bracket.

if (Math.random() < 0.5) {
  console.log("You got Heads!");
} else {
  console.log("You got Tails!");
}

The above example takes the conditional of Math.random() < 0.5 which outputs true if a random float value between 0 and 1 is greater than 0.5. The statement uses it to randomly choose between outputting You got Heads! or You got Tails! to the console. Else and else-if statements can also be chained after the curly bracket of the statement preceding it as many times as necessary, as shown below:

var x = Math.random();
if (x < 1/3) {
  console.log("One person won!");
} else if (x < 2/3) {
  console.log("Two people won!");
} else {
  console.log("It's a three-way tie!");
}

Lambda calculus[edit]

In Lambda calculus, the concept of an if-then-else conditional can be expressed using the following expressions:

true = λx. λy. x
false = λx. λy. y
ifThenElse = (λc. λx. λy. (c x y))
  1. true takes up to two arguments and once both are provided (see currying), it returns the first argument given.
  2. false takes up to two arguments and once both are provided(see currying), it returns the second argument given.
  3. ifThenElse takes up to three arguments and once all are provided, it passes both second and third argument to the first argument(which is a function that given two arguments, and produces a result). We expect ifThenElse to only take true or false as an argument, both of which project the given two arguments to their preferred single argument, which is then returned.

note: if ifThenElse is passed two functions as the left and right conditionals; it is necessary to also pass an empty tuple () to the result of ifThenElse in order to actually call the chosen function, otherwise ifThenElse will just return the function object without getting called.

In a system where numbers can be used without definition (like Lisp, Traditional paper math, so on), the above can be expressed as a single closure below:

 ((λtrue. λfalse. λifThenElse.
     (ifThenElse true 2 3)
 )(λx. λy. x)(λx. λy. y)(λc. λl. λr. c l r))

Here, true, false, and ifThenElse are bound to their respective definitions which are passed to their scope at the end of their block.

A working JavaScript analogy(using only functions of single variable for rigor) to this is as follows:

 var computationResult = ((_true => _false => _ifThenElse => 
     _ifThenElse(_true)(2)(3) 
 )(x => y => x)(x => y => y)(c => x => y => c(x)(y)));

The code above with multivariable functions looks like this:

 var computationResult = ((_true, _false, _ifThenElse) =>
     _ifThenElse(_true, 2, 3)
 )((x, y) => x, (x, y) => y, (c, x, y) => c(x, y));

Another version of the earlier example without a system where numbers are assumed is below.

The first example shows the first branch being taken, while second example shows the second branch being taken.

 ((λtrue. λfalse. λifThenElse.
     (ifThenElse true (λFirstBranch. FirstBranch) (λSecondBranch. SecondBranch))
 )(λx. λy. x)(λx. λy. y)(λc. λl. λr. c l r))

 ((λtrue. λfalse. λifThenElse.
     (ifThenElse false (λFirstBranch. FirstBranch) (λSecondBranch. SecondBranch))
 )(λx. λy. x)(λx. λy. y)(λc. λl. λr. c l r))

Smalltalk uses a similar idea for its true and false representations, with True and False being singleton objects that respond to messages ifTrue/ifFalse differently.

Haskell used to use this exact model for its Boolean type, but at the time of writing, most Haskell programs use syntactic sugar «if a then b else c» construct which unlike ifThenElse does not compose unless
either wrapped in another function or re-implemented as shown in The Haskell section of this page.

Case and switch statements[edit]

Switch statements (in some languages, case statements or multiway branches) compare a given value with specified constants and take action according to the first constant to match. There is usually a provision for a default action (‘else’,’otherwise’) to be taken if no match succeeds. Switch statements can allow compiler optimizations, such as lookup tables. In dynamic languages, the cases may not be limited to constant expressions, and might extend to pattern matching, as in the shell script example on the right, where the ‘*)’ implements the default case as a regular expression matching any string.

Pascal: C: Shell script:
case someChar of
  'a': actionOnA;
  'x': actionOnX;
  'y','z':actionOnYandZ;
  else actionOnNoMatch;
end;
switch (someChar) {
  case 'a': actionOnA; break;
  case 'x': actionOnX; break;
  case 'y':
  case 'z': actionOnYandZ; break;
  default: actionOnNoMatch;
}
case $someChar in 
   a)    actionOnA; ;;
   x)    actionOnX; ;;
   [yz]) actionOnYandZ; ;;
  *)     actionOnNoMatch  ;;
esac

Pattern matching[edit]

Pattern matching may be seen as an alternative to both if–then–else, and case statements. It is available in many programming languages with functional programming features, such as Wolfram Language, ML and many others. Here is a simple example written in the OCaml language:

match fruit with
| "apple" -> cook pie
| "coconut" -> cook dango_mochi
| "banana" -> mix;;

The power of pattern matching is the ability to concisely match not only actions but also values to patterns of data. Here is an example written in Haskell which illustrates both of these features:

map _ []      = []
map f (h : t) = f h : map f t

This code defines a function map, which applies the first argument (a function) to each of the elements of the second argument (a list), and returns the resulting list. The two lines are the two definitions of the function for the two kinds of arguments possible in this case – one where the list is empty (just return an empty list) and the other case where the list is not empty.

Pattern matching is not strictly speaking always a choice construct, because it is possible in Haskell to write only one alternative, which is guaranteed to always be matched – in this situation, it is not being used as a choice construct, but simply as a way to bind names to values. However, it is frequently used as a choice construct in the languages in which it is available.

Hash-based conditionals[edit]

In programming languages that have associative arrays or comparable data structures, such as Python, Perl, PHP or Objective-C, it is idiomatic to use them to implement conditional assignment.[13]

pet = input("Enter the type of pet you want to name: ")
known_pets = {
    "Dog": "Fido",
    "Cat": "Meowsles",
    "Bird": "Tweety",
}
my_name = known_pets[pet]

In languages that have anonymous functions or that allow a programmer to assign a named function to a variable reference, conditional flow can be implemented by using a hash as a dispatch table.

Predication[edit]

An alternative to conditional branch instructions is predication. Predication is an architectural feature that enables instructions to be conditionally executed instead of modifying the control flow.

Choice system cross reference[edit]

This table refers to the most recent language specification of each language. For languages that do not have a specification, the latest officially released implementation is referred to.

Programming language Structured if switch–select–case Arithmetic if Pattern matching[A]
then else else–if
Ada Yes Yes Yes Yes No No
APL No Yes Yes Yes No No
Bash shell Yes Yes Yes Yes No Yes
C, C++ No Yes unneeded[B][C] Fall-through No No
C# No Yes Unneeded[B][C] Yes No No
COBOL Yes Yes Unneeded[C] Yes No No
Eiffel Yes Yes Yes Yes No No
F# Yes Yes Yes Unneeded[D] No Yes
Fortran 90 Yes Yes Yes Yes Yes[G] No
Go No Yes Unneeded[C] Yes No No
Haskell Yes Needed Unneeded[C] Yes, but unneeded[D] No Yes
Java No Yes Unneeded[C] Fall-through[14] No No
ECMAScript (JavaScript) No Yes Unneeded[C] Fall-through[15] No No
Mathematica No Yes Yes Yes No Yes
Oberon Yes Yes Yes Yes No No
Perl No Yes Yes Yes No No
PHP No Yes Yes Fall-through No No
Pascal, Object Pascal (Delphi) Yes Yes Unneeded Yes No No
Python No Yes Yes No No Yes
QuickBASIC Yes Yes Yes Yes No No
Ruby Yes Yes Yes Yes No Yes[H]
Rust No Yes Yes Unneeded No Yes
Scala No Yes Unneeded[C] Fall-through[citation needed] No Yes
SQL Yes[F] Yes Yes Yes[F] No No
Swift No Yes Yes Yes No Yes
Tcl No Yes Yes Yes No Yes
Visual Basic, classic Yes Yes Yes Yes No No
Visual Basic .NET Yes Yes Yes Yes No No
Windows PowerShell No Yes Yes Fall-through No No
  1. ^ This refers to pattern matching as a distinct conditional construct in the programming language – as opposed to mere string pattern matching support, such as regular expression support.
  2. 1 2 An #ELIF directive is used in the preprocessor sub-language that is used to modify the code before compilation; and to include other files.
  3. 1 2 3 4 5 6 The often-encountered else if in the C family of languages, and in COBOL and Haskell, is not a language feature but a set of nested and independent if then else statements combined with a particular source code layout. However, this also means that a distinct else–if construct is not really needed in these languages.
  4. 1 2 In Haskell and F#, a separate constant choice construct is unneeded, because the same task can be done with pattern matching.
  5. ^ In a Ruby case construct, regular expression matching is among the conditional flow-control alternatives available. For an example, see this Stack Overflow question.
  6. 1 2 SQL has two similar constructs that fulfill both roles, both introduced in SQL-92. A «searched CASE» expression CASE WHEN cond1 THEN expr1 WHEN cond2 THEN expr2 [...] ELSE exprDflt END works like if ... else if ... else, whereas a «simple CASE» expression: CASE expr WHEN val1 THEN expr1 [...] ELSE exprDflt END works like a switch statement. For details and examples see Case (SQL).
  7. ^ Arithmetic if is obsolescent in Fortran 90.
  8. ^ Pattern matching was added in Ruby 3.0.[16] Some pattern matching constructs are still experimental.

See also[edit]

  • Branch (computer science)
  • Conditional compilation
  • Dynamic dispatch for another way to make execution choices
  • McCarthy Formalism for history and historical references
  • Named condition
  • Relational operator
  • Test (Unix)
  • Yoda conditions
  • Conditional move

References[edit]

  1. ^ PHP elseif syntax
  2. ^ Visual Basic ElseIf syntax
  3. ^ POSIX standard shell syntax
  4. ^ Haskell 98 Language and Libraries: The Revised Report
  5. ^ «If-then-else Proposal on HaskellWiki»
  6. ^ «Efficient C Tips #6 – Don’t use the ternary operator « Stack Overflow». Embeddedgurus.com. 2009-02-18. Retrieved 2012-09-07.
  7. ^ «New Control Structures». Tcler’s wiki. Retrieved August 21, 2020.
  8. ^ «uplevel manual page». www.tcl.tk. Retrieved August 21, 2020.
  9. ^ «if manual page». www.tcl.tk. Retrieved August 21, 2020.
  10. ^ «If and if let expressions». Retrieved November 1, 2020.
  11. ^ «American National Standard Programming Language FORTRAN». 1978-04-03. Archived from the original on 2007-10-11. Retrieved 2007-09-09.
  12. ^ «VisualWorks: Conditional Processing». 2006-12-16. Archived from the original on 2007-10-22. Retrieved 2007-09-09.
  13. ^ «Pythonic way to implement switch/case statements». Archived from the original on 2015-01-20. Retrieved 2015-01-19.
  14. ^ Java.sun.com, Java Language Specification, 3rd Edition.
  15. ^ Ecma-international.org Archived 2015-04-12 at the Wayback Machine ECMAScript Language Specification, 5th Edition.
  16. ^ «Pattern Matching». Documentation for Ruby 3.0.

External links[edit]

Look up then or else in Wiktionary, the free dictionary.

  • Media related to Conditional (computer programming) at Wikimedia Commons
  • IF NOT (ActionScript 3.0) video

Программирование требует от пользователя определенных познаний в сфере выбранного языка. Большинство из них поддерживает использование так называемых условных операторов. Они в той или иной форме присутствуют во всех ЯП.

Далее предстоит изучить конструкцию the if else then и условные операторы. Эта информация пригодится как новичкам, так и более опытным разработчикам. Она должна быть усвоена каждым, кто планирует заниматься созданием программного обеспечения и игр. Примеры будут приведены на the Pascal и the JavaScript.

Условные операторы

Условный оператор – основа любого языка разработки. С его помощью значение некоторого выражения принимается за определение дальнейшего поведения приложения. Через the operator происходит выбор действия из нескольких предложенных.

В основе работы оператора (не только состоящего из IF) заложена булева логика. Она подразумевает сведение любых утверждений к двум вариантам:

  • истина (the true);
  • ложь (the false).

Если условие истинно, приложение отправляться работать по одному алгоритму, если ложно – по другому. Это приводит к тому, что в каждый момент времени программное обеспечение выбирает алгоритм из двух направлений. Существуют более сложные условия. Они базируются на последовательном прохождении элементарных двоичных условий.

Разновидности

Условных операторов много. Каждый язык поддерживает их в той или иной степени. Основными конструкциями выступают ветвления. Они могут быть:

  • постфиксными;
  • тернарными;
  • с одной веткой;
  • с двумя ветвями;
  • с поддержкой нескольких ветвей (if elseif else или if else then);
  • множественного выбора – switch.

Отдельно выделяются циклы:

  • while;
  • for;
  • foreach;
  • бесконечные.

Особое внимание необходимо уделить ветвлению. Оно является основой разработки практически любого программного обеспечения.

Перед изучением if else then необходимо рассмотреть более простые варианты ветвлений. В противном случае разработчик рискует запутаться и получить «на выходе» совершенно непредсказуемый результат.

Конструкция «с одной веткой» – элементарный вариант ветвления. Заданная операция будет обрабатываться, если соблюдено то или иное условие. В случае с the JavaScript форма представления ветвления будет следующей:

Сначала здесь задается ключевое слово IF (без else и then). Далее прописывается условие (condition), а в фигурных скобках указывается реализуемый алгоритм. Блок выполняется, если результат condition становится истиной. В противном случае управление переходит к следующему написанному в программном обеспечении фрагменту.

В the Pascal соответствующий вариант рассматривается как неполный условный оператор. Его блок схема имеет следующую форму реализации:

Данный вариант является элементарным. Он помогает составлять простейшие задачи. В сложных проектах встречается достаточно редко. Там программисты стараются использовать цикл и другие условные операторы.

Две ветви

Следующий вариант тоже является достаточно распространенным у большинства языков. Это двойное ветвление. В разных ЯП отмечается по-разному. В основном:

  • If условие else;
  • If условие then.

Соответствующая конструкция поддерживает несколько блоков кода:

  • если условие является the true, выполняется алгоритм1;
  • в противном случае обрабатывается алгоритм2.

В the Pascal if then – это тоже неполное ветвление. Примеры:

Здесь, если введенное значение переменной a = 7, на экране появится приветствие. В противном случае ничего не происходит.

В данном фрагменте на экране при соблюдении указанного условия в консоль будет выведено не только приветствие, но и прощание. Это связано с тем, что writeln(‘До встречи’) не имеет отношения к ветвлению.

Примеры реализации в the JavaScript конструкции if then будут выглядеть несколько иначе. Общая форма записи:

Наглядный пример:

Чтобы увидеть, как работает данный фрагмент, значение переменной рекомендуется сначала установить на нечетное (здесь оно по умолчанию = 5), а затем – поменять на четное. На экране будет появляться запись, характеризующая тип введенного числа.

Операторные скобки

В the Pascal, работая с записями типа if else then необходимо использовать операторные скобки. Они включают в себя:

  • begin;
  • end if.

Они помогают грамотно использовать ветвление. Ранее приведенный пример будет работать корректно только при наличии операторных скобок. Они указывают на начало и конец алгоритмов, относящихся к тому или иному оператору.

В приведенном выше фрагменте при if a = 10 then… ничего не произойдет. Если указать a = 7, на дисплее появится и приветствие, и прощание.

Составные условия

В the Pascal могут использоваться составные (сложные) условия. Такой подход встречается и в других языках разработки. Чтобы сформировать составное условие, необходимо применять:

  • and – составное условие истинно, когда все его простые составляющие являются true;
  • or – составное условие истинно, когда таким является хотя бы одно его составное условие.

Вот пример:

Он помогает отыскать максимальное среди трех чисел. Аналогичным образом составные конструкции используются в других языках разработки.

Множественное ветвление

The JavaScript и The Pascal, а также другие ЯП поддерживают множественное ветвление. Такой вариант иногда называется «полным оператором». Он подразумевает создание инструкций с несколькими «ветками». Встречается, когда требуется проверить разнообразные условия.

В the JS форма записи будет такой:

Соответствующий фрагмент if else then работает так:

  1. Сначала проверяется condition1. Если оно истинно, реализовывается первый блок кода.
  2. При the condition1 = false происходит проверка condition2. Присвоенный ему алгоритм работает, когда результат расчетов = true. В противном случае программа переходит к condition3 и так далее.
  3. Если все условия – это ложь, система будет реализовывать последний написанный блок.

В the Pascal if else then выглядит схематично так:

Некоторые разработчики называют соответствующую концепцию двойным ветвлением. Пример:

В соответствующем операторе if then перед записью …else…точка с запятой не ставится. Зато программисту придется использовать операторные скобки.

Тернарный оператор и JS

Тернарный оператор – это выражение, возвращающее то или иное значение. Сокращенная форма записи then else. В the JavaScript используется следующий вариант реализации:

В случае с Pascal достаточно использовать сокращенную форму записи условного оператора. В приведенном выше примере поддерживаются три операнда:

  • первое выражение;
  • второе выражение;
  • проверяемое системой условие.

Для разделения условия и выражений необходимо применять символы «?», «:». Если condition = true, выполняется expression1, в противном случае – expression2.

Работа со switch

Оператор if then в большинстве языков разработки очень легко использовать. Кроме обычного ветвления можно задействовать выбор варианта из нескольких предложенных. Для этого используется конструкция switch.

Выбор алгоритма действий базируется на основании полного совпадения результатов расчетов, записанный в case. В случае с JS форма записи будет такой:

Раздел default не является обязательным. Он встречается тогда, когда необходимо указать алгоритм, реализующийся, если ни одно case не обнаружено. Это своеобразная замена if then.

Можно заметить, что в записи поддерживается break. Данный компонент тоже не является обязательным. Он используется в switch для непосредственного прерывания. После его обработки управление переходит к инструкциям, написанным после условного оператора. В противном случае может образоваться цикл, который приведет к неправильной работе кода.

Здесь можно увидеть больше примеров реализации изученной темы на Pascal. Досконально условные операторы и их особенности помогут рассмотреть специальные компьютерные дистанционные курсы.

Хотите освоить современную IT-специальность? Огромный выбор курсов по востребованным IT-направлениям есть в Otus! 

Используется для
программирования полной формы ветвления.
Если логическое выражение принимает
значение True
– Истина
,
выполняется
один блок операторов,
в противном случае (значение логического
выражения False
– Ложь) –
второй.
Можно
использовать однострочный или блочный
синтаксис.

Однострочный
синтаксис:

If
<условие>
Then
<оператор>
Else
<оператор>

Блочный синтаксис:

If
<условие>
Then

<Блок операторов>

Else

<Блок операторов>

End
If

Запрограммируем
следующие фрагменты графической схемы
алгоритма:

If a
> 5 Then b = b + a Else b = b – a

или

If
a > 5 Then

b = b + a

Else

b
= b — a

End If

Первый вариант
предпочтительнее.

If x>0 Then

y=x+1

f=1

Else

f=2

End if

или If
x>0
Then
y=x+1:
f=1
Else
f=2

Первый вариант
предпочтительнее.

4.3. Условный оператор If…Then…ElseIf

Условный оператор
может содержать другие условные
операторы. В этом случае имеет место
так называемое вложенное
ветвление
.
Для его программирования могут
использоваться операторы If  Then
и
If  Then  Else.
Если первый блок ветки Else
является вложенным ветвлением, то
рациональнее использовать разновидность
условного оператора IfThenElseIf.

Синтаксис:

if
<условие_1>
Then

<Блок
операторов_1>

ElseIf
<условие_2>
Then

<Блок
операторов_2>

ElseIf
<условие_3>
Then

<Блок
операторов_3>

[Else

<Блок
операторов>]

End
If

Например:

If
g > 10 Then

z=5

ElseIf g<5 Then

z=1

End
If

If
x > 5 Then

y = x + 2

f =1

ElseIf x < -10 Then

y = 2 * x

f=2

Else

y = x — 5

f=3

End
If

Следующий фрагмент
блок-схемы может быть запрограммирован
только с помощью оператора IfThenElse

4.4. Примеры использования оператора условного перехода If

Пример 4.1.
Вычислить значение функции

y=

Результаты
вычислений и номер формулы вывести в
окне сообщений
.

Таблица
соответствия переменных

Обозначение

в задании

Имя

переменной

Тип

переменной

Комментарий

y

x

y

x

f

Вещественный

Вещественный

Целый

Значение
функции

Исходное
данное

Номер
формулы

Анализ исходных
данных:

Тесты:

теста

Значение

№ формулы

Комментарий

x

y

1.

2.

3.

1

10

15

0

9

31

2

2

1

x<10

x=10

x>10

Графическая схема
алгоритма представлена на рис.4.1.,
результаты тестирования программы –
на рис.4.2.

Sub
Pr4_1()

Dim
y
As
Single,
x
As
Single

Dim
f
As
Byte

‘Ввод исходных
данных

x= InputBox(«Введи
значение х»)

‘Выполнение
расчетов и вывод результатов

If x > 10 Then y
= 2 * x + 1: f = 1 Else y = x — 1: f = 2

MsgBox «При
х=» & x & Chr(13) & _

«Значение
y =» & y & Chr(13) & _

«Номер
формулы вычисления — » & f, , «Пример»

EndSub

Пример 4.2.
Проанализировать
результаты сдачи учащимися экзаменов
по физике, математике и русскому языку.
Вывести сообщения:

если
средний балл >4 – “отлично”

3<= ср. балл
<=4 – “удовлетворительно”

средний
балл <3 – “плохо”

Результат анализа
вывести в окне сообщения.

Таблица соответствия
переменных

Обозначение

в задании

Имя

переменной

Тип

переменной

Комментарий

Оценка по
физике

Оценка по
математике

Оценка по
русскому языку

Средний
балл

fiz

mat

rus

Sr

S

P

целый

целый

целый

вещественный

строковый

Integer

Int

Исходное
данное

Исходное
данное

Исходное
данное

Промежуточное
значение

Сообщение

Рабочая
переменная для вывода информационного
значкая в окне сообщения

Анализ исходных
данных:

Имя

переменной

Недопустимые

значения

Ситуация,
при которой переменная получает
недопустимое значение

fiz, mat, rus

<1
или>5

ввод
данных

Анализ
значений переменнойSr:

теста

Значение

Комментарий

fiz

mat

rus

Sr

1.

2.

3.

4.

5.

6.

7.

8.

0

5

3

5

4

3

3

3

5

6

4

4

4

4

3

2

4

5

-1

5

4

4

3

3

4,7

4,0

3,7

3

2,7

Введено
некорректное значение

Введено
некорректное значение

Введено
некорректное значение

Отлично

Удовлетворительно

Удовлетворительно

Удовлетворительно

Плохо

Графическая схема алгоритма
представлена на рис.4.3., а результаты
тестирования – на рис.4.4.

Sub Pr4_2()

Dim fiz
As Byte,
mat As
Byte, rus
As Byte

Dim Sr
As Single,
S As
String, P
As Integer

‘Ввод и проверка исходных данных

fiz = InputBox(«Введи оценку по физике»)

mat = InputBox(«Введи оценку по
математике»)

rus = InputBox(«Введи оценку по русскому
языку»)

If (fiz < 1 Or fiz > 5) Or (mat <
1 Or mat > 5) Or (rus < 1 Or rus > 5) Then

MsgBox «Введено некорректное
значение» & Chr(13) & _

«оценка по физике — » &
fiz & Chr(13) & _

«оценка по математике — »
& mat & Chr(13) & _

«оценка по русскому языку
— » & rus

Else

‘Выполнение расчетов

Sr = (fiz
+
mat + rus)
/ 3

If Sr
> 4
Then
P – значение
константы для вывода

S = «Отлично»:
P = vbExclamation
‘ информ. значка в окне

ElseIf Sr < 3 Then
сообщения

S = «Плохо«:
P = vbCritical

Else

S = «Удовлетворительно«:
P = vbQuestion

End If

‘Вывод результатов. Для вывода среднего
значения используется формат

MsgBox S
&
Chr(10) & «Средний
балл = » &
Sr &
_

Chr(13) & «Оценка по физике
— » & fiz & _

Chr(13) & «Оценка по
математике — » & mat & _

Chr(13) & «Оценка по русскому
языку — » & rus,
P

End If

End Sub

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]

  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #

6.1 Конструкция If . . . Then
6.2 Конструкция If . . . Then . . . Else 
6.3 Конструкция Select Case


Управляющие структуры позволяют управлять последовательностью выполнения программы. Без операторов управления все операторы программы будут выполняться слева направо и сверху вниз. Однако иногда требуется многократно выполнять некоторый набор инструкций автоматически, либо решить задачу по-другому в зависимости от значения переменных или параметров, заданных пользователем во время выполнения. Для этого служат конструкции управления и циклы.

VBA поддерживает следующие конструкции принятия решений:

If . . . Then

If . . . Then . . . Else

Select Case

6.1 Конструкция If . . . Then

Конструкция If . . . Then применяется, когда необходимо выполнить один или группу операторов в зависимости от некоторого условия. Синтаксис этой конструкции позволяет задавать ее в одной строке или в нескольких строках программы:

If условие Then выражение
If условие Then
выражение
End If

Обычно условие является простым сравнением, но оно может быть любым выражением с вычисляемым значением. Это значение интерпретируется как False (Ложь), если оно нулевое, а любое ненулевое рассматривается как True (Истина). Если условие истинно, то выполняются все выражения, стоящие после ключевого слова Then. Для условного выполнения одного оператора можно использовать как синтаксис для одной строки, так и синтаксис для нескольких строк (блоковую конструкцию).

Следующие два оператора эквивалентны:

If anyDate < Now Then anyDate = Now
If anyDate < Now Then
anyDate = Now 
End If

Заметим, что синтаксис оператора If . . . Then для одной строки не использует оператор End If. Чтобы выполнить последовательность операторов, если условие истинно, следует использовать блоковую конструкцию If . . . Then . . . End If.

If anyDate < Now Then
anyDate = Now
Timer.Enabled = False   ' Запретить таймер. 
End If

Если условие ложно, то операторы после ключевого слова Then не выполняется, а управление передается на следующую строку (или строку после оператора End If в блочной конструкции).

6.2 Конструкция If . . . Then . . . Else

определяет несколько блоков операторов, один из которых будет выполняться в зависимости от условия:

If условие1 Then
выражение1
ElseIf условие2 Then
выражение2
. . . 
Else
выражение-n
End If

При выполнении сначала проверяется условие1. Если оно ложно, VBA проверяет следующее условие2 и т. д., пока не найдет истинного условия. Найдя его, VBA выполняет соответствующий блок операторов и затем передает управление инструкции, следующей за оператором End if. В данную конструкцию можно включить блок оператора Else, который VBA выполняет, если не выполнено ни одно из условий.

Конструкция If . . . Then . . . ElseIf в действительности всего лишь специальный случай конструкции If . . . Then . . . Else. Заметим, что в данной конструкции может быть любое число блоков ElseIf, или даже ни одного. Блок Else можно включать независимо от присутствия или, наоборот, отсутствия блоков ElseIf.

Рассмотрим пример вычисления функции

Sub пример1()
Dim a As Single, b As Single, x As Single
Dim z As Double
Call read("A1", a)
Call read("B1", b)
Let x = CSng(InputBox("введи x", "Ввод данных", 0))
If x <= a Then
z = Sin(x)
ElseIf x >= b Then
z = Tan(x)
Else: z = Cos(x)
End If
Call out("C1", z)
End Sub

Заметим, что можно добавить любое число блоков Elself в конструкцию If . . . Then. Однако количество блоков Elself может стать настолько большим, что конструкция If . . . Then станет очень громоздкой и неудобной. В подобной ситуации следует применять другую конструкцию принятия решения — Select Case.

6.3 Конструкция Select Case

Конструкция Select Case является альтернативой конструкции If . . . Then . . . Else в случае выполнения блока, состоящего из большого набора операторов. Конструкция Select Case предоставляет возможность, похожую на возможность конструкции If . . . Then . . . Else, но в отличие от нее она делает код более читаемым при наличии нескольких вариантов выбора.

Конструкция Select Case работает с единственным проверяемым выражением, которое вычисляется один раз при входе в эту конструкцию. Затем VBA сравнивает полученный результат со значениями, задаваемыми в операторах Case конструкции. Если найдено совпадение, выполняется блок операторов, ассоциированный с оператором Case:

Select Case проверяемое_выражение 
[Case список_выражений1 
[блок_операторов1]] 
[Case список_выражений2 
[блок_операторов2]]
. . . 
[Case Else 
[блок_операторовn]]
End Select

Каждый список выражений является списком из одного или более значений. Если в одном списке больше одного значения, они отделяются запятыми. Каждый блок операторов содержит несколько операторов или ни одного. Если окажется, что вычисленному значению проверяемого выражения соответствуют значения из нескольких операторов Case, то выполняется блок операторов, ассоциированный с первым оператором Case из всех найденных соответствий. VBA выполняет блок операторов, ассоциированный с оператором Case Else (заметим, что он необязателен), если не найдено ни одного соответствия проверяемого значения выражения и значений из всех списков операторов Case.

Рассмотрим пример вычисления функции

Sub пример2()
Const pi2 = 1.57
Dim x As Single
Dim z As Double
Let x = CSng(InputBox("введи x", "Ввод данных", 0))
Select Case x
Case -pi2
z = Sin(x)
Case 0
z = Cos(x)
Case pi2
z = Tan(x)
Case Else
MsgBox "Неверные исходные данные!"
Exit Sub
End Select
Call out("D1", z)
End Sub

Заметим, что конструкция Select Case вычисляет выражение только один раз при входе в нее, а в конструкции If . . . Then . . . Else вычисляются различные выражения для каждого оператора Elself. Конструкцию If . . . Then . . . Else можно заменить конструкцией Select Case, только если оператор If и каждый оператор Elself вычисляют одно и то же выражение.

Понравилась статья? Поделить с друзьями:
  • Уснинат натрия инструкция по применению цена
  • Усн доходы для ооо подробная инструкция
  • Условная инструкция for в python
  • Условная инструкция if elif else в python
  • Условия работы бухгалтера в должностной инструкции