Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 – Control Structures: Part 2

Similar presentations


Presentation on theme: "Chapter 5 – Control Structures: Part 2"— Presentation transcript:

1 Chapter 5 – Control Structures: Part 2
Outline Introduction Essentials of Counter-Controlled Repetition for Repetition Structure Examples Using the for Structure switch Multiple-Selection Structure do/while Repetition Structure Statements break and continue Logical and Conditional Operators Structured-Programming Summary

2 5.2 Essentials of Counter Controlled Repetition
Control variable The variable used to determine if the loop continues Initial value of the control variable Incrementing/decrementing of the variable The condition When the looping should continue

3 WhileCounter.cs Program Output
1 // Fig. 5.1: WhileCounter.cs 2 // Counter-controlled repetition. 3 4 using System; 5 6 class WhileCounter 7 { static void Main( string[] args ) { int counter = 1; // initialization 11 while ( counter <= 5 ) // repetition condition { Console.WriteLine( counter ); counter++; // increment 16 } // end while 18 } // end method Main 20 21 } // end class WhileCounter WhileCounter.cs Program Output This is where the counter variable is initialized. It is set to 1. The loop will continue until counter is greater than five (it will stop once it gets to six) The counter is incremented and 1 is added to it 1 2 3 4 5

4 5.3 for Repetition Structure
The for repetition structure Syntax: for (Expression1, Expression2, Expression3) Expression1 = names the control variable Can contain several variables Expression2 = loop-continuation condition Expression3 = incrementing/decrementing If Expression1 has several variables, Expression3 must have several variables accordingly ++counter and counter++ are equivalent Variable scope Expression1 can only be used in the body of the for loop When the loop ends the variable expires

5 5.3 for Repetition Structure
( int counter = 1; counter <= 5; counter++ ) Initial value of control variable Increment Control variable name Final value keyword Loop-continuation condition Fig. 5.3 Components of a typical for header.

6 5.3 for Repetition Structure
Establish initial value of control variable. int counter = 1 Determine if final value of control variable has been reached. true Console.WriteLine counter <= 10 counter++ ( counter * 10 ); Increment the control variable. false Body of loop (this may be multiple statements) Fig. 5.4 Flowcharting a typical for repetition structure.

7 ForCounter.cs Program Output
1 // Fig. 5.2: ForCounter.cs 2 // Counter-controlled repetition with the for structure. 3 4 using System; 5 6 class ForCounter 7 { static void Main( string[] args ) { // initialization, repetition condition and incrementing // are all included in the for structure for ( int counter = 1; counter <= 5; counter++ ) Console.WriteLine( counter ); } 15 } This is where the counter variable is initialized. It is set to 1. ForCounter.cs Program Output The counter is incremented (1 is added to it) The loop will continue until counter is greater than five (it will stop once it gets to six) 1 2 3 4 5

8 5.4 Examples Using the for Structure
Increment/Decrement When incrementing In most cases < or <= is used When decrementing In most cases > or >= is used Message boxes Buttons OK OKCancel YesNo AbortRetryIgnore YesNoCancel RetryCancel

9 5.4 Examples Using the for Structure
Massages boxes Icons Exclamation Question Error Information Formatting (variable : format) Table 5.9 lists some formatting codes

10 Once the number is greater than 100 the loop breaks
1 // Fig. 5.5: Sum.cs 2 // Summation with the for structure. 3 4 using System; 5 using System.Windows.Forms; 6 7 class Sum 8 { static void Main( string[] args ) { int sum = 0; 12 for ( int number = 2; number <= 100; number += 2 ) sum += number; 15 MessageBox.Show( "The sum is " + sum, "Sum Even Integers from 2 to 100", MessageBoxButtons.OK, MessageBoxIcon.Information ); 20 } // end method Main 22 23 } // end class Sum Sum.cs Program Output Once the number is greater than 100 the loop breaks The counter. It is initialized to 2 Increments number by 2 every time the loop starts over The caption of the message box The title of the message box Displays a message box with an OK button Has the message box contain an information icon Argument 4: MessageBox Icon (Optional) Argument 3: OK dialog button. (Optional) Argument 2: Title bar string (Optional) Argument 1: Message to display

