0% found this document useful (0 votes)
58 views

Conditional (Computer Programming)

Conditional statements in programming perform different computations or actions depending on whether a condition is true or false. The most common conditional statement is the if-then statement, which can optionally include an else statement. If the condition is true, the code in the then block executes; otherwise, the code in the else block executes. Many languages also support conditional expressions, where an if-else expression returns a value rather than performing an action.

Uploaded by

Dream Eater17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Conditional (Computer Programming)

Conditional statements in programming perform different computations or actions depending on whether a condition is true or false. The most common conditional statement is the if-then statement, which can optionally include an else statement. If the condition is true, the code in the then block executes; otherwise, the code in the else block executes. Many languages also support conditional expressions, where an if-else expression returns a value rather than performing an action.

Uploaded by

Dream Eater17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Conditional (computer programming)

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.

A conditional is sometimes colloquially referred to as an "if-check," especially when perceived as a simple


one and when its specific form is irrelevant or unknown.

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

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

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.

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 ifstatement, 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 nestedconditionals 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

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;
The statements of elseif, 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 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 elsestatements. 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 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, 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" in that code else if branch is, effectively, adding an extra nesting
level, complicating the job for some compilers (or its implementers), 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

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 familyEdit

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 dialectsEdit

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

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 functioncan 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

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

In Small Basic

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.

In Visual BasicEdit

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

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

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 SmalltalkEdit

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

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

JavaScriptEdit
Two examples in JavaScript:

if (Math.random() < 0.5) {


console.log("You got Heads!");
} else {
console.log("You got Tails!");
}
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!");
}

In Lambda Calculus, the concept of an if-then-else conditional can be expressed using the 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:

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.

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 statementsEdit

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:
case someChar of
'a': actionOnA;
'x': actionOnX;
'y','z':actionOnYandZ;
else actionOnNoMatch;
end;

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

C – If..else, Nested If..else and else..if Statement with example

In the last tutorial we learned how to use if statement in C. In this guide, we will learn how to use if else,
nested if else and else if statements in a C Program.

C If else statement

Syntax of if else statement:


If condition returns true then the statements inside the body of “if” are executed and the statements inside
body of “else” are skipped.
If condition returns false then the statements inside the body of “if” are skipped and the statements in
“else” are executed.
if(condition) {
// Statements inside body of if
}
else {
//Statements inside body of else
}

Flow diagram of if else statement

Example of if else statement

In this program user is asked to enter the age and based on the input, the
if..else statement checks whether the entered age is greater than or equal to
18. If this condition meet then display message “You are eligible for voting”,
however if the condition doesn’t meet then display a different message “You
are not eligible for voting”.

#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
/* This statement will only execute if the
* above condition (age>=18) returns true
*/
printf("You are eligible for voting");
}
else
{
/* This statement will only execute if the
* condition specified in the "if" returns false.
*/
printf("You are not eligible for voting");
}
return 0;
}
Output:
Note: If there is only one statement is present in the “if” or “else” body then you do not need to use the braces
(parenthesis). For example the above program can be rewritten like this:

#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
printf("You are eligible for voting");
else
printf("You are not eligible for voting");
return 0;
}

C Nested If..else statement


When an if else statement is present inside the body of another “if” or “else” then this is called nested if else. Syntax
of Nested if else statement:

if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}

Example of nested if..else


#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 != var2)
{
printf("var1 is not equal to var2\n");
//Nested if else
if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else
{
printf("var2 is greater than var1\n");
}
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}

Output:

Input the value of var1:12


Input the value of var2:21
var1 is not equal to var2
var2 is greater than var1
C – else..if statement
The else..if statement is useful when you need to check multiple conditions within the program, nesting of if-else
blocks can be avoided using else..if statement.

Syntax of else..if statement:

if (condition1)
{
//These statements would execute if the condition1 is true
}
else if(condition2)
{
//These statements would execute if the condition2 is true
}
else if (condition3)
{
//These statements would execute if the condition3 is true
}
else
{
//These statements would execute if all the conditions return false.
}

Example of else..if statement


Lets take the same example that we have seen above while discussing nested if..else. We will rewrite the same
program using else..if statements.

#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2\n");
}
else if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else if (var2 > var1)
{
printf("var2 is greater than var1\n");
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}
Output:

Input the value of var1:12


Input the value of var2:21
var1 is not equal to var2
As you can see that only the statements inside the body of “if” are executed. This is because in this statement as
soon as a condition is satisfied, the statements inside that block are executed and rest of the blocks are ignored.

Important Points:
1. else and else..if are optional statements, a program having only “if” statement would run fine.
2. else and else..if cannot be used without the “if”.
3. There can be any number of else..if statement in a if else..if block.
4. If none of the conditions are met then the statements in else block gets executed.
5. Just like relational operators, we can also use logical operators such as AND (&&), OR(||) and NOT(!).

You might also like