Play Video
1
Computer programming: How to write conditional statements | lynda.com tutorial
Computer programming: How to write conditional statements | lynda.com tutorial
::2011/09/26::
Play Video
2
Introduction to Computer Programming - Conditional Structures - Create a Vending Machine
Introduction to Computer Programming - Conditional Structures - Create a Vending Machine
::2014/07/26::
Play Video
3
Introduction to Computer Programming - Conditional Structures - Nested Conditionals
Introduction to Computer Programming - Conditional Structures - Nested Conditionals
::2014/08/08::
Play Video
4
The fundamentals of writing computer programming | lynda.com overview
The fundamentals of writing computer programming | lynda.com overview
::2011/09/26::
Play Video
5
Computer programming: What is object-oriented language? | lynda.com overview
Computer programming: What is object-oriented language? | lynda.com overview
::2011/09/26::
Play Video
6
Introduction to Computer Programming - Conditional Structures - Cell Phone Contract: Iteration 4
Introduction to Computer Programming - Conditional Structures - Cell Phone Contract: Iteration 4
::2014/07/26::
Play Video
7
Computer programming: How to write code functions | lynda.com tutorial
Computer programming: How to write code functions | lynda.com tutorial
::2011/09/26::
Play Video
8
Java Programming Tutorial - 20 - Conditional Operators
Java Programming Tutorial - 20 - Conditional Operators
::2009/05/10::
Play Video
9
Conditional Code:Boolean Expressions Of C programming
Conditional Code:Boolean Expressions Of C programming
::2013/09/29::
Play Video
10
Programming with Casio Graphing Calculators (Part 2): Conditional Statements & Loops
Programming with Casio Graphing Calculators (Part 2): Conditional Statements & Loops
::2013/09/27::
Play Video
11
Assembly Language Programming Tutorial - 40 - Conditional Jumps: Jc, Jnc, Jz and Jnz
Assembly Language Programming Tutorial - 40 - Conditional Jumps: Jc, Jnc, Jz and Jnz
::2013/12/13::
Play Video
12
Java Programming Tutorial #11: Nested Conditional Statements
Java Programming Tutorial #11: Nested Conditional Statements
::2014/08/04::
Play Video
13
Java Programming Tutorial   20   Conditional Operators xvid
Java Programming Tutorial 20 Conditional Operators xvid
::2013/12/13::
Play Video
14
Conditional Code:The switch Statement Of C programming
Conditional Code:The switch Statement Of C programming
::2013/09/29::
Play Video
15
Computer Languages - Conditional Statements
Computer Languages - Conditional Statements
::2014/04/17::
Play Video
16
Conditional Code:The if Statement Of C programming
Conditional Code:The if Statement Of C programming
::2013/09/29::
Play Video
17
Conditional Code:Blocks Of C programming
Conditional Code:Blocks Of C programming
::2013/09/29::
Play Video
18
UNIX: Detailed scripting tutorial part 2 [Conditional programing]
UNIX: Detailed scripting tutorial part 2 [Conditional programing]
::2014/05/11::
Play Video
19
C++ in Urdu - Lesson 9:Conditional Statements - If
C++ in Urdu - Lesson 9:Conditional Statements - If
::2010/11/04::
Play Video
20
Java Programming Tutorial 12 | Conditional Operators
Java Programming Tutorial 12 | Conditional Operators
::2013/11/10::
Play Video
21
Ruby Programming - 27 - Conditional Assignment Operator
Ruby Programming - 27 - Conditional Assignment Operator
::2014/06/01::
Play Video
22
Intro to C Programming - Conditional Statements - if
Intro to C Programming - Conditional Statements - if
::2013/09/05::
Play Video
23
CS & IT Symposium 2010:  Teaching Computer Programming to Middle School Students
CS & IT Symposium 2010: Teaching Computer Programming to Middle School Students
::2010/08/20::
Play Video
24
Conditional Code:The goto Statement Of C programming
Conditional Code:The goto Statement Of C programming
::2013/09/29::
Play Video
25
# if / #else / #elif / #endif Conditional Compilation Macros  -36- C Programming Video Tutorial
# if / #else / #elif / #endif Conditional Compilation Macros -36- C Programming Video Tutorial
::2013/05/03::
Play Video
26
Conditional Code:The if...else Statement Of C programming
Conditional Code:The if...else Statement Of C programming
::2013/09/29::
Play Video
27
Conditional Code:Advanced Relational Operators Of C programming
Conditional Code:Advanced Relational Operators Of C programming
::2013/09/29::
Play Video
28
Lec 19 | MIT 6.042J Mathematics for Computer Science, Fall 2010
Lec 19 | MIT 6.042J Mathematics for Computer Science, Fall 2010
::2012/12/31::
Play Video
29
Conditional Statements - COMP100 Programming 1
Conditional Statements - COMP100 Programming 1
::2013/09/26::
Play Video
30
Conditional Code:Chapter 4 Exercises Of C programming
Conditional Code:Chapter 4 Exercises Of C programming
::2013/09/29::
Play Video
31
Conditional Code:Relational Operators Of C programming
Conditional Code:Relational Operators Of C programming
::2013/09/29::
Play Video
32
Assembly Language Programming Tutorial 35- Conditional Assembly
Assembly Language Programming Tutorial 35- Conditional Assembly
::2014/04/05::
Play Video
33
Game Programming Prerequisites Assignment 2: Conditional Statements
Game Programming Prerequisites Assignment 2: Conditional Statements
::2012/10/12::
Play Video
34
Java Programming Tutorial #8: Conditional Statements (If-Else)
Java Programming Tutorial #8: Conditional Statements (If-Else)
::2014/08/01::
Play Video
35
Conditional Code:Introducing the Course Project Of C programming
Conditional Code:Introducing the Course Project Of C programming
::2013/09/29::
Play Video
36
Conditional Code:Course Project Solution Of C programming
Conditional Code:Course Project Solution Of C programming
::2013/09/29::
Play Video
37
AP Computer Science: Conditional Statements
AP Computer Science: Conditional Statements
::2012/06/11::
Play Video
38
Excel 2013: Conditional Formatting
Excel 2013: Conditional Formatting
::2013/12/16::
Play Video
39
PFC #1: Computer Basics, Programming, Languages, Algorithms, Flowcharts
PFC #1: Computer Basics, Programming, Languages, Algorithms, Flowcharts
::2012/03/08::
Play Video
40
C Programming: C Preprocessor (directives, conditional compilation) Lab1
C Programming: C Preprocessor (directives, conditional compilation) Lab1
::2012/04/19::
Play Video
41
Conditional Code:Chapter 4 Solutions Of C programming
Conditional Code:Chapter 4 Solutions Of C programming
::2013/09/29::
Play Video
42
Programming with Conditional Statements - Programming Virgin w/ Javascript
Programming with Conditional Statements - Programming Virgin w/ Javascript
::2014/04/15::
Play Video
43
Microsoft Access Conditional Formatting Expression
Microsoft Access Conditional Formatting Expression
::2013/04/23::
Play Video
44
C language Tutorial for Beginners 27- Conditional Expressions
C language Tutorial for Beginners 27- Conditional Expressions
::2014/04/06::
Play Video
45
How to program in C++ #7 - Conditional Structures - If And Else
How to program in C++ #7 - Conditional Structures - If And Else
::2013/05/30::
Play Video
46
C++ Programming Tutorial 22 - Conditional Statements
C++ Programming Tutorial 22 - Conditional Statements
::2014/06/24::
Play Video
47
Introduction to Programs Data Types and Variables
Introduction to Programs Data Types and Variables
::2011/06/30::
Play Video
48
ABMC4007 (Part 4-2) Selection Statements, Conditional Tests and Logical Operators
ABMC4007 (Part 4-2) Selection Statements, Conditional Tests and Logical Operators
::2012/06/22::
Play Video
49
Swift Programming Tutorial - 17 - Ternary Conditional Operator
Swift Programming Tutorial - 17 - Ternary Conditional Operator
::2014/07/03::
Play Video
50
C++ Programming Tutorial 15 - Conditional Ternary Operator
C++ Programming Tutorial 15 - Conditional Ternary Operator
::2014/06/21::
NEXT >>
RESULTS [51 .. 101]
From Wikipedia, the free encyclopedia
  (Redirected from Conditional (programming))
