Chapter 5

Conditional Structures and Loops

Key Skills & Concepts

Image   Control Structures

Image   Comparison Operators

Image   Conditional Structures

Image   Loops


 

This chapter introduces the two main types of control structures, conditional structures and loops. Conditional structures enable decision making for code execution. Loop structures enable repetitive code execution.

Control Structures

Both conditional structures and loops are control structures because they rely on conditional expressions to select branches of code for execution. The conditional expression in a conditional structure or loop evaluates to either a true or false result. For example, if an expression is true, such as when the value of x is greater than 5, the code block enclosed by the control structure is executed:

image

Indentation and Alignment

Each control structure usually begins with a header that contains an expression for evaluation. While there are exceptions, normally, the block of code to be executed follows the control structure header. This code block is contained within opening { and closing } curly braces. Code within the curly braces is indented and left-aligned.

Usually, the opening curly brace is placed on the line after the control structure header, like this:

image

To save space, curly braces may be placed after the control structure header on the same line, like this:

image

When only one line of code exists in the control structure block, the curly braces are optional, as shown here:

image

TIP      

To help keep your code readable and easier to debug, you are better off using proper indentation and alignment of your control structures as you write your code. Your teammates will expect this from you too.

Nesting

It is possible to place control structures within control structures, a practice called nesting. In this case, a conditional statement is placed within a conditional statement:

image

Comparison Operators

To enable conditional structures and loops, comparison operators allow you to create Boolean expressions that are used in either structure type. The conditional expressions generate either true or false outcomes that allow the program to decide whether or not to execute code within the conditional block or loop block. In this section we will examine the common comparison operators.

Equals and Not Equals Operators

The equals operator, = =, determines if two operands of the same data type are equal. The equals operator uses two equal signs because the use of only one equal sign is interpreted as an assignment. In other words, c = d assigns the value of d to c. However, c = = d implies a comparison is being made.

To determine if two operands of the same data type are not equal, use the not equals operator, !=. The exclamation mark is a negation operator, which is usually called not. Placing ! before a true expression makes it false. Since two negatives make a positive, placing ! before a false expression makes it true. Table 5-1 shows how the equals and not equals operators are used in Boolean expressions.

image

Table 5-1 Equals and Not Equals Operators

Less Than and Greater Than Operators

C# uses less than (<), greater than (>), less than or equal (<=), and greater than or equal (>=) operators to compare values of the same data type. Results from less than and greater than expressions must always be either true or false. For example, 5 > 4 is always true and 5.0f >= 6.0f is always false. Table 5-2 lists these four less than and greater than expressions with examples of each.

image

Table 5-2 Less Than and Greater Than Operators

AND and OR Operators

The logical AND and logical OR operators allow you to create composite conditional expressions. The logical AND operator is denoted with a double ampersand, &&. The logical OR operator uses the double pipe, ||, notation. With the logical AND, both conditions on each side of the operator must be true for the final outcome to be true. With the logical OR, at least one condition on either side of the operator must be true for the entire expression to be true. Table 5-3 presents examples for each type of operator.

image

Table 5-3 Logical AND and Logical OR Operators

Let’s now look at how comparison operators work with conditional structures to implement decision logic.

Conditional Structures

Conditional structures allow you to select and execute different branches of code through the use of conditional expressions. Even the most complex decision-making systems and algorithms rely on these simple but essential structures. Whenever a conditional expression in a conditional structure is true, the code block that follows is executed and then the program exits the conditional series. The three types of conditional structures are

Image   If-else statements

Image   Conditional operators

Image   Switches

If-Else Statements

The if-else statement is the most commonly used conditional structure. The if-else statement is really a series of conditional expressions that are grouped together. After finding the first true conditional expression in the series, the block of code that follows is executed. Once the code block has executed, the program immediately exits the conditional series so no other expressions from the series are evaluated. This conditional series may use if, else if, and else structures. Together this series resembles the structure in this sample:

image

To understand this better, let’s examine the three possible branch types in an if-else series:

Image   if if statements contain the first conditional expression within the if-else statement. Only one if statement can exist in a series, and it is mandatory for any series or on its own. When the if statement is true, the code block underneath is executed.

Image   else if else if statements are optional and must follow the opening if statement. The else if statement presents another conditional expression and an alternative block of code for execution if the expression is true. Multiple else if statements can exist within an if-else series.

Image   else An else statement is the default selection when no previous condition in the if-else series is true. Only one else condition is permitted, and it must be at the end of the conditional series.



Example 5-1 If-Else Statements