11 5.4 Examples Using the for Structure

12 5.4 Examples Using the for Structure

13 Formats amount to have a currency formatting ($0.00)
1 // Fig. 5.8: Interest.cs 2 // Calculating compound interest. 3 4 using System; 5 using System.Windows.Forms; 6 7 class Interest 8 { static void Main( string[] args ) { decimal amount, principal = ( decimal ) ; double rate = .05; string output; 14 output = "Year\tAmount on deposit\n"; 16 for ( int year = 1; year <= 10; year++ ) { amount = principal * ( decimal ) Math.Pow( rate, year ); 21 output += year + "\t" + String.Format( "{0:C}", amount ) + "\n"; } 25 MessageBox.Show( output, "Compound Interest", MessageBoxButtons.OK, MessageBoxIcon.Information ); 28 } // end method Main 30 31 } // end class Interest Interest.cs Loops through 10 times starting at 1 and ending at 10, adding 1 to the counter (year) each time Formats amount to have a currency formatting ($0.00) Insert a Tab Creates a message box that displays the output with a title of “Compound Interest” has an OK button and an information icon

14 Interest.cs Program Output

15 5.4 Examples Using the for Structure

16 5.5 switch Multiple-Selection Structure
The switch statement Constant expressions String Integral Cases Case ‘x’ : Use of constant variable cases Empty cases The default case The break statement Exit the switch statement

17 Prompt the user for a grade and store it into the grade variable
1 // Fig. 5.10: SwitchTest.cs 2 // Counting letter grades. 3 4 using System; 5 6 class SwitchTest 7 { static void Main( string[] args ) { char grade; // one grade int aCount = 0, // number of As bCount = 0, // number of Bs cCount = 0, // number of Cs dCount = 0, // number of Ds fCount = 0; // number of Fs 16 for ( int i = 1; i <= 10; i++ ) { Console.Write( "Enter a letter grade: " ); grade = Char.Parse( Console.ReadLine() ); 21 switch ( grade ) { case 'A': // grade is uppercase A case 'a': // or lowercase a aCount; break; 28 case 'B': // grade is uppercase B case 'b': // or lowercase b bCount; break; 33 SwitchTest.cs A for loop that initializes i to 1, loops 10 times and increments i by one each time Each of these variables acts as a counter so they are initialized to zero Prompt the user for a grade and store it into the grade variable The start of the switch statement. The grade variable is used as the data to be tested for each case. Both cases add one to aCount case ‘A’ is empty so it is the same as case ‘a’ The break statement is used to exit the switch statement and not perform the rest of the operations Both case ‘B’ and case ‘b’ add one to the bCount variable

18 Both cases add 1 to cCount
case 'C': // grade is uppercase C case 'c': // or lowercase c cCount; break; 38 case 'D': // grade is uppercase D case 'd': // or lowercase d dCount; break; 43 case 'F': // grade is uppercase F case 'f': // or lowercase f fCount; break; 48 default: // processes all other characters Console.WriteLine( "Incorrect letter grade entered." + "\nGrade not added to totals." ); break; 54 } // end switch 56 } // end for 58 Console.WriteLine( "\nTotals for each letter grade are:\nA: {0}" + "\nB: {1}\nC: {2}\nD: {3}\nF: {4}", aCount, bCount, cCount, dCount, fCount ); 63 } // end method Main 65 66 } // end class SwitchTest Both cases add 1 to cCount SwitchTest.cs If grade equals D or d add one to dCount Add one to fCount if grade equals F or f If non of the cases are equal to the value of grade then the default case is executed Display the results

19 SwitchTest.cs Program Output
Enter a letter grade: a Enter a letter grade: A Enter a letter grade: c Enter a letter grade: F Enter a letter grade: z Incorrect letter grade entered. Grade not added to totals. Enter a letter grade: D Enter a letter grade: d Enter a letter grade: B Enter a letter grade: C Totals for each letter grade are: A: 3 B: 1 C: 2 D: 2 F: 1 SwitchTest.cs Program Output

20 5.5 switch Multiple-Selection Structure
break; case : a a action(s) true false . b action(s) z z action(s) default action(s) b Fig Flowcharting the switch multiple-selection structure.

