2002 prentice hall. all rights reserved. 1 lecture 1 consolidation of first year work (part 1) read...
TRANSCRIPT
2002 Prentice Hall. All rights reserved.
1
Lecture 1
• Consolidation of first year work (part 1)• Read all the chapters on your own• Slides highlight important concepts only• Do not learn from slides only• Summary of chapters 1 through to 5 • Homework at end of slides
2002 Prentice Hall. All rights reserved.
2
Chapter 1 – Introduction to Computers, the Internet, the Web and C#
Outline1.1 Introduction1.2 What Is a Computer?1.3 Computer Organization1.4 Evolution of Operating Systems1.5 Personal Computing, Distributed Computing and
Client/Server Computing1.6 Machine Languages, Assembly Languages and
High-level Languages1.7 C, C++, Visual Basic .NET and Java1.8 C# 1.9 Other High-level Languages1.10 Structured Programming1.11 Key Software Trend: Object Technology1.12 Hardware Trends1.13 History of the Internet and World Wide Web1.14 World Wide Web Consortium (W3C)1.15 Extensible Markup Language (XML)
2002 Prentice Hall. All rights reserved.
3
Chapter 1 – Introduction to Computers, the Internet, the Web and C#
Outline1.16 Introduction to Microsoft .NET1.17 .NET Framework and the Common Language Runtime
2002 Prentice Hall. All rights reserved.
4
1.7 C, C++, Visual Basic .NET and Java (III)
• Object-Oriented Programming– Uses objects
• Reusable software components
• Modeled after items in the real world
– More productive than structured programming
– Easier to understand, correct and modify
2002 Prentice Hall. All rights reserved.
5
1.8 C#
• C#– Developed at Microsoft by a team led by Anders Hejlsberg
and Scott Wiltamuth
– Event driven, object oriented, visual programming language
– Based from C, C++ and Java
– Incorporated into .NET platform• Web based applications can be distributed
– Devices and desktop computers
• Programs that can be accessed by anyone through any device
• Allows communicating with different computer languages
– Integrated Design Environment (IDE)• Makes programming and debugging fast and easy
• Rapid Application Development (RAD)
2002 Prentice Hall. All rights reserved.
6
1.11 Key Software Trend: Object Technology
• What is Object Technology?– Packaging scheme for creating software units
• Units are objects
– Any noun can be represented as an object
• Date object, time object, car object
– Have properties
• Size, color, weight
– Perform actions
• Moving, sleeping, drawing
– Defined in classes
• Specify general format
• Provide specific attributes and behaviors
2002 Prentice Hall. All rights reserved.
7
1.11 Key Software Trend: Object Technology (II)
• Object-Oriented programming– Based on nouns
• Reflects way world is perceived
– Advantages over structured programming• More natural process
– Results in better productivity
• Classes provide reusability
– Microsoft Foundation Classes (MFC)
• Easier to maintain
– Programs more understandable
– Focus on behaviors and interactions
– Less attention to details
2002 Prentice Hall. All rights reserved.
8
1.16 Introduction to Microsoft .NET
• .NET initiative– Introduced by Microsoft (June 2000)
• Vision for embracing the Internet in software development
– Independence from specific language or platform• Applications developed in any .NET compatible language
– Visual Basic .NET, Visual C++ .NET, C# and more
• Programmers can contribute to applications using the language in which they are most competent
– Architecture capable of existing on multiple platforms
– New program development process• Provides increased productivity
2002 Prentice Hall. All rights reserved.
9
1.16 Introduction to Microsoft .NET (II)
• Key components of .NET– Web services
• Applications used over the Internet
– Software reusability• Web services provide solutions for wide variety of companies
– Cheaper than developing one-time solutions that can’t be reused
– Single applications perform all operations for a company via various Web services
• Manage taxes, bills, investments and more
• Pre-packaged components
– Make application development quicker and easier
– Developers no longer need to be concerned with details of components
2002 Prentice Hall. All rights reserved.
10
1.16 Introduction to Microsoft .NET (III)
• Keys to interaction– XML and SOAP
• “Glue” that combines various Web services to form applications
– XML gives meaning to data
– SOAP allows communication to occur easily
2002 Prentice Hall. All rights reserved.
11
1.16 Introduction to Microsoft .NET (IV)
• Other concepts– Universal data access
• Eliminates need to synchronize files
– Updating multiple copies of same file to the most recent
• Data resides at one central location
– Accessible by anyone with connection and proper authorization
• Data formatted appropriately for display on various devices
– Same document seen on PC, PDA, cell phone and other devices
– Additional information available at Microsoft Web site www.microsoft.com/net
2002 Prentice Hall. All rights reserved.
12
1.17 .NET Framework and the Common Language Runtime
• .NET Framework– Heart of .NET strategy
• Manages and executes applications and Web services
• Provides security, memory management and other programming capabilities
– Includes Framework class library (FCL)• Pre-packaged classes ready for reuse
• Used by any .NET language
– Details contained in Common Language Specification (CLS)• Submitted to European Computer Manufacturers Association
to make the framework easily converted to other platforms
– Executes programs by Common Language Runtime (CLR)
2002 Prentice Hall. All rights reserved.
13
1.17 .NET Framework and the Common Language Runtime (II)
• Common Language Runtime (CLR)– Central part of framework
• Executes Visual Basic .NET programs
– Compilation process• Two compilations take place
– Programs compiled to Microsoft Intermediate Language (MSIL)
• Defines instructions for CLR
– MSIL code translated into machine code
• Machine code for a particular platform
2002 Prentice Hall. All rights reserved.
14
1.17 .NET Framework and the Common Language Runtime (III)
• Why two compilations?– Platform independence
• .NET Framework can be installed on different platforms
• Execute .NET programs without any modifications to code
– Language independence• .NET programs not tied to particular language
• Programs may consist of several .NET-compliant languages
• Old and new components can be integrated
• Other advantages of CLR– Execution-management features
• Manages memory, security and other features
– Relieves programmer of many responsibilities
– More concentration on program logic
2002 Prentice Hall. All rights reserved.
15
Chapter 2 – Introduction to the Visual Studio .NET IDE
Outline2.1 Introduction2.2 Visual Studio .NET Integrated Development
Environment (IDE) Overview2.3 Menu Bar and Toolbar2.4 Visual Studio .NET Windows
2.4.1 Solution Explorer2.4.2 Toolbox2.4.3 Properties Window
2.5 Using Help2.6 Simple Program: Displaying Text and an Image
2002 Prentice Hall. All rights reserved.
16
2.1 Introduction
• Visual Studio .NET– Microsoft’s Integrated Development Environment (IDE)
– Program in a variety of .NET languages
– Tools to edit and manipulate several file types
2002 Prentice Hall. All rights reserved.
172.2 Visual Studio .NET Integrated Development Environment (IDE)
Overview
Fig. 2.1 Start Page in Visual Studio .NET.
navigation buttons
location bar
recent projects
buttons
hidden window
Start Page links
2002 Prentice Hall. All rights reserved.
18
2.2 Visual Studio .NET Integrated Development Environment (IDE)
– The My Profile screen• Allows Visual Studio .NET customization
– Keyboard preferences
– Window layout preferences
• New project dialogue (Fig. 2.2)– C# .NET project
• Group of related files, images, and documentations
– C# .NET solution• Group of projects creating one or a group of applications
– Windows Applications• Anything that runs in the Windows OS
– Microsoft Word
– Microsoft Internet Explorer
2002 Prentice Hall. All rights reserved.
19
Chapter 3 – Introduction to C# Programming
Outline3.1 Introduction3.2 Simple Program: Printing a Line of Text3.3 Another Simple Program: Adding Integers3.4 Memory Concepts3.5 Arithmetic3.6 Decision Making: Equality and Relational Operators
2002 Prentice Hall. All rights reserved.
20
3.1 Introduction
• Console applications– No visual components
– Only text output
– Two types• MS-DOS prompt
– Used in Windows 95/98/ME
• Command prompt
– Used in windows 2000/NT/XP
– Windows applications• Forms with several output types
• Contain Graphical User Interfaces (GUIs)
2002 Prentice Hall. All rights reserved.
21
3.2 Simple Program: Printing a line of text
• Comments– Comments can be created using //…
– Multi-lines comments use /* … */
– Comments are ignored by the compiler
– Used only for human readers
• Namespaces– Groups related C# features into a categories
– Allows the easy reuse of code
– Many namespaces are found in the .NET framework library
– Must be referenced in order to be used
• White Space– Includes spaces, newline characters and tabs
2002 Prentice Hall. All rights reserved.
22
3.2 Simple Program: Printing a line of text
• Keywords– Words that cannot be used as variable or class names or any other
capacity– Have a specific unchangeable function within the language– Example: class – All keywords are lowercase
• Classes– Class names can only be one word long (i.e. no white space in
class name )– Class names are capitalized, with each additional English word
capitalized as well (e.g., MyFirstProgram )– Each class name is an identifier
• Can contain letters, digits, and underscores (_)• Cannot start with digits• Can start with the at symbol (@)
2002 Prentice Hall. All rights reserved.
23
3.2 Simple Program: Printing a line of text
– Class bodies start with a left brace ({)
– Class bodies end with a right brace (})
• Methods– Building blocks of programs
– The Main method• Each console or windows application must have exactly one
• All programs start by executing the Main method
– Braces are used to start ({) and end (}) a method
• Statements– Anything in quotes (“) is considered a string
– Every statement must end in a semicolon (;)
2002 Prentice Hall. All rights reserved.
24
3.2 Simple Program: Printing a line of text
• Graphical User Interface– GUIs are used to make it easier to get data from the user as
well as display data to the user
– Message boxes• Within the System.Windows.Forms namespace
• Used to prompt or display information to the user
2002 Prentice Hall. All rights reserved.
25
3.2 Simple Program: Printing a Line of Text
Fig. 3.8 Adding a reference to an assembly in Visual Studio .NET (part 1).
Add Reference dialogue
2002 Prentice Hall. All rights reserved.
26
3.2 Simple Program: Printing a Line of Text
References folder
Solution Explorer
System.Windows.Forms reference
Fig. 3.8 Adding a reference to an assembly in Visual Studio .NET (part 2).
2002 Prentice Hall. All rights reserved.
27
3.3 Another Simple Program: Adding Integers
• Primitive data types– Data types that are built into C#
• String, Int, Double, Char, Long
• 15 primitive data types (chapter 4)
– Each data type name is a C# keyword
– Same type variables can be declared on separate lines or on one line
• Console.ReadLine()– Used to get a value from the user input
• Int32.Parse()– Used to convert a string argument to an integer
– Allows math to be preformed once the string is converted
2002 Prentice Hall.All rights reserved.
Outline28
Addition.cs
1 // Fig. 3.11: Addition.cs2 // An addition program.3 4 using System;5 6 class Addition7 {8 static void Main( string[] args )9 {10 string firstNumber, // first string entered by user11 secondNumber; // second string entered by user12 13 int number1, // first number to add14 number2, // second number to add15 sum; // sum of number1 and number216 17 // prompt for and read first number from user as string18 Console.Write( "Please enter the first integer: " );19 firstNumber = Console.ReadLine();20 21 // read second number from user as string22 Console.Write( "\nPlease enter the second integer: " );23 secondNumber = Console.ReadLine();24 25 // convert numbers from type string to type int26 number1 = Int32.Parse( firstNumber );27 number2 = Int32.Parse( secondNumber );28 29 // add numbers30 sum = number1 + number2;31
This is the start of class Addition
Two string variables defined over two lines
The comment after the declaration is used to briefly state the variable purpose
These are three ints that are declared over several lines and only use one semicolon. Each is separated by a coma.
Console.ReadLine is used to take the users input and place it into a variable.
This line is considered a prompt because it asks the user to input data.
Int32.Parse is used to convert the given string into an integer. It is then stored in a variable.
The two numbers are added and stored in the variable sum.
2002 Prentice Hall.All rights reserved.
Outline29
Addition.cs
Program Output
32 // display results33 Console.WriteLine( "\nThe sum is {0}.", sum );34 35 } // end method Main36 37 } // end class Addition
Please enter the first integer: 45 Please enter the second integer: 72 The sum is 117.
Putting a variable out through Console.WriteLine is done by placing the variable after the text while using a marked place to show where the variable should be placed.
2002 Prentice Hall. All rights reserved.
30
3.4 Memory Concepts
• Memory locations– Each variable is a memory location
• Contains name, type, size and value
– When a new value is enter the old value is lost
– Used variables maintain their data after use
2002 Prentice Hall. All rights reserved.
31
3.4 Memory Concepts
Fig. 3.12 Memory location showing name and value of variable number1.
number1 45
2002 Prentice Hall. All rights reserved.
32
3.5 Arithmetic
• Arithmetic operations– Not all operations use the same symbol
• Asterisk (*) is multiplication
• Slash (/) is division
• Percent sign (%) is the modulus operator
• Plus (+) and minus (-) are the same
– Must be written in a straight line
– There are no exponents
• Division– Division can vary depending on the variables used
• When dividing two integers the result is always rounded down to an integer
• To be more exact use a variable that supports decimals
2002 Prentice Hall. All rights reserved.
33
3.5 Arithmetic
• Order– Parenthesis are done first
– Division, multiplication and modulus are done second• Left to right
– Addition and subtraction are done last• Left to right
2002 Prentice Hall. All rights reserved.
34
3.4 Memory Concepts
Fig. 3.13 Memory locations after values for variables number1 and number2 have been input.
number1 45
number2 72
2002 Prentice Hall. All rights reserved.
35
3.4 Memory Concepts
Fig. 3.14 Memory locations after a calculation.
number1 45
number2 72
sum 117
2002 Prentice Hall. All rights reserved.
36
3.5 Arithmetic
C# operation Arithmetic operator Algebraic expression C# expression
Addition + f + 7 f + 7
Subtraction – p – c p - c
Multiplication * bm b * m
Division / x / y or x / y
Modulus % r mod s r % s
Fig. 3.15 Arithmetic operators.
xy
2002 Prentice Hall. All rights reserved.
37
3.5 Arithmetic
Operator(s) Operation Order of evaluation (precedence) ( ) Parentheses Evaluated first. If the parentheses are nested,
the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
*, / or % Multiplication Division Modulus
Evaluated second. If there are several such operators, they are evaluated left to right.
+ or - Addition Subtraction
Evaluated last. If there are several such operators, they are evaluated left to right.
Fig. 3.16 Precedence of arithmetic operators.
2002 Prentice Hall. All rights reserved.
38
3.6 Decision Making: Equality and Relational Operators
• The if structure– Used to make a decision based on the truth of the condition
• True: a statement is performed
• False: the statement is skipped over
– The start of an if statement should not end in a semicolon (;)
– Fig. 3.18 lists the equality and rational operators• There should be no spaces separating the operators
2002 Prentice Hall. All rights reserved.
39
3.6 Decision Making: Equality and Relational Operators
Standard algebraic equality operator or relational operator
C# equality or relational operator
Example of C# condition
Meaning of C# condition
Equality operators == x == y x is equal to y != x != y x is not equal to y Relational operators > > x > y x is greater than y < < x < y x is less than y >= x >= y x is greater than or equal to
y <= x <= y x is less than or equal to y Fig. 3.18 Equality and relational operators.
2002 Prentice Hall. All rights reserved.
40
3.6 Decision Making: Equality and Relational Operators
Operators Associativity Type () left to right parentheses * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality = right to left assignment Fig. 3.20 Precedence and associativity of operators discussed in this
chapter.
2002 Prentice Hall. All rights reserved.
41
Chapter 4 – Control Structures Part 1
Outline4.1 Introduction4.2 Algorithms4.3 Pseudocode4.4 Control Structures4.5 if Selection Structure4.6 if/else Selection Structure4.7 while Repetition Structure4.8 Formulating Algorithms: Case Study 1
(Counter-Controlled Repetition)4.9 Formulating Algorithms with Top-Down, Stepwise Refinement:
Case Study 2 (Sentinel-Controlled Repetition)4.10 Formulating Algorithms with Top-Down, Stepwise Refinement:
Case Study 3 (Nested Control Structures)4.11 Assignment Operators4.12 Increment and Decrement Operators4.13 Introduction to Windows Application Programming
2002 Prentice Hall. All rights reserved.
42
4.1 Introduction
• Before writing a program– Understand the problem
– Think of an approach
– Understand building blocks
– Use proven principals of structured programming
2002 Prentice Hall. All rights reserved.
43
4.2 Algorithms
• Procedure– The actions a program will perform
– The order these actions will be performed
– Also called an algorithm
• Program control– The task of ordering a computers procedure correctly
2002 Prentice Hall. All rights reserved.
44
4.3 Pseudocode
• Pseudocode– Artificial and informal language
– Helps programmers to plan an algorithm
– Similar to everyday English
– Not an actual programming language
– Converting simply replaces words with C# code
– Can use either Pseudocode OR flowcharts
2002 Prentice Hall. All rights reserved.
45
4.4 Control Structures
• Program of control– Program performs one statement then goes to next line
• Sequential execution
– Different statement other than the next one executes• Selection structure
– The if and if/else statements
– The goto statement
• No longer used unless absolutely needed
• Causes many readability problems
• Repetition structure
– The while and do/while loops (chapter 5)
– The for and foreach loops (chapter 5)
2002 Prentice Hall. All rights reserved.
46
4.4 Control Structures
• Flow charts– Used to map program
– Illustrates the order events will go in• Rectangle used to show action
• Oval used to show beginning
• Circles used as connectors
• Diamonds used as decisions
– Combination of control structures• Stacking
– Placing one after another
• Nesting
– Inserting of one structure into another
2002 Prentice Hall. All rights reserved.
47
4.4 Control Structures
add grade to total
add 1 to counter
total = total + grade;
counter = counter + 1;
Fig. 4.1 Flowcharting C#’s sequence structure.
2002 Prentice Hall. All rights reserved.
48
4.4 Control Structures
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. 4.2 C# keywords.
2002 Prentice Hall. All rights reserved.
49
4.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
2002 Prentice Hall. All rights reserved.
50
4.5 if Selection Structure
Fig. 4.3 Flowcharting a single-selection if structure.
print “Passed”Grade >= 60true
false
2002 Prentice Hall. All rights reserved.
51
4.6 if/else selection structure
• The if/else structure– Alternate courses can be taken when the statement is false
– Rather than one action there are two choices
– Nested structures can test many cases
– Structures with many lines of code need braces ({)• Can cause errors
– Fatal logic error
– Nonfatal logic error
2002 Prentice Hall. All rights reserved.
52
4.6 if/else Selection Structure
Fig. 4.4 Flowcharting a double-selection if/else structure.
Grade >= 60
print “Passed”print “Failed”
false true
2002 Prentice Hall. All rights reserved.
53
4.7 while Repetition Structure
• Repetition Structure– An action is to be repeated
• Continues while statement is true
• Ends when statement is false
– Contain either a line or a body of code• Must alter conditional
– Endless loop
2002 Prentice Hall. All rights reserved.
54
4.7 while Repetition Structure
Fig. 4.5 Flowcharting the while repetition structure.
true
false
Product = 2 * productProduct <= 1000
2002 Prentice Hall. All rights reserved.
55
4.11 Assignment Operators
• Assignment operators– Can reduce code
• x += 2 is the same as x = x + 2
– Can be done with all the math operators• ++, -=, *=, /=, and %=
2002 Prentice Hall. All rights reserved.
56
4.11 Assignment Operators
2002 Prentice Hall. All rights reserved.
57
4.12 Increment and Decrement Operators
• Increment operator– Used to add one to the variable– x++– Same as x = x + 1
• Decrement operator– Used to subtract 1 from the variable– y--
• Pre-increment vs. post-increment– x++ or x--
• Will perform an action and then add to or subtract one from the value
– ++x or --x• Will add to or subtract one from the value and then perform an
action
2002 Prentice Hall. All rights reserved.
58
4.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. 4.13 The increment and decrement operators.
2002 Prentice Hall. All rights reserved.
59
4.12 Increment and Decrement Operators
Operators Associativity Type
() ++ --
left to right right to left
parentheses unary postfix
++ -- + - (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
Fig. 4.15 Precedence and associativity of the operators discussed so far in this book.
2002 Prentice Hall. All rights reserved.
60
4.13 Introduction to Windows Application Programming
• Inheritance– Base class
• a class from which another class inherits from
– Derived class• The class from which another class inherits
– Classes inherit basics of a class• Attributes (data)
• Behaviors (methods)
– Prevents the continual rewriting of code
2002 Prentice Hall. All rights reserved.
61
Chapter 5 – Control Structures: Part 2Outline5.1 Introduction5.2 Essentials of Counter-Controlled Repetition5.3 for Repetition Structure5.4 Examples Using the for Structure5.5 switch Multiple-Selection Structure5.6 do/while Repetition Structure5.7 Statements break and continue5.8 Logical and Conditional Operators5.9 Structured-Programming Summary
2002 Prentice Hall. All rights reserved.
62
5.2 Essentials of Counter Controlled Repetition
• 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
2002 Prentice Hall.All rights reserved.
Outline63
WhileCounter.cs
Program Output
1 // Fig. 5.1: WhileCounter.cs2 // Counter-controlled repetition.3 4 using System;5 6 class WhileCounter7 {8 static void Main( string[] args )9 {10 int counter = 1; // initialization11 12 while ( counter <= 5 ) // repetition condition13 {14 Console.WriteLine( counter );15 counter++; // increment16 17 } // end while18 19 } // end method Main20 21 } // end class WhileCounter
12345
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
2002 Prentice Hall. All rights reserved.
64
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
2002 Prentice Hall. All rights reserved.
65
5.3 for Repetition Structure
for ( int counter = 1; counter <= 5; counter++ )
Initial value of control variable Increment of control variable
Control variable name Final value of control variablefor keyword
Loop-continuation condition
Fig. 5.3 Components of a typical for header.
2002 Prentice Hall. All rights reserved.
66
5.3 for Repetition Structure
counter++
Establish initial value of control variable.
Determine if final value of control variable has been reached.
counter <= 10
Console.WriteLine( counter * 10 );
true
false
int counter = 1
Body of loop (this may be multiple statements)
Increment the control variable.
Fig. 5.4 Flowcharting a typical for repetition structure.
2002 Prentice Hall.All rights reserved.
Outline67
ForCounter.cs
Program Output
1 // Fig. 5.2: ForCounter.cs2 // Counter-controlled repetition with the for structure.3 4 using System;5 6 class ForCounter7 {8 static void Main( string[] args )9 {10 // initialization, repetition condition and incrementing11 // are all included in the for structure12 for ( int counter = 1; counter <= 5; counter++ )13 Console.WriteLine( counter );14 }15 }
12345
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 (1 is added to it)
2002 Prentice Hall. All rights reserved.
68
5.4 Examples Using the for Structure
Format Code Description C or c Formats the string as currency. Precedes the number with an appropriate currency
symbol ($ in the US). Separates digits with an appropriate separator character (comma in the US) and sets the number of decimal places to two by default.
D or d Formats the string as a decimal. Displays number as an integer.
N or n Formats the string with commas and two decimal places.
E or e Formats the number using scientific notation with a default of six decimal places.
F or f Formats the string with a fixed number of decimal places (two by default).
G or g General. Either E or F.
X or x Formats the string as hexadecimal.
Fig. 5.9 string formatting codes.
2002 Prentice Hall. All rights reserved.
69
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
2002 Prentice Hall.All rights reserved.
Outline70
SwitchTest.cs
1 // Fig. 5.10: SwitchTest.cs2 // Counting letter grades.3 4 using System;5 6 class SwitchTest7 {8 static void Main( string[] args )9 {10 char grade; // one grade11 int aCount = 0, // number of As12 bCount = 0, // number of Bs13 cCount = 0, // number of Cs14 dCount = 0, // number of Ds15 fCount = 0; // number of Fs16 17 for ( int i = 1; i <= 10; i++ )18 {19 Console.Write( "Enter a letter grade: " );20 grade = Char.Parse( Console.ReadLine() );21 22 switch ( grade )23 {24 case 'A': // grade is uppercase A25 case 'a': // or lowercase a26 ++aCount;27 break;28 29 case 'B': // grade is uppercase B30 case 'b': // or lowercase b31 ++bCount;32 break;33
Each of these variables acts as a counter so they are initialized to zero
The start of the switch statement. The grade variable is used as the data to be tested for each case.
Prompt the user for a grade and store it into the grade variable
case ‘A’ is empty so it is the same as case ‘a’
Both cases add one to aCount
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
A for loop that initializes i to 1, loops 10 times and increments i by one each time
2002 Prentice Hall.All rights reserved.
Outline71
SwitchTest.cs
34 case 'C': // grade is uppercase C35 case 'c': // or lowercase c36 ++cCount;37 break;38 39 case 'D': // grade is uppercase D40 case 'd': // or lowercase d41 ++dCount;42 break;43 44 case 'F': // grade is uppercase F45 case 'f': // or lowercase f46 ++fCount;47 break;48 49 default: // processes all other characters50 Console.WriteLine( 51 "Incorrect letter grade entered." +52 "\nGrade not added to totals." );53 break;54 55 } // end switch56 57 } // end for58 59 Console.WriteLine( 60 "\nTotals for each letter grade are:\nA: {0}" +61 "\nB: {1}\nC: {2}\nD: {3}\nF: {4}", aCount, bCount,62 cCount, dCount, fCount );63 64 } // end method Main65 66 } // end class SwitchTest
Both cases add 1 to cCount
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
2002 Prentice Hall.All rights reserved.
Outline72
SwitchTest.csProgram Output
Enter a letter grade: aEnter a letter grade: AEnter a letter grade: cEnter a letter grade: FEnter a letter grade: zIncorrect letter grade entered.Grade not added to totals.Enter a letter grade: DEnter a letter grade: dEnter a letter grade: BEnter a letter grade: aEnter a letter grade: C Totals for each letter grade are:A: 3B: 1C: 2D: 2F: 1
2002 Prentice Hall. All rights reserved.
73
5.5 switch Multiple-Selection Structure
break;
case: a case a action(s)true
false
.
.
.
break;
case b action(s) break;
false
false
case: z case z action(s) break;
default action(s)
true
true
case: b
Fig. 5.11 Flowcharting the switch multiple-selection structure.
2002 Prentice Hall. All rights reserved.
74
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
2002 Prentice Hall.All rights reserved.
Outline75
DoWhileLoop.cs
Program Output
1 // Fig. 5.12: DoWhileLoop.cs2 // The do/while repetition structure.3 4 using System;5 6 class DoWhileLoop7 {8 static void Main( string[] args )9 {10 int counter = 1;11 12 do 13 {14 Console.WriteLine( counter );15 counter++;16 } while ( counter <= 5 );17 18 } // end method Main19 20 } // end class DoWhileLoop
12345
The counter is initialized to one
These actions are performed at least one
Continue looping as long as counter is less than 6The incrementing task
2002 Prentice Hall. All rights reserved.
76
5.6 do/while Repetition Structure
true
false
action(s)
condition
Fig. 5.13 Flowcharting the do/while repetition structure.
2002 Prentice Hall. All rights reserved.
77
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
2002 Prentice Hall.All rights reserved.
Outline78
BreakTest.cs
1 // Fig. 5.14: BreakTest.cs2 // Using the break statement in a for structure.3 4 using System;5 using System.Windows.Forms;6 7 class BreakTest8 {9 static void Main( string[] args ) 10 {11 string output = "";12 int count;13 14 for ( count = 1; count <= 10; count++ )15 {16 if ( count == 5 )17 break; // skip remaining code in loop 18 // if count == 519 20 output += count + " ";21 22 } // end for loop23 24 output += "\nBroke out of loop at count = " + count;25 26 MessageBox.Show( output, "Demonstrating the break statement",27 MessageBoxButtons.OK, MessageBoxIcon.Information );28 29 } // end method Main30 31 } // end class BreakTest
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
A loop that starts at one, goes to ten, and increments by one
If count = 5 then break out of the loop
Display the last value that the counter was at before it broke
2002 Prentice Hall.All rights reserved.
Outline79
BreakTest.csProgram Output
2002 Prentice Hall.All rights reserved.
Outline80
ContinueTest.cs
1 // Fig. 5.15: ContinueTest.cs2 // Using the continue statement in a for structure.3 4 using System;5 using System.Windows.Forms;6 7 class ContinueTest8 {9 static void Main( string[] args ) 10 {11 string output = "";12 13 for ( int count = 1; count <= 10; count++ )14 {15 if ( count == 5 )16 continue; // skip remaining code in loop17 // only if count == 518 19 output += count + " ";20 }21 22 output += "\nUsed continue to skip printing 5";23 24 MessageBox.Show( output, "Using the continue statement",25 MessageBoxButtons.OK, MessageBoxIcon.Information );26 27 } // end method Main28 29 } // end class ContinueTest
A loop that starts at 1, goes to 10, and increments by 1If 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.
2002 Prentice Hall.All rights reserved.
Outline81
ContinueTest.csProgram Output
2002 Prentice Hall. All rights reserved.
82
5.8 Logical and Conditional Operators
• Operators– Logical AND (&)
– 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
2002 Prentice Hall. All rights reserved.
83
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
2002 Prentice Hall. All rights reserved.
84
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)
2002 Prentice Hall. All rights reserved.
85
5.9 Structured Programming Summary
Operators Associativity Type
() ++ --
left to right right to left
parentheses unary postfix
++ -- + - ! (type) right to left unary prefix
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
& left to right logical AND
^ left to right logical exclusive OR
| left to right logical inclusive OR
&& left to right conditional AND
|| left to right conditional OR
?: right to left conditional
= += -= *= /= %= right to left assignment
Fig. 5.21 Precedence and associativity of the operators discussed so far.
2002 Prentice Hall. All rights reserved.
86
5.9 Structured Programming Summary
Fig. 5.22 C#’s single-entry/single-exit sequence, selection and repetition structures. (part 1)
Sequence
.
.
2002 Prentice Hall. All rights reserved.
87
5.9 Structured Programming Summary
Fig. 5.22 C#’s single-entry/single-exit sequence, selection and repetition structures. (part 2)
Selection
T
F
if structure (single selection)
else/if structure (double selection)
TF
switch structure (multiple selections)
.
.
break
break
break
break
T
T
T
F
F
F
.
2002 Prentice Hall. All rights reserved.
88
5.9 Structured Programming Summary
Fig. 5.22 C#’s single-entry/single-exit sequence, selection and repetition structures. (part 3)
Repetition
T
F
while structure
T
F
do/while structureF
T
for structure/foreach structure
2002 Prentice Hall. All rights reserved.
89
5.9 Structured Programming Summary
Fig. 5.27 Stacked, nested and overlapped building blocks.
Stacked building blocks
Overlapping building blocks (illegal in structured programs)
Nested building blocks
2002 Prentice Hall. All rights reserved.
90
5.9 Structured Programming Summary
Fig. 5.28 Unstructured flowchart.
2002 Prentice Hall. All rights reserved.
91
Homework
• Read Chapters 1 to 5– You may be tested on this work at ANY time!
• Practical (to be done ASAP)– Exercise 4.10 (page 137)
• Change gallons to litres• Change miles to kilometres
– Exercise 4.12 (page 137)– Exercise 4.13 (page 137/138)– Exercise 4.14 (page 138)– Exercise 5.4 (page 176)– Exercise 5.5 (page 176)– Exercise 5.9 (page 177)– Exercise 5.10 (page 177)