ArticleslgStudy

computer science

Conditional (computer programming)

Conditional (computer programming) is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Conditional (computer programming) rather than just read about it. In short: In computer programming, a conditional statement directs program control flow based on the value of a condition; a Boolean expression. A conditional expression evaluates to a value without the side-effect of changing control flow.

Conditional (computer programming) — main illustration
Conditional (computer programming) — illustration

Key takeaways

  • Conditional (computer programming) belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Conditional (computer programming) to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Conditional (computer programming) from memory before moving on to harder problems.

Reference excerpt

In computer programming, a conditional statement directs program control flow based on the value of a condition; a Boolean expression. A conditional expression evaluates to a value without the side-effect of changing control flow. Many programming languages (such as C) have distinct conditional statements and expressions. In pure functional programming, a conditional expression does not have side-effects, many functional programming languages with conditional expressions (such as Lisp) support side-effects.

Conditional statement

If-then-else statement

Although the syntax of an if-then-else statement varies by language, the general syntax is shown as pseudocode below. The part represented by the condition placeholder is an expression that evaluates to either true or false. If true, control passes to consequent and when complete to after end if. If false, control passes to alternative and when complete to after end if. As the else clause is optional, the else alternative part can be omitted. Typically, both consequent and alternative can be either a single statement or a block of statements.

The following example, also in pseudocode, replaces placeholders with example logic.

History and development In early programming languages, especially dialects of BASIC, an if–then-else statement could only contain goto statements but this tended to result in hard-to-read spaghetti code. As a result, structured programming, which supports control flow via code blocks, gained in popularity, until it became the norm in most BASIC variants and all languages. Such mechanisms and principles were based on the ALGOL family of languages, including Pascal and Modula-2. While it is possible to use goto in a structured way, structured programming makes this easier. A structured if–then–else statement is one of the key elements of structured programming, and it is present in most popular languages such as C, Java, JavaScript and Visual Basic.

Dangling else

The convention is that an else clause, like the then clause, responds to the nearest preceding if clause. However, the semantics of nested conditionals in some early languages such as ALGOL 60 were less than clear; the syntax was inadequate to always specify the same predicate if clause. Thus, the parser might randomly pair the else with any one of the perhaps manifold if clauses in the intended nested hierarchy.

This is known as the dangling else problem. It is resolved in various ways, depending on the language (in some, by means of explicit block-ending syntax (such as end if ) or a block enclosure, such as curly brackets ( {⋯} ).

Chaining Chaining conditionals is often provided in a language via an else-if construct. Only the statements following the first condition that is true are executed. Other statements are skipped. In placeholder pseudocode:

In the following pseudocode, a shop offers as much as a 30% discount for an item. If the discount is 10%, then the first if statement is true and "you have to pay $30" is printed. All other statements below that first if statement are skipped.

Only one end if is needed if one uses else if instead of else followed by if. In ALGOL 68, the 1968 “Draft Report” (circulated as a supplement to ALGOL Bulletin no. 26) still used the bold keyword elsf in “contracted” conditionals. The spelling elif was then standardized in the “Revised Report on the Algorithmic Language ALGOL 68” (1973), which lists both the bold words if ~ then ~ elif ~ else ~ fi and their “brief” symbols, where elif corresponds to |: in the compact form ( ~ | ~ |: ~ | ~ | ~ ). In Ada, the elseif keyword is syntactic sugar for the two words else if. PHP also supports an elseif keyword both for its curly brackets or colon syntaxes. Perl and Ruby provide 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. Visual Basic, supports ElseIf. Similarly, the earlier UNIX shells (later gathered up to the POSIX shell syntax) 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. 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 ...), an alternative is the switch statement. In a language that does not have a switch statement, these can be encoded as a chained if-then-else.

Switch statement A switch statement supports multiway branching, often comparing the value of an expression with constant values and transferring control to the code of the first match. There is usually a provision for a default action if no match is found. An optimizing compiler may use a control table to implement the logic of a switch statement. In a dynamic language, 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.

Guarded conditional The Guarded Command Language (GCL) of Edsger Dijkstra supports conditional execution as a list of commands consisting of a Boolean-valued guard (corresponding to a condition) and its corresponding statement. In GCL, exactly one of the statements whose guards is true is evaluated, but which one is arbitrary. In this code

if G0 → S0 □ G1 → S1 ... □ Gn → Sn fi

the Gi's are the guards and the Si's are the statements. If none of the guards is true, the program's behavior is undefined. GCL is intended primarily for reasoning about programs, but similar notations have been implemented in Concurrent Pascal and occam.

Arithmetic if The earliest conditional statement in Fortran, up to Fortran 77, was the arithmetic if statement which jumped to one of three labels depending on whether a value (of type integer, real, or double precision) is <0, 0, or >0. In the following code, control passes to one of the labels based on the value of e.

… excerpt ends here. Continue reading the full article.

Illustrations

Conditional (computer programming): If-then-else flow diagram
If-then-else flow diagram
Conditional (computer programming): A nested if–then–else flow diagram
A nested if–then–else flow diagram

Worked examples

Example 1 — a first encounter with Conditional (computer programming)

Start with the simplest possible case. Write down what Conditional (computer programming) claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Conditional (computer programming) before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Conditional (computer programming) ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Conditional (computer programming)

In research
Conditional (computer programming) appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Conditional (computer programming) in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Conditional (computer programming) is common in secondary-school and first-year university syllabi. It links to neighbouring topics Conditional constructs, so understanding it makes those chapters shorter.
In everyday life
Look for Conditional (computer programming) outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Conditional (computer programming)” →

How to study Conditional (computer programming) in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Conditional (computer programming) means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Conditional (computer programming) out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Conditional (computer programming) in simple terms?

In computer programming, a conditional statement directs program control flow based on the value of a condition; a Boolean expression. A conditional expression evaluates to a value without the side-effect of changing control flow.

Why does Conditional (computer programming) matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Conditional (computer programming)?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Conditional (computer programming).

Tags

  • Conditional constructs

Keep exploring