To demonstrate decision-making logic with if-else statements, this example selects and displays warning messages based on the tornado classification. When reading through the code, note how indentation helps to visually identify each conditional block.

image

Results are displayed from the selected condition whenever ShowWarning() is called. During the first call to ShowWarning(), the default condition is selected, and on the next call to ShowWarning(), only the branch for F3 is selected:

Inactive: No damage expected.
F3+: Severe damage warning.

Image



Try This 5-1 Comparison Operator and If-Else Statement Practice


To get a better understanding of how the if-else statement works with comparison operators, try this experiment.

1. Starting with Example 5-1, set a breakpoint by clicking in the gray margin beside the first call to ShowWarning().

2. Run the program. When it is halted, step into ShowWarning() by pressing F11.

3. Step over the code in ShowWarning() using F10 during the first pass through. Notice how all conditions in the if-else statement are evaluated but their nested code blocks are not entered since none of the conditions are true. Also notice how the default else block is entered since none of the previous conditions were selected.

4. Run the program to completion.

5. Add a new tornado strength category constant declaration at the top of the class:

    const int F4 = 4;

6. Just before the last Console.ReadLine() instruction, add this code:

    strength = F4;
ShowWarning(strength);

7. Modify one of the comparison operators in one of the conditional blocks so the following output displays when running the program:

    Inactive: No damage expected.
F3+: Severe damage warning.
F3+: Severe damage warning.

Image



Example 5-2 Applying Logical AND and Logical OR Expressions


This example demonstrates how conditional expressions can be combined with logical OR and logical AND operators. In this case, the Report() method receives windspeed and warningMsg variables as parameters. Both parameters are used within conditional expressions to determine which warning message to show.

image

In the third call to Report(), notice that the wind speed is just as strong as when it was called the first time, yet, as shown next, no wind warning is displayed. The warning does not display because the Boolean parameter showWarning is false and this is recognized in the first logical OR.

Wind speed = 74 mph. Warning: possible wind damage!
Wind speed = 35 mph. No wind warnings at this time.
Wind speed = 74 mph. No wind warnings at this time.

Image

Conditional (Ternary) Operators

Conditional operators can be used to return different values based on the outcome of a simple conditional expression. Conditional operators are sometimes called ternary operators. The ternary operator offers a shorthand alternative to writing an if-else block. To implement the conditional operator, place a question mark, ?, before the assignment value used when a conditional expression is true. This assignment statement is followed by a colon, :, along with the assignment value to be used when the conditional expression is false. In the following case, message is assigned the value “Wind Alert!” when windSpeed exceeds the minimum; otherwise, message is assigned the value “Safe!”:

// Assign “Wind Alert!” if wind speed is greater than minimum. Otherwise
// assign “Safe!”.
string message = windSpeed >= TORNADO_MIN ? “Wind Alert!” : “Safe!”;

CAUTION     

Conditional operators offer convenient shorthand syntax. However, this condensed format is sometimes difficult to read and step through while debugging. If you have trouble debugging a conditional operator, you might try breaking up the instructions and using an if-else statement to achieve the same result.



Example 5-3 Conditional (Ternary) Operators


This example shows the full implementation of a conditional operator to assign a tornado alert message if wind speeds are greater than or equal to 73 miles per hour:

image

The output shows the value that is assigned when the conditional expression is false:

Tornado conditions not present.

Image

Switches

A switch is another conditional structure that provides a selection of case values to determine which code block to execute. The switch structure begins with a header where one parameter is passed in. The parameter value is then sequentially compared with case values of the same data type inside the switch. If a case value matches the parameter value from the switch header, the program enters that code block. When encountering the break statement, the program exits the switch structure. You may also include a default condition at the end of the switch structure to select instructions when no other cases match.

The following example shows the switch header with a parameter named tornadoRating. This parameter value is matched against case values in the list. For this example there is only one case, which has a value of F1. The default case is selected when no other cases match the parameter.

image



Example 5-4 Switches


This full example uses a simple switch to assign and display statistics about tornadoes. Notice how the cases are indented and code for each case is indented as well. The code for each case is terminated with a break statement.

image

When observing the output, you can see that the default option is selected for the F5 tornado since statistics are not available for this option:

* Statistics for F2 tornado*
Minimum wind speed: 112

* Statistics for F5 tornado*
Information not available.

Image

Loops

As mentioned previously, loops are structures that repeatedly execute blocks of code while a condition remains true. The loop’s ability to execute thousands or even millions of instructions extremely quickly provides powerful flexibility for processing data, creating animations, and performing repetitive tasks where automation is needed. The four most common types of C# loops are presented in this chapter:

Image   for loops

Image   while loops

Image   do while loops

Image   foreach loops

For Loops

For loops are one of the more common types of loops. These loops start with a header, which contains three instructions:

Image   The first instruction sets the initial value for a counter. To restrict the counter’s scope to the loop only, the counter is usually declared and initialized in this first instruction of the header. The first instruction is executed only one time, when the program enters the loop.

Image   The second instruction of the loop header is a conditional expression that is evaluated for every iteration of the loop—if true, the instructions within the code block of the loop are executed.

Image   The third instruction of the for loop modifies the counter variable, usually with an increment or decrement. Starting at the second loop iteration, the third instruction is executed before the conditional expression is evaluated to determine whether or not to execute the code block again.

TIP      

Often, the counter in a for loop is given the name i, for index. This practice may at first appear to contradict the practice of always using descriptive variable names. However, the variable name i is a commonly accepted shorthand name. If nested loops use counters too, they are often assigned consecutive letters of the alphabet as names, such as j and k.

Code to be executed by the for loop is nested and left-aligned between opening and closing curly braces:

image



Example 5-5 For Loops


This example shows how a for loop can iterate through all elements of an array and print them to the console:

image

When running the program, the elements of the array are obtained and printed while using the counter as a reference for the array:

Element[0] = a
Element[1] = b
Element[2] = c
Element[3] = d

Image



Example 5-6 Nested For Loops


This example shows how helpful loops can be for data processing. In this case, the code calculates daily interest on a bank balance for three weeks. The week is tracked with the outer loop, and the day of the week is tracked with the inner loop.

NOTE      

This example uses ToString(“N2”) to round the number output to two decimal places. More on rounding will be discussed in Chapter 6.

image

The output shows the cumulative savings that are calculated within the loops:

Daily Balance During Week 1
23.00  23.01  23.01  23.02  23.02  23.03  23.03

Daily Balance During Week 2
23.04  23.04  23.04  23.05  23.05  23.06  23.06

Daily Balance During Week 3
23.07  23.07  23.08  23.08  23.08  23.09  23.09

Image



Try This 5-2 Nested Loops


This exercise offers you practice with for loops and with nesting.

1. Write a program that uses three for loops with counters named i, j, and k. The for loop with the counter named j is nested inside the for loop with the counter named i. The for loop with the counter named k is nested inside the for loop with the counter named j.

2. Design your program to dynamically generate the following output:

    i=0 j=0 k=0
i=0 j=0 k=1
i=0 j=1 k=0
i=0 j=1 k=1
i=1 j=0 k=0
i=1 j=0 k=1
i=1 j=1 k=0
i=1 j=1 k=1

Image

While Loops

A while loop repeats instructions in its block as long as a specific condition is true. The keyword while starts the header. A conditional expression is inside the header. As long as the conditional expression is true, code within the loop block is executed. Instructions within the loop block are repeated until the conditional expression is false.

image



Example 5-7 While Loops


This example shows how a practical application of the while loop could calculate a bank balance until the total balance falls below zero:

image

No funds are deposited and the balance is initially low. Over time, the service charges outweigh the interest earned and the account balance falls below zero:

End of Month 1: Balance = 39.79
End of Month 2: Balance = 29.52
End of Month 3: Balance = 19.19
End of Month 4: Balance = 8.80
End of Month 5: Balance = -1.65

Image

Do While Loops

Do while loops are similar to while loops. However, the do while loop is always executed at least once, because the conditional expression is evaluated at the end. The keyword do starts this loop. The loop ends with the while keyword and a conditional expression in parentheses.

image



Example 5-8 Do While Loops


This example is slightly different from Example 5-7 because it allows the program to execute the code within the do while loop block at least once even though the balance is zero:

image

Even with a zero balance, the loop executes once to deduct service charges for the first month before it terminates:

End of Month 1: Balance = -10.50

Image

Foreach Loops

A foreach loop allows you to iterate through a collection of similarly typed objects. The keyword foreach starts the loop header. A declaration within the header creates a temporary variable to store an item from the collection. The temporary variable is followed by the keyword in and the collection reference.

image



Example 5-9 Foreach Loops


Since an array is actually a collection of similarly typed objects, you can use a foreach loop to iterate through the values stored within it. This example shows how to use a foreach loop to iterate through an array of names:

image

As expected when running the program, each name in the array is displayed on a separate line:

Jane.
Brad.
Kara.

Image

Comparing Loop Types

With multiple loop types to choose from, let’s consider the advantages of each:

Image   for loops allow convenient iteration through collections that have enumerable indexes, such as arrays.