21 5.6 do/while Repetition Structure
The while loops vs. the do/while loops Using a while loop Condition is tested The the action is performed Loop could be skipped altogether Using a do/while loop Action is performed Then the loop condition is tested Loop must be run though once Always uses brackets ({) to prevent confusion

22 DoWhileLoop.cs Program Output
1 // Fig. 5.12: DoWhileLoop.cs 2 // The do/while repetition structure. 3 4 using System; 5 6 class DoWhileLoop 7 { static void Main( string[] args ) { int counter = 1; 11 do { Console.WriteLine( counter ); counter++; } while ( counter <= 5 ); 17 } // end method Main 19 20 } // end class DoWhileLoop DoWhileLoop.cs Program Output The counter is initialized to one These actions are performed at least one The incrementing task Continue looping as long as counter is less than 6 1 2 3 4 5

23 5.6 do/while Repetition Structure
true false action(s) condition Fig Flowcharting the do/while repetition structure.

24 5.7 Statements break and continue
Use Used to alter the flow of control The break statement Used to exit a loop early The continue statement Used to skip the rest of the statements and begin the loop at the first statement in the loop Programs can be completed without their usage

25 A loop that starts at one, goes to ten, and increments by one
1 // Fig. 5.14: BreakTest.cs 2 // Using the break statement in a for structure. 3 4 using System; 5 using System.Windows.Forms; 6 7 class BreakTest 8 { static void Main( string[] args ) { string output = ""; int count; 13 for ( count = 1; count <= 10; count++ ) { if ( count == 5 ) break; // skip remaining code in loop // if count == 5 19 output += count + " "; 21 } // end for loop 23 output += "\nBroke out of loop at count = " + count; 25 MessageBox.Show( output, "Demonstrating the break statement", MessageBoxButtons.OK, MessageBoxIcon.Information ); 28 } // end method Main 30 31 } // end class BreakTest BreakTest.cs A loop that starts at one, goes to ten, and increments by one If count = 5 then break out of the loop Displays a message box the displays the output, has a title of “demonstrating the break statement,” uses an OK button, and displays an information icon Display the last value that the counter was at before it broke

26 BreakTest.cs Program Output

27 A loop that starts at 1, goes to 10, and increments by 1
1 // Fig. 5.15: ContinueTest.cs 2 // Using the continue statement in a for structure. 3 4 using System; 5 using System.Windows.Forms; 6 7 class ContinueTest 8 { static void Main( string[] args ) { string output = ""; 12 for ( int count = 1; count <= 10; count++ ) { if ( count == 5 ) continue; // skip remaining code in loop // only if count == 5 18 output += count + " "; } 21 output += "\nUsed continue to skip printing 5"; 23 MessageBox.Show( output, "Using the continue statement", MessageBoxButtons.OK, MessageBoxIcon.Information ); 26 } // end method Main 28 29 } // end class ContinueTest ContinueTest.cs A loop that starts at 1, goes to 10, and increments by 1 If count = 5 then continue looping causing the program to skip the rest of the loop Create a message box that displays the output, has the title “using the continue statement,” uses an OK button, and displays an information icon.

28 ContinueTest.cs Program Output

29 5.8 Logical and Conditional Operators
Conditional AND (&&) Logical OR (|) Conditional OR (||) Logical exclusive OR or XOR (^) Logical NOT (!) Can be avoided if desired by using other conditional operators Used to add multiple conditions to a statement

30 5.8 Logical and Conditional Operators

31 5.8 Logical and Conditional Operators

32 Outputs a truth table for the conditional AND operator (&&)
1 // Fig. 5.20: LogicalOperators.cs 2 // Demonstrating the logical operators. 3 using System; 4 5 class LogicalOperators 6 { // main entry point for application static void Main( string[] args ) { // testing the conditional AND operator (&&) Console.WriteLine( "Conditional AND (&&)" + "\nfalse && false: " + ( false && false ) + "\nfalse && true: " + ( false && true ) + "\ntrue && false: " + ( true && false ) + "\ntrue && true: " + ( true && true ) ); 16 // testing the conditional OR operator (||) Console.WriteLine( "\n\nConditional OR (||)" + "\nfalse || false: " + ( false || false ) + "\nfalse || true: " + ( false || true ) + "\ntrue || false: " + ( true || false ) + "\ntrue || true: " + ( true || true ) ); 23 // testing the logical AND operator (&) Console.WriteLine( "\n\nLogical AND (&)" + "\nfalse & false: " + ( false & false ) + "\nfalse & true: " + ( false & true ) + "\ntrue & false: " + ( true & false ) + "\ntrue & true: " + ( true & true ) ); 30 LogicalOperators.cs Outputs a truth table for the conditional AND operator (&&) Only true if both inputs are true Outputs a truth table for the conditional OR operator (||) Only false if both inputs are false Outputs a truth table for the logical AND operator (&) The result is only true if both are true

33 LogicalOperators.cs Program Output
// testing the logical OR operator (|) Console.WriteLine( "\n\nLogical OR (|)" + "\nfalse | false: " + ( false | false ) + "\nfalse | true: " + ( false | true ) + "\ntrue | false: " + ( true | false ) + "\ntrue | true: " + ( true | true ) ); 37 // testing the logical exclusive OR operator (^) Console.WriteLine( "\n\nLogical exclusive OR (^)" + "\nfalse ^ false: " + ( false ^ false ) + "\nfalse ^ true: " + ( false ^ true ) + "\ntrue ^ false: " + ( true ^ false ) + "\ntrue ^ true: " + ( true ^ true ) ); 44 // testing the logical NOT operator (!) Console.WriteLine( "\n\nLogical NOT (!)" + "\n!false: " + ( !false ) + "\n!true: " + ( !true ) ); } 50 } Outputs a truth table for the logical OR operator (||) If one is true the result is true LogicalOperators.cs Program Output Outputs a truth table for the logical exclusive OR operator (||) Returns false when the two conditionals are the same Outputs a truth table for the logical NOT operator (!) Returns the opposite as the input Conditional AND (&&) false && false: False false && true: False true && false: False true && true: True Conditional OR (||) false || false: False false || true: True true || false: True true || true: True

34 LogicalOperators.cs Program Output
Logical AND (&) false & false: False false & true: False true & false: False true & true: True Logical OR (|) false | false: False false | true: True true | false: True true | true: True Logical exclusive OR (^) false ^ false: False false ^ true: True true ^ false: True true ^ true: False Logical NOT (!) !false: True !true: False LogicalOperators.cs Program Output

35 5.9 Structured Programming Summary
Control Structures Only one entrance Only one exit Building blocks to programming Allow nesting Makes code neater and easier to follow No overlapping structures The goto keyword

36 5.9 Structured Programming Summary
3 forms of control necessary Many ways to implement these controls Sequential (only 1 way) Straight forward programming Selection (3 ways) if selection (one choice) if/else selection (two choices) switch statement (multiple choices) Repetition (4 ways) while structure do/while structure for structure foreach structure (chapter 7)

37 5.9 Structured Programming Summary

38 5.9 Structured Programming Summary
Sequence . . Fig C#’s single-entry/single-exit sequence, selection and repetition structures. (part 1)

39 5.9 Structured Programming Summary
F if structure (single selection) else/if structure (double selection) switch structure (multiple selections) . . break . Selection Fig C#’s single-entry/single-exit sequence, selection and repetition structures. (part 2)

40 5.9 Structured Programming Summary
Repetition T F while structure do/while structure for structure/foreach structure Fig C#’s single-entry/single-exit sequence, selection and repetition structures. (part 3)

41 5.9 Structured Programming Summary

42 5.9 Structured Programming Summary
Fig Simplest flowchart.

43 5.9 Structured Programming Summary
Rule 2 Rule 2 Rule 2 . . . Fig Repeatedly applying rule 2 of Fig. 5.23 to the simplest flowchart.

44 5.9 Structured Programming Summary
Rule 3 Fig Applying rule 3 of Fig. 5.23 to the simplest flowchart.

45 5.9 Structured Programming Summary
Stacked building blocks Overlapping building blocks (illegal in structured programs) Nested building blocks Fig Stacked, nested and overlapped building blocks.

46 5.9 Structured Programming Summary
Fig Unstructured flowchart.


Download ppt "Chapter 5 – Control Structures: Part 2"

Similar presentations


Ads by Google