# CSCI 201 Study Aid: Conditional Structures

## Conditional Structures

• Statements are needed that will allow a program to execute along different paths depending on the circumstances and to repeat the execution of a statement or block of statements.
• Statements which provide these capabilities are known as control statements or conditional statements. They control the flow of execution of a program, and determine which statements are executed in what order.
• The if statement is a conditional structure that contains a logical expression to select or determine which statements in the program are executed.

## Simple if statement

• The simple if statement is used when a course of action consists of
• (a) executing a statement or block of statements, or
• (b) NOT executing the statement or block of statements.
• One statement following if
```if (logical expression) statement1;
next_statement;
```
• If the logical expression is TRUE, statement1 is executed and then next_statement is executed. If the logical expression is FALSE, statement1 is ignored and next_statement is executed.

• A block of statements following if
```if (logical expression) {
statement a;	// A block
statement b;	// of
statement c;	// statements
}
next_statement;
```

• If logical expression is TRUE, the block of statements inside the braces are evaluated and then next_statement is executed. If logical expression is FALSE, the block of statements is ignored and the program proceeds to execute next_statement. The braces, { }, define the block of statements that are part of the if statement.

## Examples:

• In this example, the program is keeping track of a sequence of numbers and storing the smallest and largest values as it goes through the sequence. Notice the different styles of writing the if statement. In each case it is the semi-colon that signals the end of the if statement.
```if(thisValue > maxValue) maxValue = thisValue;

if(thisValue < minValue)
minValue = thisValue; ```
• In this example, the minimum value is not only stored it is printed as the sequence is traversed, and a block of statements, enclosed in braces, is necessary.
```if(thisValue < minValue) {
minValue = thisValue;
cout << "The minimum value so far is: " << minValue << endl;
}
```

## The if-else statement

• The if-else statement is used when the question is not whether to execute a statement or statements, but which statement or statements to execute. The simplest if-else construct consists of two options, and its form is:
```if (logical expression)
statement1 or block1;
else
statement2 or block2;

next_statement;
```

• If logical expression is TRUE, statement1 (or block1) is executed and then next_statement is executed. If logical expression is FALSE, statement2 (or block2) is executed and then next_statement is executed.

• Example: Which number is largest?

```// Program fragment to tell larger number
int a, b;
cout << "Input the numbers, a, b: ";
cin >> a >> b; 		// a, and b are input on one line
// separated by blanks
if (a > b)
cout << "The larger number is: " << a << endl;
else
cout << "The larger number is: " << b << endl;

// remaining program statements
```

## Multiple possibilities

• The number of options in an if-else construct is not limited to two, and frequently more are used in a program. The general form is:
```
if (logical expression1)
statement1 or block1;
else if (logical expression2)
statement2 or block2;
else if (logical expression3)
statement3 or block3;
else if (logical expression4)
statement4 or block4;
else
the_after_else_statement;

next_statement;
```
• If logical expression1 is TRUE, block1 is executed and program control jumps out of the if-else if block and passes to next_statement.
• If logical expression1 is FALSE and logical expression2 is TRUE , then block2 is executed and program control passes to next_statement.
• Likewise, if the first two logical statements are FALSE and logical expression3 is TRUE, block3 is executed and the program control passes to next_statement.
• The statement block following the first logical expression which is TRUE is the only statement block that will be executed.
• If none of the logical expressions evaluate to TRUE, control passes to the_after_else_statement without any of the statements in the if-else if statements having been executed, followed by execution of next_statement.
• It is important to note that an else clause, as opposed to an else if clause, can not have a logical expression associated with it. The logical expression is associated with the key word if.
• Example: How many real roots?
```//The following program fragment finds the number of real roots in a

float a, b, c, discriminant;
unsigned int nRoots;
cout << "Input the coefficients of a quadratic function: " ;
cin >> a >> b >> c;
discriminant = pow(b, 2.) - 4 * a * c);
cout << endl << endl; 		// go to new line and skip it
if (discriminant > 0.)
cout << "There are two roots to the quadratic function.";
else if (discriminant == 0.)
cout << "There is one root to the quadratic function.";
else
cout << "There are no roots to the quadratic function.";

// Continue program execution
```

## Switch Statements

The switch statement is very similar to the if-else-if structure of selection statements. Here is its general form:

