aplikom

29
I. If Then (Else) Statement A. Description Of If Then Else Statement The if-then construct (sometimes called if-then-else) is common across many programming languages. Although the syntax varies quite a bit from language to language, the basic structure (in pseudocode form) looks like this: (This example is actually perfectly valid Visual Basic or QuickBASIC syntax.) If (predicate) Then (consequent) Else (alternative) End If 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. 1

Transcript of aplikom

If Then (Else) StatementA. Description Of If Then Else Statement The if-then construct (sometimes called if-then-else) is common across many programming languages. Although the syntax varies quite a bit from language to language, the basic structure (in pseudocode form) looks like this: (This example is actually perfectly valid Visual Basic or QuickBASIC syntax.) If (predicate) Then (consequent) Else (alternative) End If 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. In early programming languages - and in particular, in some dialects of BASIC in the 1980s - an if-then statement could only contain GOTO statements. 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 allowed (virtually) arbitrary statements to be put in statement blocks inside an if statement, gained in popularity, until it became the norm. 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 1

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 modern high-level programming languages including VB (all versions including .NET), C and its derivatives (including C++ and C#), Java and JavaScript. Else If Parts 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. The statements of the final Else will be executed if none of the conditions are true. This example is written in the Ada programming language: if condition then -- statements; else if condition then -- more statements; else if condition then -- more statements; ... else condition then -- other statements; end if; elsif, in Ada, is simply syntactic sugar for else followed by if. In Ada, the difference is that only one end if is needed, if one uses elsif instead of else followed by if. In some other languages, such as C and Java, else if literally just means else followed by if - so no syntactic sugar is needed or provided. This works since when an else is followed by one statement (in this case the if), it doesn't need any braces.

2

In Python, there is a special keyword elif for this because Python uses indent to indicate structure, so if you only used else and if, then you would need to keep increasing the indent at every condition. In Perl, there is a special keyword elsif for this because braces are required for if and else, so if you only used else and if, then you would need to keep adding braces. B. If Expressions 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 just perform an act As a ternary operator Main article: In C and C-like languages conditional expressions take the form of a ternary operator called the conditional expression operator, ?:, which follows this template: (condition)?(evaluate if condition was true):(evaluate if condition was false) This means that conditions can be inlined into expressions, unlike with if statements, as shown here using C syntax: //Invalid my_variable = if(x > 10) { "foo" } else { "bar" }; //Valid my_variable = (x > 10)?"foo":"bar"; To accomplish the same as the second (correct) line above, using a standard if/else statement, this would take more than one line of code (under standard layout conventions): if (x > 10) my_variable = 'foo'; else 3

my_variable = 'bar'; ALGOL 60 and some other members of the ALGOL family have the if expression which performs the same function. In Algol: myvariable := if x > 10 then 1 else 2 In Scheme, the Lisp dialect which was inspired to a great extent by Algol (define myvariable (if (> x 10) 1 2)) As a function 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. In Haskell 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.[1] 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 3). It can be written like this:[2] if' :: Bool -> a -> a -> a if' True x _ = x 4

if' False _ y = y Arithmetic IF 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. 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 IF (e .GT. 0) GOTO label3 Because this arithmetic IF is equivalent to multiple GOTO statements, 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 it could be implemented quite efficiently using instructions such as 'Branch if accumulator negative'.

Case and switch statements Switch statements (in some languages, case statements) compare a given value with specified constants and take action according to the first constant to match. The example on the left is written in Pascal, and the example on the right is written in C. Pascal: C: 5

case someChar of 'a': actionOnA; 'x': actionOnX; 'y','z':actionOnYandZ; end;

switch (someChar) { case 'a': actionOnA; break; case 'x': actionOnX; break; case 'y': default: actionOnNoMatch;

else actionOnNoMatch; case 'z': actionOnYandZ; break;

C.Pattern matchingPattern matching is a more sophisticated alternative to both if-then-elseif, and the simple case or switch statements mentioned above. It is available in some programming languages such as the ML language family. Here is a simple example written in the O'Caml language: match fruit with | "apple" -> cook pie | "coconut" -> cook dango_mochi | "banana" -> mix;; The true power of pattern matching, however, comes from the ability to concisely (a) match on data structure patterns, and (b) bind variables at the same time. 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 not two separate definitions of the function, but rather definitions of what to do in two cases - one case where the list is empty (just return an empty list) and the other case where the list is not empty.

6

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 variables. However, it is frequently used as a choice construct in the languages in which it is available. Description Conditionally executes a group of statements, depending on the value of an expression. Syntax If condition Then statements [Else elsestatements ] Or, you can use the block form syntax: If condition Then [statements] [ElseIf condition-n Then [elseifstatements]] . . . [Else [elsestatements]] End If The If...Then...Else statement syntax has these parts:

Part condition

Description One or more of the following two types of expressions: A numeric or string expression that evaluates to True or False. If condition is Null, condition is treated as False.

7

An expression of the form TypeOf objectname Is objecttype. The objectname is any object reference and objecttype is any valid object type. The expression is True if objectname is of the object type specified by objecttype; otherwise it is False. statements condition-n One or more statements separated by colons; executed if condition is True. Same as condition. n is True. elsestatements One or more statements executed if no previous condition or condition-n expression is True.

elseifstatements One or more statements executed if the associated condition-

The Print Statementprint_stmt ::= "print" ([expression ("," expression)* [","]] | ">>" expression [("," expression)+ [","]]) print evaluates each expression in turn and writes the resulting object to standard output (see below). If an object is not a string, it is first converted to a string using the rules for string conversions. The (resulting or original) string is then written. A space is written 8

before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case (1) when no characters have yet been written to standard output, (2) when the last character written to standard output is a whitespace character except ' ', or (3) when the last write operation on standard output was not a print statement. (In some cases it may be functional to write an empty string to standard output for this reason.) Note Objects which act like file objects but which are not the built-in file objects often do not properly emulate this aspect of the file objects behavior, so it is best not to rely on this. A '\n' character is written at the end, unless the print statement ends with a comma. This is the only action if the statement contains just the keyword print. Standard output is defined as the file object named stdout in the built-in module sys. If no such object exists, or if it does not have a write() method, a RuntimeError exception is raised. print also has an extended form, defined by the second portion of the syntax described above. This form is sometimes referred to as print chevron. In this form, the first expression after the >> must evaluate to a file-like object, specifically an object that has a write() method as described above. With this extended form, the subsequent expressions are printed to this file object. If the first expression evaluates to None, then sys.stdout is used as the file for output. Basic Theory: A. PRINT Statement Is a statement that can used to give commands to the computer to print or remove the results that have been processed by the CPU into a computer monitor. Namely: 9

Writing text / all existing text in the opening and closing quotes will be printed. Why outputkan result of a calculation Giving an empty space or room. Syntax / Method of Writing: Line Number PRINT [