Jump to: navigation, search

In computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. Apart from the case of branch predication, this is always achieved by selectively altering the control flow based on some condition.

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.

Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at runtime.

If–then(–else)[edit]

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:

 IF (boolean condition) 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, especially some dialects of BASIC in the 1980s home computers, 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 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 .

A subtlety is that the optional else clause found in many languages means that the context-free grammar is ambiguous, since nested conditionals can be parsed in multiple ways. Specifically,

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.

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. The statements of

if condition then
   --statements
elseif condition then
    -- more statements
elseif condition then
    -- more statements;
...
else
    -- 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. This is similar in Perl, which provides the keyword elsif to avoid the large number of braces that would be required by multiple if and else statements and also in Python, which 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.

However, in many languages more directly descended from Algol, such as Algol68, 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, ECMA-script, PHP, 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" in that code else if branch is, effectively, adding an extra nesting level, complicating the job for some compilers (or its implementors), which has to 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=0 ... else if x=1 ... else if x=2...), then 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 changes the program state or perform some kind of action).

Algol family[edit]

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

  myvariable := if x > 10 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 10) 1 2))   ; Assigns ‘myvariable’ to 1 or 2, depending on the value of ‘x’
 ;; Common Lisp
 (let ((x 5))
   (setq myvariable (if (> x 10) 1 2)))  ; 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.[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 three). It can be written like this:[2]

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