Image   while loops enable repeated execution of code blocks when nonnumeric or complex conditions must be checked before iterating.

Image   do while loops share the same advantages of the while loop, but do while loops ensure that the loop iterates at least once.

Image   foreach loops can iterate through any type of collection.

Break Statements

Break statements force the program to exit the current loop when they are encountered. All C# loop types allow break statements.



Example 5-10 Break Statements


In this example, a menu prompts the program user to press 1 to keep running the program or press 2 to quit. The menu options and instructions are driven from a loop. When the user enters 2, the break statement forces the program to exit the loop.

image

Here is some sample output. The user chooses to keep running the program during the first iteration. During the second iteration, the user chooses 2 to exit.

** Menu **
1. Keep running this program.
2. Quit.
1
You have chosen to keep running.


** Menu **
1. Keep running this program.
2. Quit.
2
The program has been terminated.

Image

Continue Statement

A continue statement allows you to bypass all remaining instructions in a loop block to return to the top of the loop.



Example 5-11 Continue Statements


This example emulates a simplified game of 21 where the player can continually draw random playing cards, which have values between 1 and 11. The goal of the game is to get a sum of cards as close to 21 as possible without going over. Every time the program iterates through the loop, a random playing card value is generated and printed. If the sum of the card values drawn is less than or equal to 14, the continue statement forces the program to skip the remaining instructions within the loop to return to the top. If the sum of card values is 21, a message is printed to indicate that the player has won, and then the score is printed and the program breaks out of the loop. If the card value sum exceeds 21, a message is printed to indicate that the player has lost, and then the score is printed and the program breaks out of the loop.

image

image

This random set of output indicates that the loop encountered the continue statement twice before exiting during the third iteration:

Card number: 10
Card number: 7
Your score is 17.

Image

 

Image Chapter 5 Self Test


The following questions are intended to help reinforce your comprehension of the concepts covered in this chapter. The answers can be found in the accompanying online Appendix B, “Answers to the Self Tests.”

1. Given the following declarations,

    image

     indicate if the following conditional expressions are true or false:

    A. ____ !OVERRIDE_REQUEST || age >= MIN_AGE && age <= MAX_AGE

    B. ____ OVERRIDE_REQUEST || age >= MIN_AGE && age <= MAX_AGE

    C. ____ !OVERRIDE_REQUEST && age >= MIN_AGE && age <= MIN_AGE

    D. ____ !OVERRIDE_REQUEST || age < MIN_AGE || age > MAX_AGE

2. Add a conditional block to the ShowWarning() method in Example 5-1 to output a “Devastating damage warning.” message when the tornado strength equals F4. You will need to create a constant for this extra strength classification. Test this new method by assigning F4 to the strength variable inside the Main() method and then calling ShowWarning().

3. Write a small program that declares a number variable with a suitable data type to store a temperature in Celsius. Assign the value of 19.3 to this variable. Then, convert this value to Fahrenheit and store the result in a different variable. Note that Fahrenheit = (Celsius * 9/5) + 32. Print both the original Celsius and Fahrenheit values in the window.

Image   If the Fahrenheit value is less than or equal to 32, print “I am cold.”

Image   If the Fahrenheit value is greater than 32 and less than 65, print “It’s chilly out.”

Image   If the Fahrenheit value is greater than or equal to 65 and less than 80, print “This feels good.”

Image   If the Fahrenheit value is greater than or equal to 80, then print “It is hot out.”

4. Modify Example 5-4 to include a case statement that shows the wind speed that can lead to F3 tornadoes. (F3 tornadoes can occur when speeds reach 207 miles per hour.) Test the new case by calling the ShowData() method with F3 as the rating.

5. Write a small program to input a string value from a program user. To input the value, you can use this instruction:

    string input = Console.ReadLine();

    Use a switch to determine if the user types a when prompted. If the user types a, the program outputs “You pressed a.” If the user types b, the program outputs “You pressed b.” If the user types anything else, the program outputs “You did not press a or b.”

6. Write a program that declares and initializes a bank balance of $10,000. Inside a for loop, calculate the interest on the current balance and add it to the current balance. The interest rate is 7 percent per year. Output the updated balance with interest to the window. Perform the operations in the loop 25 times to determine what the cumulative balance will be after 25 years.

7. Write the same program as in question 6, but this time use a while loop.

8. Write the same program as in question 6, but this time use a do while loop.

9. Write a small program that creates an array for storing float values. Then store 13.3f, 14.2f, and 5.2f in it. Next, using a foreach loop, iterate through the array to print values stored in the array to the window.