Upload
cassandra-sherman
View
217
Download
0
Embed Size (px)
Citation preview
Jozef Goetz, 2015
1
2011 - 2015 Pearson Education, Inc. All rights reserved.
2002 Prentice Hall. All rights reserved.
expanded by J. Goetz, 2014
credits:
Jozef Goetz, 2015
2
Chapter 5 – Control Structures Part 1
Outline5.1 Introduction5.2 Algorithms5.3 Pseudocode5.4 Control Structures5.5 if Selection Structure5.6 use if/else Selection Structure5.7 use while Repetition Structure5.8 Formulating Algorithms: Case Study 1
(Counter-Controlled Repetition)5.9 Formulating Algorithms with Top-Down, Stepwise Refinement:
Case Study 2 (Sentinel-Controlled Repetition)5.10 Formulating Algorithms with Top-Down, Stepwise Refinement:
Case Study 3 (Nested Control Structures)5.11 Assignment Operators5.12 Increment and Decrement Operators
5.13 Simple Types
Jozef Goetz, 2015
3
The wheel is come full circle. William Shakespeare
Let’s all move one place on. Lewis Carroll
How many apples fell on Newton’s head before he took the hint! Robert Frost
All the evolution we know of proceeds from the vague to the definite. Charles Sanders Peirce
Jozef Goetz, 2015
4Objectives
To understand basic problem-solving techniques of programming.
To develop algorithms through the process of top-down, stepwise refinement.
To use the if and if/else selection structures to choose among alternative actions.
To use the while repetition structure to execute statements in a program repeatedly.
To understand counter-controlled repetition and sentinel-controlled repetition.
To use the increment, decrement and assignment operators.
Jozef Goetz, 2015
55.1 Introduction
Before writing program Have thorough understanding of problem Carefully planned approach for solving it
While writing program Know what “building blocks” are available Use good programming principles
We learn about Control Structures Structured-programming principle Control structures help build and manipulate objects
(Chapter 5-8)
Jozef Goetz, 2015
65.2 Algorithms
Algorithm is a procedure for solving a problem in terms of Series of actions in specific order
The actions executed The order in which actions execute
Example: "Rise and Shine" algorithm Get out of bed, take off pajamas, take a shower, get dressed, eat breakfast, carpool to
work
• Program control Specifying the order in which actions execute
Control structures help specify this order
Algorithmic thinking is a formal and structured thinking type which helps us to design and understand modern software. Learning algorithmic thinking is not easy and needs a lot of practice and
endurance/patience. Experience has shown that the most difficult part of solving a problem on a computer is
developing the algorithm for the solution.
Jozef Goetz, 2015
75.2 Algorithms
Computational thinking means thinking algorithmically and with the ability to apply mathematical concepts such as induction to develop more efficient, fair, and secure solutions.
Center for Computational Thinking, Carnegie Mellon
Tim the Train: Binpacking
Problem: Given is a sequence of parts. Find a sequence of commands that fill the wagons of the
train with as many parts as possible. The wagons must not be overloaded.
Jozef Goetz, 2015
85.3 Pseudocode
Pseudocode Artificial, informal language
Helps develop algorithms
Similar to everyday English Not actually executed on computers “Think out” program before writing it
Easy to convert into corresponding C# program
Consists only of executable statements
• Declarations are not executable statements
– Actions: input, output, calculation
Jozef Goetz, 2015
95.4 Control Structures
Sequential execution Execute statements in the order they appear in the code
Transfer of control (flow of control) Changing the order in which statements execute
All programs can be written in terms of only three control structures:
sequence selection
– The if and if/else statements
– The goto statement• No longer used unless absolutely needed• Causes many readability and debuging problems
repetition
– The while and do/while loops (chapter 5)
– The for and foreach loops (chapter 6)
Jozef Goetz, 2015
105.4 Control Structures
Flowchart Graphical representation of an algorithm Drawn using symbols connected by arrows called flowlines
Rectangle symbol (action symbol)
– Indicates any type of action Diamond symbol (decision symbol)
– Indicates that a decision to be made Oval symbol:
– Indicates beginning or end of a program, or a section of code (circles)
add grade to total
add 1 to counter
total = total + grade;
counter = counter + 1;
Indicates a portion of an algorithm
Jozef Goetz, 2015
115.4 Control Structures
add grade to total
add 1 to counter
total = total + grade;
counter = counter + 1;
Fig. 5.1 Flowcharting C#’s sequence structure.
•Flowchart of sequence structure: Two actions performed in order
When drawing a portion, small circles is used
When flowcharting a complete algorithm
Oval containing "Begin" is first symbol
Oval containing "End" is last symbol
When drawing a portion, small circles usedFig. 6.20 C#’s single-entry/single-exit sequence, selection and repetition structures. (part 1)
Sequence
.
.
Jozef Goetz, 2015
125.4 Control Structures Sequential execution
Program statements execute one after the other
Transfer of control Next statement executed is not the next one in
sequence. Overuse of goto in 1960's led to many problems
structured programming became almost synonymous with “goto” elimination
C# has a goto statement, but it is used to transfer control out of a nested scope
Three control statements can specify order of statements Sequence structure Selection structure Repetition structure
Bohm and Jacopini All programs can be written in terms of 3 control
structures Sequence, Selection and Repetition
Jozef Goetz, 2015
135.4 Control Structures
8 control structures C# and Java has a sequence structure “built-in” C# provides three selection structures
if if/else (double selection) Switch
C# provides four (Java first three, VB.NET seven) repetition structures Repeatedly performs an action while its loop-continuation condition remains true while - performs the actions in its body zero or more times do/while - performs the actions in its body one or more times for - performs the actions in its body zero or more times foreach (specific for C#, VB.NET) - - performs the actions in its body zero
or more times
Each of these words is a C# keyword Words reserved for C# don’t use as identifiers or variable names
Jozef Goetz, 2015
145.4 Control Structures
Single-entry/single-exit control structures make it easy to build programs
Connect exit point of one control structure to entry point of the next (control-structure stacking)
Assemble program (connect control structures) by
Stacking– Placing one after another
Nesting– Inserting of one structure into another
Any these control structures can be combined in only 2 ways: control-structure stacking and nesting.
Jozef Goetz, 2015
15
6.9 Structured-Programming Summary
Fig. 6.20 | C#’s single-entry/single-exit sequence, selection and repetition statements.
Jozef Goetz, 2015
16 Structured Programming Summary
Stacked, nested and overlapped building blocks.
Stacked building blocks
Overlapping building blocks (illegal in structured programs)
Nested building blocks
Combination of control structures:
1. Stacking
Placing one after another
2. Nesting
Inserting of one structure into another
Jozef Goetz, 2015
175.4 Control Structures (Cont.)
UML activity diagram (www.uml.org) Models the workflow (or activity) of a part of a software system Action-state symbols (rectangles with their sides replaced with outward-curving arcs)
Represent action expressions specifying actions to perform
Diamonds Decision symbols (explained in section 5.5) Merge symbols (explained in section 5.7)
Small circles Solid circle represents the activity’s initial state Solid circle surrounded by a hollow circle represents the activity’s final state
Transition arrows Indicate the order in which actions are performed
Notes (rectangles with the upper-right corners folded over) Explain the purposes of symbols (like comments in C#) Arc connected to the symbols they describe by dotted lines
<= Guard conditions
Jozef Goetz, 2015
18C# keywords
C# Keywords
abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach get goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed set short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using value virtual void volatile while Fig. C# keywords.
Jozef Goetz, 2015
195.5 if Selection Structure
The if structure Causes the program to make a selection
Chooses based on conditional Any expression that evaluates to a bool type True: perform an action False: skip the action
Single entry/exit point Require no semicolon in syntax
Jozef Goetz, 2015
205.5 The if Selection Structure
Selection structure Psuedocode statement
If student’s grade is greater than or equal to 60 Print “Passed”
code statement in C#if ( studentGrade >= 60 ) Console.WriteLine( "Passed" );
code statement in Javaif ( studentGrade >= 60 )
System.out.println( "Passed" );
Notice similarity
Jozef Goetz, 2015
21Fig. 5.2 | if single-selection statement UML activity diagram.
true
false
grade >= 60 print “Passed”
Flowchart example of the if selection structure
“if” is a single-entry/single-exit structure
Diamond symbol - decision symbol has two paths
Perform action only when condition is true
Important - indicates an decision is to be made
Decision can be made on anything that evaluates a value of data type boolean
true or false
Single-entry/single-exit structure
UML
Jozef Goetz, 2015
22Action/decision model of computing
1. Programmer assemble structures by stacking and nesting
2. Then defines actions and decisions
Jozef Goetz, 2015
235.6 The if/else Selection Structure
Selection structures if
Only performs an action if condition true
if/else Performs different action when condition true than when
condition false Psuedocode
If student’s grade is greater than or equal to 60Print “Passed”
elsePrint “Failed”
C# code: if ( studentGrade >= 60 )
Console.WriteLine( "Passed" ); else
Console.WriteLine( "Failed" );
Note spacing/indentation conventions
Indent both body statements of an if...else statement.
Jozef Goetz, 2015
245.6 The if/else Selection Structure
Flowchart of if/else structure Symbols (besides circles and arrows)
Rectangles: actions Diamonds: decisions
truefalse
print “Failed” print “Passed”
grade >= 60
Fig. 5.3 Flowcharting a double-selection if/else structure.
Jozef Goetz, 2015
255.6 The if/else Selection Structure
Ternary conditional operator (?:) Takes three arguments
(boolean value ? if true : if false) C#’s only ternary operator Similar to an if/else structure
Our pseudocode could be written:
Console.WriteLine( studentGrade >= 60 ? “Passed” : “Failed” );
Jozef Goetz, 2015
265.6 The if/else Selection Structure
Nested if/else structures Test for multiple cases Place if/else structures inside if/else structures If first condition met, other statements skipped
Nested structures: if ( studentGrade >= 90 )
Console.WriteLine( "A" );else if ( studentGrade >= 80 ) Console.WriteLine( "B" ); else if ( studentGrade >= 70 ) Console.WriteLine( "C" ); else if ( studentGrade >= 60 ) Console.WriteLine( "D" ); else Console.WriteLine( "F" );
Avoid deep indentation
else only executes when the if condition fails.
Once condition is met, rest of statements skipped.
Jozef Goetz, 2015
275.6 The if/else Selection Structure
Alternate form of nested structures Avoids deep indentation Preferred to previous format
if ( grade >= 90 ) Console.WriteLine( "A" );else if ( grade >= 80 ) Console.WriteLine( "B" );else if ( grade >= 70 ) Console.WriteLine( "C" );else if ( grade >= 60 ) Console.WriteLine( "D" );else Console.WriteLine( "F" );
As before, else only executes when the if condition fails.
Jozef Goetz, 2015
285.6 The if/else Selection Structure
Important note C# associates else with previous if unless
braces ({}) present
Dangling-else problemx = 2; y = 2;
if ( x > 5 ) if ( y > 5 ) Console.WriteLine( "x and y are > 5" );else Console.WriteLine( "x is <= 5" );
Does not execute as it appears, executes as if ( x > 5 )
if ( y > 5 ) Console.WriteLine("x and y are > 5" ); else Console.WriteLine("x is <= 5" );
If x <= 5, nothing is output,
Is logic OK?
Jozef Goetz, 2015
295.6 The if/else Selection Structure
Important note Must force structure to execute as intended
Use braces to indicate that second if in body of first if ( x > 5 )
{ if ( y > 5 ) Console.WriteLine("x and y are > 5" );}
else Console.WriteLine( "x is <= 5" );
Block statement (sometimes called a compound statement) Set of statements within braces
Can be used wherever a single statement can
if expects one statement in its body enclose multiple statements in braces to have one equivalent one
statement
Jozef Goetz, 2015
305.6 The if/else Selection Structure
Block Example:
if (grade >= 60) Console.WriteLine( "Passed" );else
{
Console.WriteLine( "Failed" ); Console.WriteLine( "You must take this course again." );}
Without braces, third WriteLine always executes
Block can contain declarations Example: body of Main
Jozef Goetz, 2015
315.6 The if/else Selection Structure
Errors
Syntax errors Caught by compiler Example: forgetting a brace in a block
Logic errors Have effect at execution time Non-fatal: program runs, but has incorrect output Fatal: program exits prematurely
Jozef Goetz, 2015
325.7 The while Repetition Structure while repetition structure
A Repeat action while some condition remains true while loop repeated until condition becomes false
Psuedocode:
While there are more items on my shopping list Purchase next item and cross it off my list
First statement after repetition structure executed
Body may be a single or block statement If condition initially false, body never executed
If there is no body what happens?
product <= 1000 product = 2 * producttrue
false
Find the first power of 2 larger than 1000
Jozef Goetz, 2015
33
Fig. 5.4 | while repetition statement UML activity diagram.
product <= 100 product = 3 * producttrue
false
Find the first power of 3 larger than 100
int product = 3;
while ( product <= 100 ) product = 3 * product;
Jozef Goetz, 2015
34Common Programming Error 5.3
Not providing in the body of a while statement an action that eventually causes the condition in the while to become false normally results in a logic error called an
infinite loop, in which the loop never terminates.
Jozef Goetz, 2015
355.8 Formulating Algorithms: Case
Study 1 (Counter Controlled Repetition- CCR)
Counter Controlled Repetition Used to enter data one at a time
Constant amount A counter is used to determine when the loop should break
When counter hits certain value, the statement terminates
Number of repetitions known
Jozef Goetz, 2015
365.8 Formulating Algorithms: Case
Study 1 (Counter Controlled Repetition)
•Illustrate how algorithms are developed - Consider class averaging problem
•Problem statement:
A class of 10 students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you.
Determine the class average on the quiz.
Jozef Goetz, 2015
375.8 Formulating Algorithms: Case Study 1 (Counter Controlled Repetition)
Set total to zero
Set grade counter to one
While grade counter is less than or equal to tenInput the next gradeAdd the grade into the totalAdd one to the grade counter
Set the class average to the total divided by tenPrint the class average
Total - used to accumulate sum of a series of values Initialize to zero to clear contents
Counter - variable used to count
Fig. 5.5 Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.
A total is a variable in which a script accumulates the sum of a series of values
•Variables that store totals should normally be initialized to zero before they are used in a program
2002 Prentice Hall.All rights reserved.
Outline38
1 // Fig. 4.7 ed1: Average1.cs2 // Class average with counter-controlled repetition.3 4 using System;5 6 class Average17 {8 static void Main( string[] args )9 {10 int total, // sum of grades11 gradeCounter, // number of grades entered12 gradeValue, // grade value13 average; // average of all grades14 15 // 1. initialization phase16 total = 0; // clear total17 gradeCounter = 1; // prepare to loop18 19 // 2. processing phase20 while ( gradeCounter <= 10 ) // loop 10 times21 {22 // prompt for input and read grade from user23 Console.Write( "Enter integer grade: " );24 25 // read input and convert to integer26 gradeValue = Int32.Parse( Console.ReadLine() );27 28 // add gradeValue to total29 total = total + gradeValue;30 31 // add 1 to gradeCounter32 gradeCounter = gradeCounter + 1;33 }
The while loop will loop through 10 times to get the grades of the 10 students
Initialize gradeCounter to 1
Accumulate the total of the 10 grades
Add 1 to the counter so the loop will eventually end
Initialize total to 0
Prompt the user to enter a grade
Set total to zeroSet grade counter to one
While grade counter is less than or equal to tenInput the next gradeAdd the grade into the totalAdd one to the grade counter
Set the class average to the total divided by tenPrint the class average
2002 Prentice Hall.All rights reserved.
Outline39
Average1.cs
Program Output
34 35 // 3. termination phase36 average = total / 10; // integer division37 38 // display average of exam grades39 Console.WriteLine( "\nClass average is {0}", average );40 41 } // end Main42 43 } // end class Average1
Enter integer grade: 100Enter integer grade: 88Enter integer grade: 93Enter integer grade: 55Enter integer grade: 68Enter integer grade: 77Enter integer grade: 83Enter integer grade: 95Enter integer grade: 73Enter integer grade: 62 Class average is 79
Divide the total by ten to get the average of the ten grades
Display the results
Jozef Goetz, 2015
40 1 // Fig. 5.6: GradeBookTest.cs
2 // Create GradeBook object and invoke its DetermineClassAverage method.
3 public class GradeBookTest
4 {
5 public static void Main( string[] args )
6 {
7 // create GradeBook object myGradeBook and
8 // pass course name to constructor
9 GradeBook myGradeBook = new GradeBook(
10 "CS101 Introduction to C# Programming" );
11
12 myGradeBook.DisplayMessage(); // display welcome message
13 myGradeBook.DetermineClassAverage(); // find average of 10 grades
14 } // end Main
15 } // end class GradeBookTest
Welcome to the grade book for CS101 Introduction to C# Programming! Enter grade: 88 Enter grade: 79 Enter grade: 95 Enter grade: 100 Enter grade: 48 Enter grade: 88 Enter grade: 92 Enter grade: 83 Enter grade: 90 Enter grade: 85
Total of all 10 grades is 848 Class average is 84
Outline
GradeBookTest.cs
Jozef Goetz, 2015
1 // Fig. 5.6: GradeBook.cs - class and driver approach (expanded Fig. 4.12)
2 // GradeBook class that solves class-average problem using
3 // counter-controlled repetition.
4 using System;
5
6 public class GradeBook
7 {
8 //private string courseName; // name of course this GradeBook represents
9
10 // constructor initializes courseName
11 public GradeBook( string name )
12 {
13 CourseName = name; // initializes courseName by using property
14 } // end constructor
15
16 // property to get and set the course name 17 public string CourseName { get; set; } 18 // end property CourseName
GradeBook.cs (1 of 3)
Jozef Goetz, 2015
4228
29 // display a welcome message to the GradeBook user
30 public void DisplayMessage()
31 {
32 // property CourseName gets the name of the course
33 Console.WriteLine( "Welcome to the grade book for\n{0}!\n",
34 CourseName );
35 } // end method DisplayMessage
36
37 // determine class average based on 10 grades entered by user
38 public void DetermineClassAverage()
39 {
40 int total; // sum of the grades entered by user
41 int gradeCounter; // number of the grade to be entered next
42 int grade; // grade value entered by the user
43 int average; // average of the grades
44
45 // initialization phase
46 total = 0; // initialize the total
47 gradeCounter = 1; // initialize the loop counter
GradeBook.cs (2 of 3)
Set total to zeroSet grade counter to one
While grade counter is less than or equal to ten
Input the next gradeAdd the grade into the totalAdd one to the grade counter
Set the class average to the total divided by tenPrint the class average
Welcome to the grade book forCS101 Introduction to C# Programming!Enter grade: 88Enter grade: 79Enter grade: 95Enter grade: 100Enter grade: 48Enter grade: 88Enter grade: 92Enter grade: 83Enter grade: 90Enter grade: 85Total of all 10 grades is 848Class average is 84
Jozef Goetz, 2015
4348
49 // processing phase
50 while ( gradeCounter <= 10 ) // loop 10 times
51 {
52 Console.Write( "Enter grade: " ); // prompt the user
53 grade = Convert.ToInt32( Console.ReadLine() ); // read grade
54 total = total + grade; // add the grade to total
55 gradeCounter = gradeCounter + 1; // increment the counter by 1
56 } // end while
57
58 // termination phase
59 average = total / 10; // integer division yields integer result
60
61 // display total and average of grades
62 Console.WriteLine( "\nTotal of all 10 grades is {0}", total );
63 Console.WriteLine( "Class average is {0}", average );
64 } // end method DetermineClassAverage
65 } // end class GradeBook
Outline GradeBook.cs
(3 of 3)
Welcome to the grade book forCS101 Introduction to C# Programming!Enter grade: 88Enter grade: 79Enter grade: 95Enter grade: 100Enter grade: 48Enter grade: 88Enter grade: 92Enter grade: 83Enter grade: 90Enter grade: 85Total of all 10 grades is 848Class average is 84
Set total to zeroSet grade counter to one
While grade counter is less than or equal to ten
Input the next gradeAdd the grade into the totalAdd one to the grade counter
Set the class average to the total divided by tenPrint the class average
Exc. Replace hard coded values 10 by variable
Jozef Goetz, 2015
44 1 // Fig. 5.7: GradeBookTest.cs
2 // Create GradeBook object and invoke its DetermineClassAverage method.
3 public class GradeBookTest
4 {
5 public static void Main( string[] args )
6 {
7 // create GradeBook object myGradeBook and
8 // pass course name to constructor
9 GradeBook myGradeBook = new GradeBook(
10 "CS101 Introduction to C# Programming" );
11
12 myGradeBook.DisplayMessage(); // display welcome message
13 myGradeBook.DetermineClassAverage(); // find average of 10 grades
14 } // end Main
15 } // end class GradeBookTest
Welcome to the grade book for CS101 Introduction to C# Programming! Enter grade: 88 Enter grade: 79 Enter grade: 95 Enter grade: 100 Enter grade: 48 Enter grade: 88 Enter grade: 92 Enter grade: 83 Enter grade: 90 Enter grade: 85
Total of all 10 grades is 848 Class average is 84
Outline
GradeBookTest.cs
Jozef Goetz, 2015
45Good Programming Practice
Separate declarations from other statements in methods with a blank line for readability.
All local variables must be definitely assigned before their values are used in expressions.
Initialize each counter and total, either in its declaration or in an assignment statement. Totals are normally initialized to 0. Counters are normally
initialized to 0 or 1, depending on how they are used (we will show examples of each).
Jozef Goetz, 2015
465.9 Formulating Algorithms with Top-
Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled
Repetition - SCR) Let us generalize the class-average problemDevelop a class-averaging program that will process an arbitrary number of grades each time the program is run Unknown number of students - how will the program end?
Sentinel value Also called signal dummy value or flag value Indicates “end of data entry” Loop ends when sentinel is entered Sentinel chosen so it cannot be a regular input (an acceptable input
value) -1 in this case
Average2.cs has indefinite repetition User enters sentinel value (-1) to end repetition
Jozef Goetz, 2015
475.9 Sentinel-Controlled Repetition
Top-down, stepwise refinement – technique essential to the development of well-structured algorithms Begin with pseudocode representation of the top
Determine the class average for the quiz Complete representation of program
Top usually too general - must be refined Divide top into a series of smaller tasks and list them in the
order in which they need to be performed
First refinementInitialize variablesInput, sum and count the quiz gradesCalculate and print the class average
Jozef Goetz, 2015
48Software Engineering Observation 5.2
Each refinement, as well as the top itself, is a complete specification of the algorithm — only the level of detail varies.
Jozef Goetz, 2015
495.9 Sentinel-Controlled Repetition
Refine "Initialize variables" to Initialize total to zero
Initialize counter to zero
Refine "Input, sum and count the quiz grades" to Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinelAdd this grade into the running totalAdd one to the grade counterInput the next grade (possibly the sentinel)
Refine "Calculate and print the class average" toIf the counter is not equal to zero
Set the average to the total divided by the counterPrint the average
elsePrint “No grades were entered”
Jozef Goetz, 2015
50
Initialize total to zeroInitialize counter to zero
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel Add this grade into the running totalAdd one to the grade counter
Input the next grade (possibly the sentinel)
If the counter is not equal to zeroSet the average to the total divided by the counterPrint the average
elsePrint “No grades were entered”
Fig. 5.8 Pseudocode algorithm that uses sentinel-controlled repetition to solve the class-average problem.
Set total to zero
Set grade counter to 1
While grade counter is less than or equal to ten
Input the next gradeAdd the grade into the totalAdd one to the grade counter
Set the class average to the total divided by tenPrint the class average
Fig. 5.5 Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.
Total - used to accumulate sum of a series of values
Initialize to zero to clear contents Counter - variable used to count
Jozef Goetz, 2015
51Software Engineering Observation 5.4
Terminate the top-down:
stepwise refinement process terminates when you have specified the pseudocode algorithm in sufficient detail for you to convert the pseudocode to C#.
Normally, implementing the C# application is then straightforward.
Jozef Goetz, 2015
525.9 Sentinel-Controlled Repetition
Many applications (programs) can be divided into three phases1. Initialization
Initializes the program variables
2. Processing Inputs data values, adjusts variables accordingly and calculates
3. Termination Prints the final results
Helps breakup of programs for top-down refinement
Upcoming program Use sentinel-controlled loop to calculate average Show program, then discuss
2002 Prentice Hall.All rights reserved.
Outline53
Average2.cs
1 // Fig. 4.9 ed1: Average2.cs2 // Class average with sentinel-controlled repetition.3 4 using System;5 6 class Average27 {8 static void Main( string[] args )9 {10 int total, // sum of grades11 gradeCounter, // number of grades entered12 gradeValue; // grade value13 14 double average; // average of all grades15 // note – double value may be only an approximation 16 // 1. initialization phase17 total = 0; // clear total18 gradeCounter = 0; // prepare to loop19 20 // 2. processing phase21 // prompt for input and convert to integer22 Console.Write( "Enter Integer Grade, -1 to Quit: " );23 gradeValue = Int32.Parse( Console.ReadLine() );24
The variable average is set to a double so that it can be more exact and have an answer with decimals
Variables gradeCounter and total are set to zero at the beginning
Get a value from the user and store it in gradeValue
Initialize total to zeroInitialize counter to zero
Input the first grade (possibly the sentinel)
2002 Prentice Hall.All rights reserved.
Outline54
25 // loop until a -1 is entered by user26 while ( gradeValue != -1 )27 {28 // add gradeValue to total29 total = total + gradeValue;30 31 // add 1 to gradeCounter32 gradeCounter = gradeCounter + 1;33 34 // prompt for input and read grade from user35 // convert grade from string to integer36 Console.Write( "Enter Integer Grade, -1 to Quit: " );37 gradeValue = Int32.Parse( Console.ReadLine() );38 39 } // end while40 41 // 3. termination phase42 // Make sure the total amount of entered grades was not 0 to prevent any errors42 if ( gradeCounter != 0 ) 43 {44 average = ( double ) total / gradeCounter; //double version of total is divided by the int
gradeCounter. gradeCounter is promoted to double; the calculation is performed and the result of the floating-point division is assigned to average
45 46 // display average of exam grades47 Console.WriteLine( "\nClass average is {0}", average );48 }49 else50 {51 Console.WriteLine( "\nNo grades were entered" );52 }53 54 } // end method Main55 56 } // end class Average2
Have the program loop as long as gradeValue is not -1
Prompt the user for another grade, this time it is in the loop so it can happen repeatedly
Divide the total by the number of times the program looped to find the average
Display the average
Inform user if no grades were entered
Enter Integer Grade, -1 to Quit: 97Enter Integer Grade, -1 to Quit: 88Enter Integer Grade, -1 to Quit: 72Enter Integer Grade, -1 to Quit: -1 Class average is 85.6666666666667
While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel)
If the counter is not equal to zero Set the average to the total divided by the counter Print the averageelse Print “No grades were entered”
Jozef Goetz, 2015
555.9 Sentinel-Controlled Repetition
Arithmetic Can only be performed between variables of same type Promotion (implicit conversion) - promote a data type to
another type
if ( gradeCounter != 0 ) { average = ( double ) total / gradeCounter; }
Cast operator (double) Creates a temporary floating-point copy of its
operand (total)– Using a cast operator this manner is called
explicit conversion– Value in total still an integer
Jozef Goetz, 2015
565.9 Sentinel-Controlled Repetitionif ( gradeCounter != 0 ) { average = ( double ) total / gradeCounter;
A temporary copy of total is a double gradeCounter (an int) is promoted to a double
Cast operators Available for all data types
– Parenthesis around type name: (type) Unary operator (one operand) - associates right to left
Floating point numbers are represented approximately by computers (#s are not precisely represented)
Not 100% accurate– Good approximation, fine for most applications
Floating number 10/3 = 3.333333... with the sequence of 3’s repeating infinitely– The computer allocates a fixed amount of space - finite precision, so
• double value may be only an approximation – Don’t compare floating point values for equality and
inequality,
– test the absolute value of the difference
Jozef Goetz, 2015
57Common Programming Error 5.4
Assuming that integer division rounds down (rather than truncates) can lead to incorrect results. For example, 7 / 4, which yields 1.75 in
conventional arithmetic, truncates to 1 in integer arithmetic, rather than rounding to 2.
Jozef Goetz, 2015
58 1 // Fig. 5.10: GradeBookTest.cs
2 // Create GradeBook object and invoke its DetermineClassAverage method.
3 public class GradeBookTest
4 {
5 public static void Main( string[] args )
6 {
7 // create GradeBook object myGradeBook and
8 // pass course name to constructor
9 GradeBook myGradeBook = new GradeBook(
10 "CS101 Introduction to C# Programming" );
11
12 myGradeBook.DisplayMessage(); // display welcome message
13 myGradeBook.DetermineClassAverage(); // find average of grades
14 } // end Main
15 } // end class GradeBookTest Welcome to the grade book for CS101 Introduction to C# Programming!
Enter grade or -1 to quit: 96 Enter grade or -1 to quit: 88 Enter grade or -1 to quit: 79 Enter grade or -1 to quit: -1
Total of the 3 grades entered is 263 Class average is 87.67
Outline
GradeBookTest.cs
Good Programming Practice 5.7 In a sentinel-controlled loop,
the prompts requesting data entry should explicitly remind the user of the sentinel value.
Exc. Expand method DetermineClassAverage() in the way that the user is prompted if the number of grades is known or is unknown. Provide the piece of code to process both cases.
Jozef Goetz, 2015
59
1 // Fig. 5.9: GradeBook.cs
2 // GradeBook class tlhat solves class-average problem using
3 // sentinel-controled repetition. 4 using System; 5 6 public class GradeBook 7 { 8 // autoimplemented property CourseName 9 public string CourseName { get; set; } 10 11 // constructor initializes the CourseName property 12 public GradeBook( string name ) 13 { 14 CourseName = name; // set CourseName to name 15 } // end constructor 17 27
Outline
GradeBook.cs
( 1 of 3 )
• Class GradeBook now implements the algorithm for sentinel-controlled repetition (Fig. 5.9)
Fig. 5.9 | GradeBook class that solves the class-average problemusing sentinel-controlled repetition. (Part 1 of 3.)
Jozef Goetz, 2015
6028
29 // display a welcome message to the GradeBook user
30 public void DisplayMessage()
31 {
32 Console.WriteLine( "Welcome to the grade book for\n{0}!\n",
33 CourseName );
34 } // end method DisplayMessage
35
36 // determine the average of an arbitrary number of grades
37 public void DetermineClassAverage()
38 {
39 int total; // sum of grades
40 int gradeCounter; // number of grades entered
41 int grade; // grade value
42 double average; // number with decimal point for average
43
44 // initialization phase
45 total = 0; // initialize total
46 gradeCounter = 0; // initialize loop counter
47
48 // processing phase
49 // prompt for input and read grade from user
50 Console.Write( "Enter grade or -1 to quit: " );
51 grade = Convert.ToInt32( Console.ReadLine() );
52
53 // loop until sentinel value read from user
54 while ( grade != -1 )
55 {
56 total = total + grade; // add grade to total
57 gradeCounter = gradeCounter + 1; // increment counter
Outline
GradeBook.cs
(2 of 3)Welcome to the grade book forCS101 Introduction to C# Programming!Enter grade or -1 to quit: 96Enter grade or -1 to quit: 88Enter grade or -1 to quit: 79Enter grade or -1 to quit: -1Total of the 3 grades entered is 263Class average is 87.67
Input the first grade (possibly the sentinel)While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel)
If the counter is not equal to zero Set the average to the total divided by the counter Print the averageelse Print “No grades were entered”
Jozef Goetz, 2015
6158
59 // prompt for input and read next grade from user
60 Console.Write( "Enter grade or -1 to quit: " );
61 grade = Convert.ToInt32( Console.ReadLine() );
62 } // end while
63
64 // termination phase
65 // if user entered at least one grade...
66 if ( gradeCounter != 0 )
67 {
68 // calculate average of all grades entered
69 average = ( double ) total / gradeCounter;
70
71 // display total and average (with two digits of precision)
72 Console.WriteLine( "\nTotal of the {0} grades entered is {1}",
73 gradeCounter, total );
74 Console.WriteLine( "Class average is {0:F2}", average );
75 } // end if F2 – floating point with 2 decimal decimal places
76 else // no grades were entered, so output error message
77 Console.WriteLine( "No grades were entered" );
78 } // end method DetermineClassAverage
79 } // end class GradeBook
Outline
GradeBook.cs
(3 of 3)
Welcome to the grade book forCS101 Introduction to C# Programming!Enter grade or -1 to quit: 96Enter grade or -1 to quit: 88Enter grade or -1 to quit: 79Enter grade or -1 to quit: -1Total of the 3 grades entered is 263Class average is 87.67
While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel)
If the counter is not equal to zero Set the average to the total divided by the counter Print the averageelse Print “No grades were entered”
Exc. Draw a flowchart for method DetermineClassAverage()
Jozef Goetz, 2015
62Software Engineering Observation 5.5
Some experienced programmers write applications
without ever using application-development
tools like pseudocode or flowcharts.
They feel that their ultimate goal is to solve the problem on a computer and that writing pseudocode merely delays the production of final outputs.
Although this method may work for simple and familiar problems, it can lead to serious errors and delays in large, complex projects.
Jozef Goetz, 2015
635.10 Formulating Algorithms with Top-Down, Stepwise Refinement: Case
Study 3 (Nested Control Structures)
Nesting The insertion of one control structure inside another
Multiple loops Loops with if statements
Jozef Goetz, 2015
645.10Nested Control Structures Problem statement
A college has a list of test results (1 = pass, 2 = fail) for a licensing exam for 10 students. Write a program that analyzes the results and print the number of passes and failures. If more than 8 students pass, print "Raise Tuition".
Program should analyze results as follows: Input each test result (1 or 2). Display message
"Enter result" on screen each time program requests another result.
Count number of results of each type Display summary of test results - indicate how
many students passed and how many failed If more than 8 passed, print "Raise tuition"
Jozef Goetz, 2015
655.10Nested Control Structures
Observations Program must process 10 test results
Use counter-controlled loop 3 counters can be used
One for passes, one for fails Student counter for # of students
Each test result is either a 1 (pass) or a 2 (fail) If not a 1, assume it is a 2
Must decide if more than 8 passes
Psuedocode representation of top Analyze exam results and decide if tuition should be raised Top complete representation of problem
May need several refinements
Jozef Goetz, 2015
665.10Nested Control Structures
First refinement1. Initialize variables
2. Input the ten quiz grades and count passes and failures
3. Print a summary of the exam results and decide if tuition should be raised
1. Refine "Initialize variables" to
Initialize passes to zeroInitialize failures to zeroInitialize student counter to 1
Jozef Goetz, 2015
675.10Nested Control Structures
2. Refine "Input the ten quiz grades and count passes and failures" to
While student counter is less than or equal to ten Input the next exam result
if the student passed
Add one to passeselse Add one to failures
Add one to student counter
Jozef Goetz, 2015
685.10Nested Control Structures
3. Refine "Print a summary of the exam results and decide if tuition should be raised" toPrint the number of passesPrint the number of failures
If more than eight students passed Print “Raise tuition”
Psuedocode sufficiently refined Can be converted to a C# program
Jozef Goetz, 2015
69Initialize passes to zeroInitialize failures to zeroInitialize student counter to 1
While student counter is less than or equal to ten Input the next exam result
If the student passed Add one to passes
else Add one to failures
Add one to student counter
Print the number of passesPrint the number of failures
If more than eight students passed Print “Raise tuition”
Fig 5.11 Pseudocode for examination-results problem.
Jozef Goetz, 2015
70 1 // Fig. 5.12: Analysis.cs
2 // Analysis of examination results, using nested control statements.
3 using System;
4
5 public class Analysis
6 {
7 public void ProcessExamResults()
8 {
9 // initializing variables in declarations
10 int passes = 0; // number of passes
11 int failures = 0; // number of failures
12 int studentCounter = 1; // student counter
13 int result; // one exam result from user
14
15 // process 10 students using counter-controlled repetition
16 while ( studentCounter <= 10 )
17 {
18 // prompt user for input and obtain value from user
19 Console.Write( "Enter result (1 = pass, 2 = fail): " );
20 result = Convert.ToInt32( Console.ReadLine() );
21
22 // if...else nested in while
23 if ( result == 1 ) // if result 1,
24 passes = passes + 1;
25 else // else result is not 1, so
26 failures = failures + 1; // increment failures
27
28 // increment studentCounter so loop eventually terminates
29 studentCounter = studentCounter + 1;
30 } // end while 31 32 // termination phase; prepare and display results
33 Console.WriteLine( "Passed: {0}\nFailed: {1}", passes, failures );
34
35 // determine whether more than 8 students passed
36 if ( passes > 8 )
37 Console.WriteLine( "Raise Tuition" );
38 } // end method ProcessExamResults
39 } // end class Analysis
Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 2Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Passed: 9Failed: 1Raise Tuition
Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 2Enter result (1 = pass, 2 = fail): 2Enter result (1 = pass, 2 = fail): 2Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 1Enter result (1 = pass, 2 = fail): 2Enter result (1 = pass, 2 = fail): 2Passed: 5Failed: 5
Initialize passes to zeroInitialize failures to zeroInitialize student counter to one
While student counter is less than or equal to ten Input the next exam result
If the student passed Add one to passes
else Add one to failures
Add one to student counter
Print the number of passesPrint the number of failures
If more than eight students passed Print “Raise tuition”
Jozef Goetz, 2015
71 1 // Fig. 5.13: AnalysisTest.cs
2 // Test application for class Analysis.
3 public class AnalysisTest
4 {
5 public static void Main( string[] args )
6 {
7 Analysis application = new Analysis(); // create Analysis object
8 application.ProcessExamResults(); // call method to process results
9 } // end Main
10 } // end class AnalysisTest Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Passed: 9 Failed: 1 Raise Tuition Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 2 Passed: 5 Failed: 5
Outline
AnalysisTest.cs
Jozef Goetz, 2015
725.11 Compound Assignment Operators
Compound assignment operators Can reduce code
x += 2 is the same as x = x + 2 Can be done with all the math operators
+=, -=, *=, /=, and %=
Statements of the formvariable = variable operator expression;
can be rewritten asvariable operator= expression;
Other examples d -= 4 (d = d - 4)
e *= 5 (e = e * 5)f /= 3 (f = f / 3)g %= 9 (g = g % 9)
Compiler runs a bit faster
Jozef Goetz, 2015
735.11 Assignment Operators
Assignment operator Sample expression Explanation Assigns Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;
+= c += 7 c = c + 7 10 to c
-= d -= 4 d = d - 4 1 to d
*= e *= 5 e = e * 5 20 to e
/= f /= 3 f = f / 3 2 to f
%= g %= 9 g = g % 9 3 to g
Fig. 5.13 Arithmetic assignment operators.
Jozef Goetz, 2015
745.12 Increment and Decrement Operators Unary (unry) increment operator (++)
Increment variable’s value by 1 Increment operator (++) i.e. i++
Can be used instead of c += 1
Unary decrement operator (--) Decrement variable’s value by 1 Decrement operator (--) i.e. i--
Can be used instead of c -= 1
Pre-increment vs. post-incrementc++ or c--
Will perform an action in which c resides and then add to or subtract one from the value
++c or --c Will add to or subtract one from the value and then perform an action in which c
resides
++(c + 1) – a syntax error, b. c + 1 is not a variable reference
Jozef Goetz, 2015
755.12 Increment and Decrement Operators
Operator Called Sample expression Explanation
++ preincrement ++a Increment a by 1, then use the new value of a in the expression in which a resides.
++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1.
-- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides.
-- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1.
Fig. 5.14 The increment and decrement operators.
Good Programming Practice 5.7 Unlike binary operators, the unary increment and decrement operators should (by convention) be placed next to their operands, with no intervening spaces.
2002 Prentice Hall.All rights reserved.
Outline76
Increment.cs
Program Output
1 // Fig. 5.15: Increment.cs2 // Preincrementing and postincrementing3 4 using System;5 6 class Increment7 {8 static void Main(string[] args)9 { 10 int c;11 12 c = 5;13 Console.WriteLine( c ); // print 514 Console.WriteLine( c++ ); // print 5 then postincrement
// (then action in which c resides)15 Console.WriteLine( c ); // print 616 17 Console.WriteLine(); // skip a line18 19 c = 5;20 Console.WriteLine( c ); // print 521 Console.WriteLine( ++c ); // preincrement(first action in which c resides then print 622 Console.WriteLine( c ); // print 623 24 } // end of method Main25 26 } // end of class Increment
556 566
Declare variable cSet c equal to 5
Jozef Goetz, 2015
77Fig. 5.17 | Precedence and associativity of the operators discussed so far - see appendix A
p.951.
Operators Associativity Type
. new ++(postfix) --(postfix) left to right Highest precedence
++ -- + - (type) right to left unary prefix * / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
?: right to left conditional
= += -= *= /= %= right to left assignment
Jozef Goetz, 2015
78
• The table in Appendix B p. 953 , Simple Types, lists the 13 simple types in C#.
• C# requires all variables to have a type.
• Instance variables of types char, byte, sbyte, short, ushort, int, uint, long, ulong, float (4
bytes), double (8 bytes), and decimal (16 bytes), are all given the value 0 by default.
• Instance variables of type bool are given the value false by default.
• Reference type instance variables are initialized by default to the value null
5.13 Simple Types
Jozef Goetz, 2015
Jozef Goetz, 2015
80Flowchart of the calculation of sum = 1 + x/ 1! + /2! + /3! + … + …+ x^n/n!
Values n (= number of terms without the first one)and x should be prompted to enter.
x 2 x 3
Convert the previous flowchart => to a new one
Modify the above flowchart for x = 1