```   switch(expression)
{
case constant_1:
statement_1 or block1;
break;
case constant_2:
statement_2 or block_2;
break;
case constant_3:
statement_3 or block_3;
break;

default:
default_statement;
break;
}
```

The switch statement evaluates the value of an expression which must evaluate to an integer or to a character. Execution then passes to the case whose label matches the value of the expression. Duplicate labels are not allowed, so only one case will be selected. If no matching label is found, the execution passes to the default label. If there is no default label (and no matching case label), the statement does nothing and execution passes to next_statement.

Each case is initiated by the appearance of the case reserved word, and is usually terminated by the appearance of the word break. The break is not required.

There is one subtle but very important difference between the if-else-if structure and the switch statement. That difference involves the break statement. In the if-else-if structure, no matter what, only one of the blocks of code is executed. The break statement inside each of the case blocks has the same effect - it tells the computer to continue the execution after the switch statement (execution passes to the next_statement). If the break statement is omitted, the flow of execution will go forward into the next block. Leaving out a break is sometimes useful, but pretty rare. If you are missing a break statement in any block, make sure you intended to leave it out!

## The if-else-if and the switch structures

The if-else-if and the switch structures have very similar usage in a program, but there are distinct differences.

• In an if-else-if statement, a logical expression is evaluated and the code is selected based on the truth value of the expression. In a switch statement an expression is evaluated (its value may be an integer or a character) and the case and is selected based on the value of the expression.
• In an if-else-if satement, each if (and else if) statement has its own logical expression to be evaluated as true or false. In the switch statement, each case label refers back to the value of the expression in the switch statement.

## Example 1

```#include <iostream.h>
int main()
{
float a, b;
char operation;
cout << "Enter a number, an operation, and a number:";
cin >> a >> operation >> b;
cout << endl << endl << "The answer, Master, is: ";

switch (operation) {
case '+':
cout << a + b;
break; 			// Without this statement, execution
// continues on to case '-'
case '-':
cout << a - b;
break;

case 'x': 			// Users may use either symbol for
// multiplication.
case '*': 			// Notice that for either case, the next
// block will be executed.
cout << a * b;
break; 			// Without this statement, execution
// continues on to case '/'
case '/':
cout << a / b;
break;
}
return 0;
}
```

## Example 2

One excellent use of the switch statement is offering a choice to the user which formula it is desired to evaluate. Consider the well known formula for the area of a right triangle, where the area is one-half the product of the height and base of the triangle. Using algebra one could solve for any of the variables and provide a general purpose triangle program wherein the user could pick which quantity should be evaluated. One possibility is written below.

```// Program to calculate needed information about a right triangle
// The variables are: area, height, and base.

#include <iostream.h>

int main()  {
char choice;
float area, height, base;

cout << "This program will evaluate right triangle formulas for:" << endl
<< "    A    Area, given the height and base" << endl
<< "    h    height, given the Area and base" << endl
<< "    b    base, given the Area and height" << endl
<< endl << endl;
cout << "What is your choice -- A, h, or b:";
cin >> choice;

switch(choice)  {
case 'a':

case 'A':
{
cout << endl << endl << "The height: ";
cin >> height;
cout << endl << "The base: ";
cin >> base;
area = 0.5 * base * height;
cout << endl << endl << "The Area is: " << area << endl;
break;
}

// More lines follow...

case 'h':
case 'H':
{
cout << endl << endl << "The Area: ";
cin >> area;
cout << endl << "The base: ";
cin >> base;
height = 2.0 * area / base;
cout << endl << endl << "The height is: " << height << endl;
break;
}

case 'b':
case 'B':
{
cout << endl << endl << "The Area: ";
cin >> area;
cout << endl << "The height: ";
cin >> height;
base = 2.0 * height / base;
cout << endl << endl << "The base is: " << base << endl;
break;
}
}
return 0;
}
```

## Exercises

1. Write a program that prompts a user to enter a series of letter grades and then prints the total number of instances of each grade (i.e., A, B, C, D, or F) that the user entered.
2. Write a program that requests and reads pass/fail values for ten students. The program prints out how many students passed and how many failed and if more than 10 students passed, the message "Raise tuition" is printed.
3. Write a program that prompts a user to enter a number grade and then prints the equivalent letter grade (i.e., A, B, C, D, or F).