<<

CS 350 – COMPUTER ORGANIZATION AND PROGRAMMING Week 8

Reading:

Conditional statements, conditional expressions and conditional constructs are features of a which perform different computations or actions depending on whether a programmer-specified condition evaluates to true or false.

Objectives:  Understanding the concept of conditional statements.  Finding the concept of Conditional expressions

Concepts:

1. IF 2. IF- Else 3. For loop 4. Switch case.

Outline:  Overview of conditional statements.  If expressions -as a ternary operator. -as a function -in Haskell.  Case and switch statements.  Branch predication.

References: D. Patterson and J. Hennessy, Computer Organization and Design: appendix A67.

Cs 350- week 8- page -1 Cs 350 - week 8 - Lecture notes If:

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 structure (in pseudocode form) looks like this:

If (condition) Then (statements) Else (statements) 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 statement block following the Then is executed. Otherwise, the execution continues in the following block - either in the Else block (which is usually optional), or if there is no "Else" block, then after the End If.

After either the block after the Then or the block after the Else 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. As a result, , which allowed (virtually) arbitrary statements to be put in statement blocks inside an if statement, gained in popularity, until it became the norm.

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:

elseif, in Ada, is simply 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.

In some other languages, such as , else if literally just means else followed by if - so no syntactic sugar is needed or provided.

Cs 350- week 8- page -2 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 action).

As a ternary operator

Main article: ?: [sic]

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 { my_variable = 'bar'; }

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

Cs 350- week 8- page -3 Arithmetic IF

Fortran 77 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[2]:

IF (e) label1, label2, label3

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

IF (e < 0) GOTO label1 IF (e = 0) GOTO label2 IF (e > 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 on the IBM 704 computer. On that computer it could be implemented quite efficiently using instructions such as 'Branch if accumulator negative'.

Alternative implementation

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

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

Cs 350- week 8- page -4 Case and switch statements

Main article: Switch statement

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.

case someChar of switch (someChar) { 'a': actionOnA; case 'a': actionOnA; 'x': actionOnX; break; 'y','z':actionOnYandZ; case 'x': actionOnX; end; break; case 'y': case 'z': actionOnYandZ; break; default: actionOnNoMatch; }

Lab:

If- Else

#include int main(void) {

int number = 75; int mark;

printf("Your examination mark\n"); printf("Enter your score, please\n"); scanf("%d",&mark);

if (mark >= number) { printf("Incredible, you passed with a merit\n"); }

return 0; }

Cs 350- week 8- page -5 Case: SELECT CASE (selector) CASE (-list-1) statements-1 CASE (label-list-2) statements-2 CASE (label-list-3) statements-3 ...... CASE (label-list-n) statements-n CASE DEFAULT statements-DEFAULT END SELECT

Switch:

Here's the program with a switch and case.

#include

int main(void) { float numb1 = 0, numb2 = 0; /* the two numbers to work on */ int menu = 1; /* add or substract or divide or multiply */ float total = 0; /* the result of the calculation */ char calType; /* what type of calculation */

printf("Please enter in the first of the two numbers\n\t"); scanf("%f", &numb1); /* READ first number */

printf("\n\nPlease enter the second of the two numbers\n\t"); scanf("%f", &numb2); /* READ second number */

printf("\n\nWhat would you like to do?\n\n"); /* WRITE instructions */ printf("\t1 = add\n"); printf("\t2 = substract\n"); printf("\t3 = multiply\n"); printf("\t4 = divide\n");

printf("\n\nPleas make your selection now:\n\t"); scanf("%d",&menu); /* READ calculation type */

switch (menu) /* select the type of calculation */ { case 1: total = numb1 + numb2;

Cs 350- week 8- page -6 calType = '+'; /* assign a char to symbolise calculation type */ break; case 2: total = numb1 - numb2; calType = '-'; break; case 3: total = numb1 * numb2; calType = '*'; break; case 4: total = numb1 / numb2; calType = '/'; break; default: printf("Invalid option selected\n"); } if (menu == 3 && numb2 == 0) /* cannot divide by 0 */ printf("\n\n\tYou cannot divide by 0\n\n");

/* display result to 2 decimal places */ printf("\n\n*************************"); printf("\n\n\t%.3f %c %.3f = %.2f", numb1, calType, numb2, total); printf("\n\n*************************\n\n"); return 0;

Cs 350- week 8- page -7