C-like languages[edit]

C and C-like languages has 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 (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):

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,[3] while others argue that concise expressions are easier to read than statements spread over several lines.

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

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:[4]

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.[5]

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

Case and switch statements[edit]

Main article: Switch statement

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]

Main article: Pattern matching

Pattern matching may be seen as a more sophisticated 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.

Branch predication[edit]

Main article: Branch predication

In assembly language, branch predication is a feature of certain central processing unit (CPU) instruction sets which permits conditional execution of instructions, without having to perform costly conditional jumps.

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
C/C++ Yes Yes Unneeded[B] Fall-through No No
C# Yes Yes Unneeded[B] Yes No No
COBOL Yes Yes Unneeded[B] Yes No No
Eiffel Yes Yes Yes Yes No No
F# Yes Yes Yes Unneeded[C] No Yes
Fortran 90 Yes Yes Yes Yes Yes No
Haskell Yes Needed Unneeded[B] Unneeded[C] No Yes
Java Yes Yes Unneeded[B] Fall-through[6] No No
ECMAScript (JavaScript) Yes Yes Unneeded[B] Fall-through[7] No No
Mathematica Yes Yes Yes Yes No Yes
Oberon Yes Yes Yes Yes No No
Perl Yes Yes Yes Yes No No
PHP Yes Yes Yes Fall-through No No
Pascal, Delphi Yes Yes Unneeded Yes No No
Python Yes Yes Yes No No No
QuickBASIC Yes Yes Yes Yes No No
Ruby Yes Yes Yes Yes No No
Scala Yes Yes Unneeded[B] Fall-through No Yes
SQL Yes[S] Yes Yes Yes[S] No No
Visual Basic, classic Yes Yes Yes Yes No No
Visual Basic .NET Yes Yes Yes Yes No No
Windows PowerShell Yes 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 3 4 5 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.
  3. 1 2 In Haskell and F#, a separate constant choice construct is unneeded, because the same task can be done with pattern matching.
  4. 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).

See also[edit]

References[edit]

  1. ^ Haskell 98 Language and Libraries: The Revised Report
  2. ^ "If-then-else Proposal on HaskellWiki"
  3. ^ "Efficient C Tips #6 – Don’t use the ternary operator « Stack Overflow". Embeddedgurus.com. 2009-02-18. Retrieved 2012-09-07. 
  4. ^ "American National Standard Programming Language FORTRAN". 1978-04-03. Retrieved 2007-09-09. 
  5. ^ "VisualWorks: Conditional Processing". 2006-12-16. Retrieved 2007-09-09. 
  6. ^ Java.sun.com, Java Language Specification, 3rd Edition.
  7. ^ Ecma-international.org ECMAScript Language Specification, 5th Edition.

External links[edit]

Wikipedia content is licensed under the GFDL License
Powered by YouTube
LEGAL
  • Mashpedia © 2014