Upload
kran-kumar
View
226
Download
0
Embed Size (px)
Citation preview
8/13/2019 Programming Fundamental All Chapter
1/265
DDPC 1573-PROGRAMMINGFUNDAMENTAL
Main ReferenceHanly and Koffman, Problem Solving and
Program Design in C, Fifth Edition, AddisonWesley
ReferenceJoyce Farrell Thomson, Programming Logic
and Design, Fifth Edition
REV00
1
8/13/2019 Programming Fundamental All Chapter
2/265
Chapter 1: Overview of Computers andProgramming
ObjectivesUnderstand computer components and operationsLearn about the steps involved in the programming process
Learn about the data hierarchy and file inputUse flowchart symbols and pseudocode statementsUse and name variablesUse a sentinel, or dummy value, to end a programManage large flowcharts
Assign values to variablesRecognize the proper format of assignment statementsDescribe data typesUnderstand the evolution of programming techniques
REV00
2DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
3/265
Chapter 1: Computer Components and Operations
2 major components of computer system:HardwareSoftware
Hardware : equipment, or devicesSoftware : programs that contain instructions for thecomputer4 major operations in a computer:
InputProcessingOutputStorage
REV00
3DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
4/265
Chapter 1: Computer Components and Operations
Input devices : allow data to enter the computerMouse, keyboard, scanner
Processing : working on the dataOrganizing dataChecking data for accuracyMathematical or other manipulations on data
Central Processing Unit (CPU) : hardware that performsthe tasks
REV00
4DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
5/265
Chapter 1: Computer Components and Operations
Output devices : provide data to the userPrinter, monitor, speakers
Programming language : special language containinginstructions for the computer
Visual Basic, Java, C#, C++, COBOLSyntax : rules governing word usage and punctuation inthe language
REV00
5DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
6/265
Chapter 1: Computer Components and Operations
Machine language : controls the computer s on/offcircuitryCompiler or interpreter : software that translatesprogramming languages to machine languageProgram must be free of syntax errors to be run, orexecuted , on a computerTo function properly, the logic must be correct
REV00
6DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
7/265
Chapter 1: Computer Components and Operations
What is wrong with this logic for making a cake?StirAdd two eggsBake at 350 degrees for 45 minutesAdd three cups of flour
REV00
7DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
8/265
Chapter 1: Computer Components and Operations
Logic errors , or semantic errors , are more difficult tolocate than syntax errorsLogic for multiplying a number by 2 (includes input,processing, and output statements)
Get input number.Compute calculated answer as
inputNumber times 2.Print calculatedAnswer.
REV00
8DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
9/265
Chapter 1: Computer Components and Operations
2 storage categories:- internal
- external
REV00
9DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
10/265
Chapter 1: Computer Components and Operations
- Internal storage :Main memory, random access memory (RAM)Located inside the computer systemVolatile : contents are lost when power goes down
External storage :Persistent : contents are relatively permanent
Floppy drive, hard drive, flash media, magnetic tapeLocated outside the computer systemNon-volatile : contents remain eventhough power goesdown
REV00
10DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
11/265
Chapter 1: Steps Involved in the ProgrammingProcess
6 programming phases:Understand the problemPlan the logic
Code the programUse software to translate the program to machinelanguageTest the program
Put the program into production
REV00
11DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
12/265
Chapter 1: Steps Involved in the ProgrammingProcess
Understanding the Problem May be the most difficult phaseUsers may not be able to articulate their needs well
User needs may be changing frequentlyProgrammers may have to learn the user s functional jobtasksFailure to understand the problem is the major cause of
most project failures
REV00
12DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
13/265
Chapter 1: Steps Involved in the ProgrammingProcess
Planning the Logic Plan the steps that the program will takeUse tools such as flowcharts and pseudocode
Flowchart : a pictorial representation of the logic stepsPseudocode : Natural language representation of the logicWalk through the logic before coding by desk-checking the logic
REV00
13DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
14/265
Chapter 1: Steps Involved in the ProgrammingProcess
Coding the Program Select the programming language
Some languages more efficient for certain tasks
All languages handle input, arithmetic processing,output, other standard functionsLogic can be executed in any number of languages
Write the instructionsPlanning generally more difficult than coding
REV00
14DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
15/265
Chapter 1: Steps Involved in the ProgrammingProcess
Using Software to Translate the Program into MachineLanguage Programmers write instructions in high-level languages
that resemble a natural languageCompilers or interpreters change the programs into alow-level machine language that can be executedSyntax errors are identified by the compiler or
interpreter
REV00
15DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
16/265
Chapter 1: Steps Involved in the ProgrammingProcess
Creating an executable program
Using Software to Translate the Program into Machine Language
REV00
16DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
17/265
Chapter 1: Steps Involved in the ProgrammingProcess
Testing the Program Execute it with sample data and check resultsIdentify logic errors and correct them
Choose test data carefully to exercise all branches ofthe logic
REV00
17DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
18/265
Chapter 1: Steps Involved in the ProgrammingProcess
Putting the Program into Production Might mean simply running the program onceProcess might take months if program is used on
regular basis or is part of larger developmentTrain data-entry people and usersChange existing data
Conversion : entire set of actions organization must
take to switch over to new program(s)
REV00
18DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
19/265
Chapter 1: Steps Involved in the ProgrammingProcess
1 Planning
2 AnalysisIdentify data objectsGoal to model propertiesDetermine Input / Output dataConstraints on the problem
3 Design
Decompose into smaller problemsTop-down design (divide andconquer)Develop algorithm (Desk check)
4 ImplementationWriting the algorithm
5 TestingVerify the program meets
requirementsSystem and Unit test
6 MaintainingMaintain the system
Software Development Method
REV00
19DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
20/265
Chapter 1: Interactive Input
Prompt: message displayed on a monitor Asks the user for a response
Command prompt: location to type entries to
communicate with the operating systemGraphical User Interface (GUI): allows users tointeract with a program in a graphical environment
REV00
20DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
21/265
Chapter 1: Interactive Input
A prompt, response, and output in a command line environment
REV00
21DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
22/265
Chapter 1: Interactive Input
A prompt, response, and output in a GUI environment
REV00
22DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
23/265
Chapter 1: Data Hierarchy and File Input
Data hierarchy : ordering of data types by sizeCharacter : single symbol
A, 7, $
Field : group of characters forming a single data itemSmith
Record : a group of related fieldsCustomer record containing name and addressfields
REV00
23DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
24/265
Chapter 1: Data Hierarchy and File Input
File : a group of related recordsCustomer file, containing all customer records
Database : collection of related files, called tables,that serve the information needs of theorganization
REV00
24DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
25/265
Chapter 1: Data Hierarchy and File Input
The data hierarchy
REV00
25DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
26/265
Chapter 1: Data Hierarchy and File Input
The EMPLOYEE file represented as a stack of index cards
REV00
26DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
27/265
Chapter 1: Flowchart Symbols and PseudocodeStatements
Flowchart : pictorial representation of the logicPseudocode : English-like representation of the logic
Example:
startget inputNumbercompute calculatedAnswer as
inputNumber times 2print calculatedAnswer
stop
REV00
27DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
28/265
Chapter 1: Flowchart Symbols and PseudocodeStatements
Input symbol
Processing symbol
Output symbol
REV00
28DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
29/265
Chapter 1: Flowchart Symbols and PseudocodeStatements
Flowlines :Connect the stepsShow the sequence of statements
Have arrows to show the direction
Terminal symbol (start/stop symbol):Shows the start and end points of the statementsLozenge shape
REV00
29DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
30/265
Chapter 1: Flowchart Symbols and PseudocodeStatements
Flowchart and pseudocode of program that doubles a number
REV00
30DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
31/265
Chapter 1: Flowchart Symbols and PseudocodeStatements
Inefficient pseudocode for program that doubles 10,000 numbers
REV00
31DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
32/265
Chapter 1: Flowchart Symbols and PseudocodeStatements
Flowchart of infinite number-doubling program
REV00
32DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
33/265
Chapter 1: Name Variables, Assign Values toVariables
Variable : a memory location whose contents can vary;also called an identifierEach programming language has its own rules for namingidentifiers, including:
Legal charactersMaximum lengthUse of upper- or lowercase
Variable name must be a single word, but can be formedfrom several wordsrate, interestRate, interest_rate
REV00
33DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
34/265
Chapter 1: Name Variables, Assign Values toVariables
Choose meaningful names for variablesImproves the readability and maintainability of code
Suitability of suggested variable names for an employee s last name
34DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
35/265
Chapter 1: Ending a Program by Using SentinelValues
Infinite loop : a sequence of statements that repeatsforever with no escape
Avoid infinite loops by testing for a predetermined valuethat means stop processing
Decision : testing a valueFlowchart decision symbol : a diamond shape with two
flowlines, one for Yes and one for No
35DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
36/265
REV00
8/13/2019 Programming Fundamental All Chapter
37/265
Chapter 1: Sentinel, or Dummy Value to End AProgram
Sentinel value (or dummy value )Does not represent real dataSignal to stopCan be used with input from files or from users
End-of-file (EOF ) marker :Code stored in the file that marks the end of the data
Usually used instead of a sentinel value for file input
37DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
38/265
Chapter 1: Sentinel, or Dummy Value to End AProgram
Flowchart using eof38DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
39/265
Chapter 1: Manage Large Flowcharts
Flowchart connector symbol :Marks a logic transfer to another location in theflowchart
Transfer location can be on the same page or onanother pageOn-page symbol : a circle with a number or letter toidentify the matching transfer locationOff-page symbol : a square with a pointed bottom,containing page number and a number of letter toidentify the matching transfer location
39DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
40/265
REV00
8/13/2019 Programming Fundamental All Chapter
41/265
Chapter 1: Data Types, the Evolution ofProgramming Techniques
Some programming languages implement several numericdata types, such as:
Integer : whole numbers only
Floating-point : fractional numeric values with decimalpointsCharacter or string data is represented as charactersenclosed in quotation marks
x, color Data types must be used appropriately
41DDC1023 PROGRAMMING METHODOLOGY
Ch t 1 D t T th E l ti fREV00
8/13/2019 Programming Fundamental All Chapter
42/265
Chapter 1: Data Types, the Evolution ofProgramming Techniques
Some examples of legal and illegal assignments42DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
43/265
REV00
8/13/2019 Programming Fundamental All Chapter
44/265
Chapter 1: Summary
Data hierarchyCharacterFieldRecordFile
Database
Software Development MethodPlanning
AnalysisDesignImplementationTestingMaintaining
44DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
45/265
Chapter 1: Summary
Flowchart: pictorial representation of program logic
Variables: named memory locations that contain valuesTesting a value involves making a decision
Assignment statements: store a value into a variable Assignment operator: the equal (=) sign in most
languages2 major data types:textnumeric
Procedural programming:focuses on actions performed on data
Object-oriented programming:focuses on representing and manipulating objects
45DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
46/265
Chapter 2: Understanding Structure
Objectives Learn about the features of unstructured spaghetticodeUnderstand the three basic structures:
sequenceselectionloop
Use a priming read Appreciate the need for structure
Recognize structureLearn about 3 special structures: case , do-while ,and do-until
46DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
47/265
Chapter 2: Features of UnstructuredSpaghetti Code
Spaghetti code : logically snarled program statementsCan be the result of poor program design
Spaghetti code programs often work, but are difficult to
read and maintainConvoluted logic usually requires more code
47DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
48/265
Chapter 2: Features of UnstructuredSpaghetti Code
Example: College Admissions Admit students who score >= 90 on admissions test ifupper 75 percent of high-school graduating class
Admit students who score >= 80 on test if upper 50percent of high-school graduating class Admit students who score >= 70 on admission test ifupper 25 percent of high-school graduating class
48DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
49/265
Chapter 2: Features of UnstructuredSpaghetti Code
49DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
50/265
Chapter 2: Three Basic Structures: Sequence,Selection and Loop
Structure : basic unit of programming logic Any program can be constructed from only 3 basic typesof structures
SequencePerform actions in orderNo branching or skipping any task
Selection (decision) Ask a question, take one of 2 actionsDual-alternative or single-alternative
LoopRepeat actions based on answer to a question
50DDC1023 PROGRAMMING METHODOLOGY
8/13/2019 Programming Fundamental All Chapter
51/265
REV00
8/13/2019 Programming Fundamental All Chapter
52/265
Chapter 2: Three Basic Structures: Sequence,Selection and Loop
Selection structure
Selection structure
52DDC1023 PROGRAMMING METHODOLOGY
REV00
8/13/2019 Programming Fundamental All Chapter
53/265
DDC1023 PROGRAMMING METHODOLOGY 53
Chapter 2: Three Basic Structures: Sequence,Selection and Loop
Dual-alternative if : contains 2 alternatives
if someCondition is true thendo oneProcess
else
do theOtherProcess
REV00
http://www.mywickedspace.com/graphics/glitter/Animals/thing2.gif8/13/2019 Programming Fundamental All Chapter
54/265
DDC1023 PROGRAMMING METHODOLOGY 54
Chapter 2: Three Basic Structures: Sequence,Selection and Loop
Single-alternative if : contains 1 alternative
Single-alternative selection structure
8/13/2019 Programming Fundamental All Chapter
55/265
REV00
8/13/2019 Programming Fundamental All Chapter
56/265
DDC1023 PROGRAMMING METHODOLOGY 56
Chapter 2: Three Basic Structures: Sequence,Selection and Loop
Loop structureRepeats a set of actions based on the answer to aquestion
Also called repetition or iterationQuestion is asked first in the most common form ofloop
Loop structure
REV00
8/13/2019 Programming Fundamental All Chapter
57/265
DDC1023 PROGRAMMING METHODOLOGY 57
Chapter 2: Three Basic Structures: Sequence,Selection and Loop
Loop structure
while testCondition continues to be true
do someProcess
while quantityInInventory remains low
continue to orderItems
REV00
8/13/2019 Programming Fundamental All Chapter
58/265
DDC1023 PROGRAMMING METHODOLOGY 58
Chapter 2: Three Basic Structures: Sequence,Selection and Loop
All logic problems can be solved using only these 3structuresStructures can be combined in an infinite number of ways
Stacking : attaching structures end-to-endEnd-structure statements: indicate the end of a structure
The endif statement ends an if-then-else structureThe endwhile ends a loop structure
REV00
Ch t 2 Th B i St t S
http://www.mywickedspace.com/graphics/glitter/Animals/i95981776_29860.gif8/13/2019 Programming Fundamental All Chapter
59/265
DDC1023 PROGRAMMING METHODOLOGY 59
Chapter 2: Three Basic Structures: Sequence,Selection and Loop
Structured flowchart and pseudocode
REV00
8/13/2019 Programming Fundamental All Chapter
60/265
DDC1023 PROGRAMMING METHODOLOGY 60
Chapter 2: Three Basic Structures: Sequence,Selection and Loop
Any individual task or step in a structure can bereplaced by a structure
Nesting : placing one structure within anotherIndent the nested structure s statements
Block : group of statements that execute as a single
unit
REV00
Chapter 2: Three Basic Structures: Sequence
8/13/2019 Programming Fundamental All Chapter
61/265
DDC1023 PROGRAMMING METHODOLOGY 61
Chapter 2: Three Basic Structures: Sequence,Selection and Loop
Flowchart and pseudocode showing a sequence nested within a selection
8/13/2019 Programming Fundamental All Chapter
62/265
REV00
8/13/2019 Programming Fundamental All Chapter
63/265
DDC1023 PROGRAMMING METHODOLOGY 63
Flowchart and pseudocode for loop within selection within sequence within selection
REV00
Chapter 2: Three Basic Structures: Sequence
8/13/2019 Programming Fundamental All Chapter
64/265
DDC1023 PROGRAMMING METHODOLOGY 64
Chapter 2: Three Basic Structures: Sequence,Selection and Loop
Each structure has 1 entry and 1 exit pointStructures attach to others only at entry or exit points
The 3 structures
REV00
8/13/2019 Programming Fundamental All Chapter
65/265
DDC1023 PROGRAMMING METHODOLOGY 65
Chapter 2: Reasons for Structure
Provides clarityProfessionalismEfficiency
Ease of maintenanceSupports modularity
REV00
http://images.google.com.my/imgres?imgurl=http://www.hudsonlibrary.org/Hudson%2520Website/Computer%2520Lab/MPj04100840000%255B1%255D.jpg&imgrefurl=http://www.hudsonlibrary.org/Hudson%2520Website/Computer%2520Lab/complab.htm&usg=__A90Ujs5ruEDSKcMqWFs1NAtYWms=&h=1024&w=965&sz=84&hl=en&start=8&itbs=1&tbnid=4LD4vNRi1acYyM:&tbnh=150&tbnw=141&prev=/images%3Fq%3Dcomputer%26gbv%3D2%26hl%3Den8/13/2019 Programming Fundamental All Chapter
66/265
DDC1023 PROGRAMMING METHODOLOGY 66
Chapter 2: Reasons for Structure
Any set of instructions can be expressed in structuredformat
Any task to which you can apply rules can be expressedlogically using sequence, selection, loop
It can be difficult to detect whether a flowchart isstructured
REV00
8/13/2019 Programming Fundamental All Chapter
67/265
DDC1023 PROGRAMMING METHODOLOGY 67
Chapter 2: Recognize Structure
Is this flowchart structured?
8/13/2019 Programming Fundamental All Chapter
68/265
REV00
Chapter 2: Recognize Structure
8/13/2019 Programming Fundamental All Chapter
69/265
DDC1023 PROGRAMMING METHODOLOGY 69
Chapter 2: Recognize Structure
Untangling Example 1, 1st step
Single process like A is part of an unacceptable
structure At least the beginning of a sequence structure
REV00
Chapter 2: Recognize Structure
8/13/2019 Programming Fundamental All Chapter
70/265
DDC1023 PROGRAMMING METHODOLOGY 70
Chapter 2: Recognize Structure
B begins a selection structure
Sequences never have decisions in themLogic never returns to B
Untangling Example 1, 2nd step
REV00
Ch 2 R i S
8/13/2019 Programming Fundamental All Chapter
71/265
DDC1023 PROGRAMMING METHODOLOGY 71
Chapter 2: Recognize StructurePull up on the flowline from the left side of B
Untangling Example 1, 3rd step
REV00
Ch 2 R i S
8/13/2019 Programming Fundamental All Chapter
72/265
DDC1023 PROGRAMMING METHODOLOGY 72
Chapter 2: Recognize Structure
Next, pull up the flowline on the right side of B
Untangling Example 1, 4th step
REV00
Chapter 2: Recogni e Str ct re
8/13/2019 Programming Fundamental All Chapter
73/265
DDC1023 PROGRAMMING METHODOLOGY 73
Chapter 2: Recognize Structure
Pull up the flowline on the left side of D and untangle itfrom the B selection by repeating C
Untangling Example 1, 5th step
REV00
Chapter 2: Recognize Structure
8/13/2019 Programming Fundamental All Chapter
74/265
DDC1023 PROGRAMMING METHODOLOGY 74
Chapter 2: Recognize Structure Now pull up the flowline on the right side of D
Untangling Example 1, 6th step
REV00
Ch t 2 R i St t
8/13/2019 Programming Fundamental All Chapter
75/265
DDC1023 PROGRAMMING METHODOLOGY 75
Chapter 2: Recognize StructureBring together the loose ends of D and of B
Finished flowchart and pseudocode for untangling Example 1
REV00
Chapter 2: Three Special Structures: case do while
8/13/2019 Programming Fundamental All Chapter
76/265
DDC1023 PROGRAMMING METHODOLOGY 76
Chapter 2: Three Special Structures: case, do-while,and do-until
Many languages allow 3 additional structures:The case structureThe do-while structureThe do-until structure
CASE Structure:Decisions with more than 2 alternativesTests a variable against a series of values and takes
action based on a matchNested if-then-else statements will do what a case structure does
8/13/2019 Programming Fundamental All Chapter
77/265
REV00
Chapter 2: Three Special Structures: case do while
8/13/2019 Programming Fundamental All Chapter
78/265
DDC1023 PROGRAMMING METHODOLOGY 78
Chapter 2: Three Special Structures: case, do-while,and do-until
Using a case structure for multiple alternatives
Flowchart and pseudocode of case structure
REV00
Chapter 2: Three Special Structures: case do while
8/13/2019 Programming Fundamental All Chapter
79/265
DDC1023 PROGRAMMING METHODOLOGY 79
Chapter 2: Three Special Structures: case, do-while,and do-until
do-while and
do-until loops
Question is asked at the end of the loop structureLoop statements always used at least once
The while loop, which isa pretest loop
Structure of a do-while or do-until loop, which are posttest loops
REV00
Chapter 2: Three Special Structures: case do while
8/13/2019 Programming Fundamental All Chapter
80/265
DDC1023 PROGRAMMING METHODOLOGY 80
Chapter 2: Three Special Structures: case, do-while,and do-until
do-while : executes as long as the question s answer isYes or Truedo-until : executes as long as the question s answer isNo or False
dowash a dish
until all dishes are washed
dowash a dish
while more dishes remain to be washed
REV00
Chapter 2: Three Special Structures: case do while
8/13/2019 Programming Fundamental All Chapter
81/265
DDC1023 PROGRAMMING METHODOLOGY 81
Chapter 2: Three Special Structures: case, do-while,and do-until
while loop with question at beginning is called apretest loopdo-while and do-until with question at end arecalled posttest loops
Posttest loop can be replaced with a sequencefollowed by a pretest while loop
pay a bill
while there are more bills to paypay a bill
endwhile
REV00
Chapter 2: Three Special Structures: case do while
8/13/2019 Programming Fundamental All Chapter
82/265
DDC1023 PROGRAMMING METHODOLOGY 82
Chapter 2: Three Special Structures: case, do-while,and do-until
Flowchart and pseudocode for do-while loop
REV00
Chapter 2: Three Special Structures: case do while
8/13/2019 Programming Fundamental All Chapter
83/265
DDC1023 PROGRAMMING METHODOLOGY 83
Chapter 2: Three Special Structures: case, do-while,and do-until
Flowchart and pseudocode for sequence followed by while loop
REV00
Chapter 2: Three Special Structures: case do-while
8/13/2019 Programming Fundamental All Chapter
84/265
DDC1023 PROGRAMMING METHODOLOGY 84
Chapter 2: Three Special Structures: case, do-while,and do-until
How can this design be made structured?
Unstructured loop
REV00
Chapter 2: Three Special Structures: case do-while
8/13/2019 Programming Fundamental All Chapter
85/265
DDC1023 PROGRAMMING METHODOLOGY 85
Chapter 2: Three Special Structures: case, do-while,and do-until
Repeat the needed step to enforce structure
Sequence and structured loop that accomplish the same tasks as Figure 2-37
8/13/2019 Programming Fundamental All Chapter
86/265
REV00
Chapter 2: Summary
8/13/2019 Programming Fundamental All Chapter
87/265
DDC1023 PROGRAMMING METHODOLOGY 87
Chapter 2: Summary
case structure: questions with multiple alternatives
while loop: a pretest loop asks the question first
while loop statements never execute if the answer is No
do-while and do-until loops: posttest loops that askthe question last
do-while and do-until loop statements are alwaysexecuted at least oncePosttest loop can be replaced by a sequence followedby a while loop
REV00
Chapter 3: The Program Planning Process:
8/13/2019 Programming Fundamental All Chapter
88/265
DDC1023 PROGRAMMING METHODOLOGY 88
Chapter 3: The Program Planning Process:Documentation and Design
ObjectivesLearn about documentationLearn about the advantages of modularization
Learn how to modularize a programDeclare local and global variables and constantsUnderstand the mainline logic for many proceduralprograms
Create hierarchy charts
REV00
8/13/2019 Programming Fundamental All Chapter
89/265
DDC1023 PROGRAMMING METHODOLOGY 89
Chapter 3: Learn About Documentation
Documentation All supporting material that goes with a programTwo major categories: for users and for programmers
Usually created by system analysts and/or tech writersMay be printed or electronic (Web or CD)End users : people who use computer programsProgram Documentation
Internal program documentation: comments withincodeExternal program documentation: supportingpaperwork written before programming begins
REV00
8/13/2019 Programming Fundamental All Chapter
90/265
DDC1023 PROGRAMMING METHODOLOGY 90
Chapter 3: Learn About Documentation
Output DocumentationDescribes the results the user can see when a programis completeUsually written firstPlanning done in consultation with the end user
After desired output is known, programmer can planprocesses needed to produce outputMost common types of output:
Printed reportsScreen output
REV00
8/13/2019 Programming Fundamental All Chapter
91/265
DDC1023 PROGRAMMING METHODOLOGY 91
Chapter 3: Learn About Documentation
Designing Printed Reports Printed reports: designed using a print chartCreated using word-processor or design software
Printed reports may contain:Detail lines : display data detailsHeading lines : contain title and column headingsTotal (or summary ) lines : contain statistics or end ofreport indicators
Printed reports may contain only summary information
http://www.mywickedspace.com/graphics/glitter/Animals/chicken.gif8/13/2019 Programming Fundamental All Chapter
92/265
REV00
8/13/2019 Programming Fundamental All Chapter
93/265
DDC1023 PROGRAMMING METHODOLOGY 93
Chapter 3: Learn About Documentation
Inventory records displayed in a GUIenvironment
Inventory records displayed in arunning program
Designing Screen Output
REV00
8/13/2019 Programming Fundamental All Chapter
94/265
DDC1023 PROGRAMMING METHODOLOGY 94
Chapter 3: Learn About Documentation
Input Documentation Describes what input is available to produce the outputFile description :
Describes data stored in a fileIndicates fields, data types, and lengths
Inventory file description
REV00
8/13/2019 Programming Fundamental All Chapter
95/265
DDC1023 PROGRAMMING METHODOLOGY 95
Chapter 3: Learn About Documentation
Input Documentation Input files organized in different ways
Field may occupy exactly 15 characters for eachrecord
Adding characters to the end of a data field to forceit to a specified size is padding the fieldSome names might be truncated or abbreviated
Fields may be delimitedDelimiter: character that separates fieldsNumeric fields may occupy a specified number ofbytes
REV00
8/13/2019 Programming Fundamental All Chapter
96/265
DDC1023 PROGRAMMING METHODOLOGY 96
Chapter 3: Learn About Documentation
Completing the Documentation Program documentation may contain:
Output designInput descriptionFlowchartsPseudocodeProgram code listing
User documentation may contain:ManualsInstructional materialOperating instructions
REV00
8/13/2019 Programming Fundamental All Chapter
97/265
DDC1023 PROGRAMMING METHODOLOGY 97
Chapter 3: Learn About Documentation
Completing the Documentation User documentation:
Written clearly in plain language
Usually prepared by system analysts and/or techwriters
User documentation usually indicates:How to prepare input
Output distribution and interpretationError message informationRun frequency
http://www.mywickedspace.com/graphics/glitter/Animals/monkey.gif8/13/2019 Programming Fundamental All Chapter
98/265
REV00
8/13/2019 Programming Fundamental All Chapter
99/265
DDC1023 PROGRAMMING METHODOLOGY 99
Chapter 3: The Advantages of Modularization
Modularization : breaking a large program into modules Advantages of modularization:
Provides abstraction
Allows multiple programmers to work simultaneously Allows code reuseMakes identifying structures easier
REV00
http://www.mywickedspace.com/graphics/glitter/Animals/sylvester1.gif8/13/2019 Programming Fundamental All Chapter
100/265
DDC1023 PROGRAMMING METHODOLOGY 100
Chapter 3: The Advantages of Modularization
Modularization Provides AbstractionFocuses on important properties while ignoring non-essential details
Avoids low-level details
Makes complex tasks look simpleHigh-level programming languages allow English-likevocabulary
One statement corresponds to dozens of machineinstructions
Modules provide another way to achieve abstraction
8/13/2019 Programming Fundamental All Chapter
101/265
REV00
8/13/2019 Programming Fundamental All Chapter
102/265
DDC1023 PROGRAMMING METHODOLOGY 102
Chapter 3: The Advantages of Modularization
Modularization Allows Multiple Programmers to Workon a Problem Commercial programs rarely written by a singleprogrammer
Development time is significantly reducedLarge programming projects can be divided into modulesModules can be written by different programmers orprogramming teams
REV00
http://images.google.com.my/imgres?imgurl=http://vietnameseworkersabroad.files.wordpress.com/2009/02/computer.jpg&imgrefurl=http://vietnameseworkersabroad.wordpress.com/2009/02/13/key-briefs-reports-camsa-aims-to-establish-database-of-trafficking-cases/&usg=__XNDUZKbBSyGUKNHgw0qQPwNN6J4=&h=360&w=360&sz=22&hl=en&start=24&itbs=1&tbnid=UTRuxKI618NLCM:&tbnh=121&tbnw=121&prev=/images%3Fq%3Dcomputer%26gbv%3D2%26ndsp%3D20%26hl%3Den%26sa%3DN%26start%3D208/13/2019 Programming Fundamental All Chapter
103/265
DDC1023 PROGRAMMING METHODOLOGY 103
Chapter 3: The Advantages of Modularization
Modularization Allows You to Reuse Your WorkSubroutines that are useful should be used more thanonce in a program
Example: routine that checks the current dateInstructions placed in their own module are easy to portto other applicationsReusability : the ability to use modules in a variety ofapplicationsReliability : assurance that a module has been testedand proven to function correctlyReliable software saves times and money
REV00
8/13/2019 Programming Fundamental All Chapter
104/265
DDC1023 PROGRAMMING METHODOLOGY 104
Chapter 3: How to Modularize A Program
Most programs contain a main programContains the mainline logic
Accesses other modules or subroutines
Rules for naming modules different for everyprogramming language
For this text:Must be one word
Should be meaningfulFollowed by a set of parenthesesCorresponds to module naming in Java, C++, C#
8/13/2019 Programming Fundamental All Chapter
105/265
8/13/2019 Programming Fundamental All Chapter
106/265
REV00
Chapter 3: How to Modularize A Program
8/13/2019 Programming Fundamental All Chapter
107/265
DDC1023 PROGRAMMING METHODOLOGY 107
Sample logic Logic from left figure using a method
REV00
Chapter 3: How to Modularize A Program
8/13/2019 Programming Fundamental All Chapter
108/265
DDC1023 PROGRAMMING METHODOLOGY 108
Logic using two methods
REV00
8/13/2019 Programming Fundamental All Chapter
109/265
DDC1023 PROGRAMMING METHODOLOGY 109
Chapter 3: How to Modularize A Program
Method is encapsulated in another method if it iscontained in another methodKnowing when to break a module into its ownsubroutines or submodules is an artBest practice: place together statements that contributeto one specific taskFunctional cohesion : extent to which the statementscontribute to the same task
REV00
Chapter 3: Declare Local and Global Variables and
8/13/2019 Programming Fundamental All Chapter
110/265
DDC1023 PROGRAMMING METHODOLOGY 110
Chapter 3: Declare Local and Global Variables andConstants
Arguments: data items required by a methodReturning a value: data sent back by a methodMethod must include:
Header: includes method identifier, other identifyinginformationBody: contains all statements in the methodReturn statement: marks the end of the method
Returns control to the calling methodData items are visible only within the method in whichthey are declared
REV00
Chapter 3: Declare Local and Global Variables andConstants
8/13/2019 Programming Fundamental All Chapter
111/265
DDC1023 PROGRAMMING METHODOLOGY 111
Constants
Program that prints a bill using main program that calls nameAndAddress() method
REV00
Chapter 3: Declare Local and Global Variables and
8/13/2019 Programming Fundamental All Chapter
112/265
DDC1023 PROGRAMMING METHODOLOGY 112
Chapter 3: Declare Local and Global Variables andConstants
Variables and constants are in scope only within methodin which they are declared
Variables and constants are local to the method
Global variables and constants are known to the entireprogramVariables and constants declared outside any method aredeclared at the program level
Reasons to declare variables globally:Needed in many methods throughout a programDeclare class s data fields at class level
REV00
Chapter 3: Declare Local and Global Variables and
8/13/2019 Programming Fundamental All Chapter
113/265
DDC1023 PROGRAMMING METHODOLOGY 113
Chapter 3: Declare Local and Global Variables andConstants
Declaring global variables and constants: violatesencapsulationDeclaring variables and constants within methods:methods are portableWhen two or more methods require access to same data,pass the data between methods
REV00
Chapter 3: Declare Local and Global Variables and
8/13/2019 Programming Fundamental All Chapter
114/265
DDC1023 PROGRAMMING METHODOLOGY 114
Constants
Program that prints a bill with some constants declared globally
REV00
Chapter 3: Mainline Logic for Many Procedural
8/13/2019 Programming Fundamental All Chapter
115/265
DDC1023 PROGRAMMING METHODOLOGY 115
p : g yPrograms
Mainline logic of most procedural programs followssame general structure:
Housekeeping tasks
Variable and constant declarationsOpening filesMain loop tasks
Processes that must occur for every data record
End-of-job tasksPrint footer linesClose open files
REV00
Chapter 3: Mainline Logic for Many ProceduralPrograms
http://www.mywickedspace.com/graphics/glitter/Animals/i60756900_85413.gif8/13/2019 Programming Fundamental All Chapter
116/265
DDC1023 PROGRAMMING METHODOLOGY 116
Programs
Flowchart and pseudocode of mainline logic for a typical procedural program
REV00
Chapter 3: Mainline Logic for Many Procedural
8/13/2019 Programming Fundamental All Chapter
117/265
DDC1023 PROGRAMMING METHODOLOGY 117
p g yPrograms
Sample payroll report
REV00
Chapter 3: Mainline Logic for Many ProceduralPrograms
8/13/2019 Programming Fundamental All Chapter
118/265
DDC1023 PROGRAMMING METHODOLOGY 118
Programs
Logic for payroll report
REV00
Chapter 3: Create Hierarchy Charts
8/13/2019 Programming Fundamental All Chapter
119/265
DDC1023 PROGRAMMING METHODOLOGY 119
p y
Hierarchy chart :Illustrates modules relationships Tells which routines call which other routinesDoes not tell when or why the modules are called
Hierarchy chart program
REV00
Chapter 3: Create Hierarchy Charts
8/13/2019 Programming Fundamental All Chapter
120/265
DDC1023 PROGRAMMING METHODOLOGY 120
p y
An organizational hierarchy chart
8/13/2019 Programming Fundamental All Chapter
121/265
REV00
Chapter 3: Summary
8/13/2019 Programming Fundamental All Chapter
122/265
DDC1023 PROGRAMMING METHODOLOGY 122
Documentation: all supporting material for a programOutput documentation: includes report designsFile description: details data types and lengths of eachfield of data in the fileUser documentation: manuals and instructional materials,and operating instructionsModules: smaller, reasonable units of code that providereusability
Subroutines, procedures, functions, methodsModularization:
Provides abstraction Allows multiple programmers to work on a problemMakes it easy to reuse work and identify structures
REV00
Chapter 3: Summary
8/13/2019 Programming Fundamental All Chapter
123/265
DDC1023 PROGRAMMING METHODOLOGY 123
Modules can call other modulesFlowchart symbol is a rectangle with a bar across thetop
Variable declarations define the name and type of thedata to be storedHierarchy chart illustrates modules relationships Common structure for procedural programs:
Housekeeping tasksMain loop
End-of-job tasksHierarchy chart illustrates modules relationships
REV00
Chapter 4: Making Decision
8/13/2019 Programming Fundamental All Chapter
124/265
DDC1023 PROGRAMMING METHODOLOGY 124
p g
Objectives Evaluate Boolean expressions to make comparisonsUse the relational comparison operatorsLearn about AND logicLearn about OR logicMake selections within rangesLearn about precedence when combining AND and OR
selectionsLearn more about the case structureUse a decision table
REV00
Chapter 4: Evaluating Boolean Expressions to Make
8/13/2019 Programming Fundamental All Chapter
125/265
DDC1023 PROGRAMMING METHODOLOGY 125
Comparisons
Dual-alternative (or binary ) selection structure: Provides an action for each of 2 possible outcomes
The dual-alternative selection structure
REV00
Chapter 4: Evaluating Boolean Expressions to Make
8/13/2019 Programming Fundamental All Chapter
126/265
DDC1023 PROGRAMMING METHODOLOGY 126
Comparisons
Single-alternative (or unary ) selection structure Action is provided for only 1 outcome
The single-alternative selection structure
8/13/2019 Programming Fundamental All Chapter
127/265
REV00
Chapter 4: Evaluating Boolean Expressions to MakeComparisons
8/13/2019 Programming Fundamental All Chapter
128/265
DDC1023 PROGRAMMING METHODOLOGY 128
Comparisons
Pseudocode for payroll program with dental insurance determination
REV00
Chapter 4: Evaluating Boolean Expressions to Make
8/13/2019 Programming Fundamental All Chapter
129/265
DDC1023 PROGRAMMING METHODOLOGY 129
Comparisons
Boolean expressionRepresents only one of 2 statesEvaluates to true or false
Every decision in a computer program involvesevaluating a Boolean expressionComputer circuitry consists of two-state on-off switches
Represented by 1 or 0
Every computer decision yields a true-false result
REV00
Chapter 4: Relational Comparison Operators
8/13/2019 Programming Fundamental All Chapter
130/265
DDC1023 PROGRAMMING METHODOLOGY 130
Chapter 4: Relational Comparison Operators
For any 2 values, 3 types of comparisons:2 values are equal1st value greater than the 2nd value
1st value less than the 2nd value
Relational comparison operatorsExpress Boolean tests
Different languages use different symbols
8/13/2019 Programming Fundamental All Chapter
131/265
REV00
Chapter 4: Relational Comparison Operators
8/13/2019 Programming Fundamental All Chapter
132/265
DDC1023 PROGRAMMING METHODOLOGY 132
Chapter 4: Relational Comparison Operators
Using a negative comparison
REV00
Chapter 4: Relational Comparison Operators
8/13/2019 Programming Fundamental All Chapter
133/265
DDC1023 PROGRAMMING METHODOLOGY 133
Chapter 4: Relational Comparison Operators
Using the positive equivalent of the negative comparison in Figure 4-5
REV00
Chapter 4: Relational Comparison Operators
8/13/2019 Programming Fundamental All Chapter
134/265
DDC1023 PROGRAMMING METHODOLOGY134
Chapter 4: Relational Comparison Operators
Relational comparisons
REV00
Chapter 4: AND Logic OR Logic
8/13/2019 Programming Fundamental All Chapter
135/265
DDC1023 PROGRAMMING METHODOLOGY135
Understanding AND LogicCompound condition
Asks multiple questions before an outcome isdetermined
AND decision Requires that both of 2 tests evaluate to TrueRequires a nested decision (nested if )
Using nested if statements
Second selection structure is contained entirelywithin 1 side of 1st structure
else clause paired with last if
REV00
Chapter 4: AND Logic OR Logic
8/13/2019 Programming Fundamental All Chapter
136/265
DDC1023 PROGRAMMING METHODOLOGY136
Flowchart and pseudocode for selection process in revised bonus-determiningprogram
Understanding AND Logic
REV00
Chapter 4: AND Logic OR Logic
8/13/2019 Programming Fundamental All Chapter
137/265
DDC1023 PROGRAMMING METHODOLOGY137
Nesting AND Decisions for Efficiency When nesting decisions, either selection can come firstPerformance time can be improved by asking questionsin the proper orderIn an AND decision, first ask the question that is lesslikely to be true
Eliminates as many instances of the 2nd decision aspossibleSpeeds up processing time
REV00
Chapter 4: AND Logic OR Logic
8/13/2019 Programming Fundamental All Chapter
138/265
DDC1023 PROGRAMMING METHODOLOGY138
Understanding OR Logic When you want to take action when 1 or the other of 2conditions is true
Example:Salespeople get bonus when they have achieved oneof two goals:
Sell at least five itemsSell at least $2,000 in merchandise
itemsSold >= ITEMS_MIN ?If true, assign $300 bonus
REV00
Chapter 4 : AND Logic OR Logic
8/13/2019 Programming Fundamental All Chapter
139/265
DDC1023 PROGRAMMING METHODOLOGY139
Writing OR Decisions for Efficiency May ask either question first
Both produce the same output, but vary widely innumber of questions asked
If first question is true, no need to ask second
In an OR decision first ask the question that is more
likely to be trueEliminates as many repetitions as possible ofsecond decision
REV00
Chapter 4: Precedence When Combining AND and OR
8/13/2019 Programming Fundamental All Chapter
140/265
DDC1023 PROGRAMMING METHODOLOGY140
Selections
Combining Decisions in an AND SelectionConditional AND operator allows you to ask 2 or morequestions in a single comparisonEach Boolean expression must be true for entireexpression to evaluate to trueTruth tables describe the truth of an entire expressionbased on the truth of its partsShort-circuit evaluation: expression evaluated only asfar as necessary to determine truth
REV00
Chapter 4: Precedence When Combining AND and OR S l i
8/13/2019 Programming Fundamental All Chapter
141/265
DDC1023 PROGRAMMING METHODOLOGY141
Selections
Combining Decisions in an OR SelectionConditional OR operator allows you to ask 2 or morequestions in a single comparisonOnly one Boolean expression in an OR selection mustbe true to produce a result of trueQuestion placed first will be asked first, so considerefficiencyComputer can ask only one question at a time
REV00
Chapter 4: Precedence When Combining AND and OR l
http://www.mywickedspace.com/graphics/glitter/Animals/i129754557_66085.gif8/13/2019 Programming Fundamental All Chapter
142/265
DDC1023 PROGRAMMING METHODOLOGY 142
Selections
Truth table for the AND operator
Combining Decisions in an AND Selection
REV00
Chapter 4: Precedence When Combining AND and OR S l ti
8/13/2019 Programming Fundamental All Chapter
143/265
DDC1023 PROGRAMMING METHODOLOGY 143
Selections
Truth table for the OR operator
Combining Decisions in an OR Selection
8/13/2019 Programming Fundamental All Chapter
144/265
REV00
Chapter 4: Precedence When Combining AND and OR S l ti
8/13/2019 Programming Fundamental All Chapter
145/265
DDC1023 PROGRAMMING METHODOLOGY 145
Selections
Using an OR operator and the logic behind it
Combining Decisions in an OR Selection
REV00
Chapter 4: Case Structure
8/13/2019 Programming Fundamental All Chapter
146/265
DDC1023 PROGRAMMING METHODOLOGY 146
Provides a series of alternatives based on the value ofa single variable
Replaces a series of chained if-else statements
Makes code easier to read
REV00
Chapter 4: Case Structure
8/13/2019 Programming Fundamental All Chapter
147/265
DDC1023 PROGRAMMING METHODOLOGY 147
Flowchart and pseudocode that determines base price for house based onmodel number using the case structure
REV00
Chapter 4: Decision Table
8/13/2019 Programming Fundamental All Chapter
148/265
DDC1023 PROGRAMMING METHODOLOGY 148
Managing multiple possible outcomes of multiple decisions can be difficult
Decision table : four-part problem-analysis tool
ConditionsPossible combinations of Boolean values for eachconditionPossible actions based on the conditions
Specific actions that correspond to each Booleanvalue of each condition
REV00
Chapter 4: Decision Table
http://www.medicinemancreations.com/go/view.php?image=images/CuteEasterBuuny.gifhttp://www.medicinemancreations.com/go/view.php?image=images/CuteEasterBuuny.gif8/13/2019 Programming Fundamental All Chapter
149/265
DDC1023 PROGRAMMING METHODOLOGY 149
Sample residence hall assignments report
REV00
Chapter 4: Decision Table
8/13/2019 Programming Fundamental All Chapter
150/265
DDC1023 PROGRAMMING METHODOLOGY 150
Rules for assigning residence hallsStudents under age 21 who request a hall with quietstudy hours: Addams HallStudents under age 21 who do not request a hallwith quiet study hours: Grant HallStudents age 21 and over who request a hall withquiet study hours: Lincoln HallStudents age 21 and over who do not request a hallwith quiet study hours: Lincoln Hall
REV00
Chapter 4: Decision Table
8/13/2019 Programming Fundamental All Chapter
151/265
DDC1023 PROGRAMMING METHODOLOGY 151
To create a decision table:List all possible conditionsDetermine the possible Boolean value combinationsfor each condition# combinations = 2 (number of conditions)
Conditions and possible values for residence hall determination
REV00
Chapter 4: Decision Table
8/13/2019 Programming Fundamental All Chapter
152/265
DDC1023 PROGRAMMING METHODOLOGY 152
To create a decision table: Add rows to list possible outcome actionsChoose one required outcome for each combination
Completed decision table for residence hall selection
REV00
Chapter 4: Decision Table
8/13/2019 Programming Fundamental All Chapter
153/265
DDC1023 PROGRAMMING METHODOLOGY 153
Program that assigns a student to a residence hall
REV00
Chapter 5: Looping
8/13/2019 Programming Fundamental All Chapter
154/265
DDC1023 PROGRAMMING METHODOLOGY 154
Objectives Learn about the advantages of loopingControl loops with counters and sentinel valuesNest loopsUse posttest loopsRecognize the characteristics shared by all loopsLearn about common loop applications
REV00
Chapter 5: Advantages of Looping
8/13/2019 Programming Fundamental All Chapter
155/265
DDC1023 PROGRAMMING METHODOLOGY 155
Looping makes computer programming efficient andworthwhileWrite one set of instructions to operate on multiple,separate sets of dataLoop : structure that repeats actions while somecondition continues
REV00
Chapter 5: Advantages of Looping
8/13/2019 Programming Fundamental All Chapter
156/265
DDC1023 PROGRAMMING METHODOLOGY 156
The while loop
REV00
Chapter 5: Control Loops with Counters andSentinel Values
8/13/2019 Programming Fundamental All Chapter
157/265
DDC1023 PROGRAMMING METHODOLOGY 157
As long as a Boolean expression remains true, while loop s body executes Must control number of repetitions to avoid an infiniteloop
Repetitions controlled byCounterSentinel value
REV00
Chapter 5: Control Loops with Counters andSentinel Values
8/13/2019 Programming Fundamental All Chapter
158/265
DDC1023 PROGRAMMING METHODOLOGY 158
Using a Definite while
Loop with a Counter Three actions make a while loop end correctly:
Loop control variable is initializedPrior to entering the loop
Loop control variable is testedIf result is true, loop body entered
Loop control variable must be altered in loop bodywhile expression eventually evaluates to false
Loop control variables altered by:IncrementingDecrementing
REV00
Chapter 5: Control Loops with Counters andSentinel Values
Using a Definite while Loop with a Counter
8/13/2019 Programming Fundamental All Chapter
159/265
DDC1023 PROGRAMMING METHODOLOGY 159 A while loop that prints Hello four times
g while p
REV00
Chapter 5: Control Loops with Counters andSentinel Values
8/13/2019 Programming Fundamental All Chapter
160/265
DDC1023 PROGRAMMING METHODOLOGY 160
Using a Definite while Loop with a CounterDefinite loop : number of iterations predetermined
Also called counted loopCounter : numeric variable used to count number of
times an event occursLoop control variable may be altered by user inputIndefinite loop : loop iterates until some condition is true
Number of iterations may vary
REV00
Chapter 5: Control Loops with Counters andSentinel Values
http://www.mywickedspace.com/graphics/glitter/Animals/bunny1.gif8/13/2019 Programming Fundamental All Chapter
161/265
DDC1023 PROGRAMMING METHODOLOGY 161
Using an Indefinite while Loop with a Sentinel Value Indefinite loop: loop performed a different number oftimes each time the program executes3 crucial steps:
Starting value to control the loop must be providedComparison must be made using the value thatcontrols the loopWithin the loop, value that controls the loop must be
alteredLoop control variable : any variable that determineswhether the loop will continue
REV00
8/13/2019 Programming Fundamental All Chapter
162/265
DDC1023 PROGRAMMING METHODOLOGY 162
Looping bank balance program
REV00
Chapter 5: Control Loops with Counters andSentinel Values
8/13/2019 Programming Fundamental All Chapter
163/265
DDC1023 PROGRAMMING METHODOLOGY 163
Typical execution of the looping bank balance program
Using an Indefinite while Loop with a Sentinel Value
REV00
Chapter 5: Control Loops with Counters andSentinel Values
8/13/2019 Programming Fundamental All Chapter
164/265
DDC1023 PROGRAMMING METHODOLOGY 164Crucial steps that must occur in every loop
Using anIndefinite while Loop with aSentinel Value
REV00
Chapter 5: Nested Loops
8/13/2019 Programming Fundamental All Chapter
165/265
DDC1023 PROGRAMMING METHODOLOGY 165
Nested loops : loops within loopsOuter loop : loop that contains the other loopInner loop : loop that is containedNeeded when values of two (or more) variables repeat
to produce every combination of values
REV00
8/13/2019 Programming Fundamental All Chapter
166/265
DDC1023 PROGRAMMING METHODOLOGY 166
Flowchart and pseudocode for AnswerSheet program
REV00
Chapter 5: Posttest Loops
8/13/2019 Programming Fundamental All Chapter
167/265
DDC1023 PROGRAMMING METHODOLOGY 167
Loop body may never execute in while loop and for loopUse posttest loop when loop body must execute at leastonce
do-until loop do-while loopdo-until loop executes until condition is truedo-while loop executes until condition is false
http://www.mywickedspace.com/graphics/glitter/Animals/i54196966_71287.gif8/13/2019 Programming Fundamental All Chapter
168/265
REV00
Chapter 5: Posttest Loops
8/13/2019 Programming Fundamental All Chapter
169/265
DDC1023 PROGRAMMING METHODOLOGY 169
Label production program using a do-until loop
REV00
Chapter 5: The Characteristics Shared by AllLoops
8/13/2019 Programming Fundamental All Chapter
170/265
DDC1023 PROGRAMMING METHODOLOGY 170
Every logical problem could be solved using only thewhile loopOther forms are conveniences
while loop
Loop-controlling question placed at beginning of stepsthat repeat
do-until loopLoop-controlling question placed at end of steps that
repeat
REV00
Chapter 5: The Characteristics Shared by AllLoops
http://www.mywickedspace.com/graphics/glitter/Animals/i130245447_47898.gif8/13/2019 Programming Fundamental All Chapter
171/265
DDC1023 PROGRAMMING METHODOLOGY 171
Characteristics of all structured loops:Loop-controlling question must provide entry or exitfrom repeating structureLoop-controlling question provides the only entry to or
exit from the repeating structureExactly one loop-controlling value
Provides only entry to or exit from the loop
REV00
Chapter 5: The Characteristics Shared by AllLoops
8/13/2019 Programming Fundamental All Chapter
172/265
DDC1023 PROGRAMMING METHODOLOGY 172
Examples of unstructured loops
REV00
Chapter 5: Common Loop Applications
8/13/2019 Programming Fundamental All Chapter
173/265
DDC1023 PROGRAMMING METHODOLOGY 173
Using a loop to accumulate totalsExamples:
Business reports often include totalsTelephone bill provides a total
List of real estate sold and total value
Accumulator : variable that gathers valuesSimilar to a counter
Counter increments by one Accumulator increments by some value
REV00
Chapter 5: Common Loop Applications
http://www.mywickedspace.com/graphics/glitter/Animals/i54198502_40438.gif8/13/2019 Programming Fundamental All Chapter
174/265
DDC1023 PROGRAMMING METHODOLOGY 174
Accumulate total real estate pricesDeclare numeric variable at beginningInitialize the accumulator to 0Read each transaction s data record
Add its value to accumulator variableRead the next record until eof
Variables exist only for the life of the applicationRun the application a second time, variables occupydifferent memory location
REV00
Chapter 5: Common Loop Applications
8/13/2019 Programming Fundamental All Chapter
175/265
DDC1023 PROGRAMMING METHODOLOGY 175
Month-end real estate sales report
REV00
8/13/2019 Programming Fundamental All Chapter
176/265
DDC1023 PROGRAMMING METHODOLOGY 176
Flowchart and pseudocode for real estate sales report program
REV00
Chapter 5: Common Loop Applications
8/13/2019 Programming Fundamental All Chapter
177/265
DDC1023 PROGRAMMING METHODOLOGY 177
Using a loop to validate dataWhen prompting a user for data, no guarantee thatdata is valid
Validate data : make sure data falls in acceptable ranges
Example: user enters birth monthIf number less than 1 or greater than 12
Display error message and stop the program Assign default value for the monthReprompt the user for valid input
REV00
Chapter 5: Common Loop Applications
http://www.mywickedspace.com/graphics/glitter/Animals/fish.gif8/13/2019 Programming Fundamental All Chapter
178/265
DDC1023 PROGRAMMING METHODOLOGY 178
Reprompting a user once after an invalid month is entered
REV00
Chapter 5: Common Loop Applications
8/13/2019 Programming Fundamental All Chapter
179/265
DDC1023 PROGRAMMING METHODOLOGY 179
Reprompting a user continuously after an invalid month is entered
REV00
Chapter 5: Summary
8/13/2019 Programming Fundamental All Chapter
180/265
DDC1023 PROGRAMMING METHODOLOGY 180
When using a loop, write one set of instructions thatoperates on multiple, separate dataThree steps must occur in every loop:
Initialize loop control variable
Compare variable to some value Alter the variable that controls the loop
Nested loops: loops within loopsNested loops maintain two individual loop controlvariables
Alter each at the appropriate time
http://www.mywickedspace.com/graphics/glitter/Animals/i53855315_83351.gif8/13/2019 Programming Fundamental All Chapter
181/265
REV00
Chapter 6: Overview of C
8/13/2019 Programming Fundamental All Chapter
182/265
DDC1023 PROGRAMMING METHODOLOGY 182
Objectives Learn about the C language elements
Apply the variable declarations and data types.Understand Input/output functions printf and scanf .Include preprocessor directives #include and #define Use assignment statement with arithmetic operatorsLearn about the general form of a C program
Apply the formatting numbers in program outputKnow the interactive modeIdentify the common programming errors
REV00
Chapter 6: C Language Elements
8/13/2019 Programming Fundamental All Chapter
183/265
DDC1023 PROGRAMMING METHODOLOGY 183
Preprocessordirectives
Main function
REV00
Chapter 6: Variable Declarations and Data Types
8/13/2019 Programming Fundamental All Chapter
184/265
DDC1023 PROGRAMMING METHODOLOGY 184
Variables: values stored in variables can changesVariables Declarations:
What kind of information will be stored in eachvariable
How that information will be represented inmemory
REV00
Chapter 6: Variable Declarations and Data Types
http://www.mywickedspace.com/graphics/glitter/Animals/pony.gif8/13/2019 Programming Fundamental All Chapter
185/265
DDC1023 PROGRAMMING METHODOLOGY 185
Variable declaration according to its data type.
EXAMPLES:int count,large;
double x, y, z;char first_initial;char ans;
http://www.mywickedspace.com/graphics/glitter/Animals/tigger1.gif8/13/2019 Programming Fundamental All Chapter
186/265
REV00
Chapter 6: Executable Statements
Program in Memory
8/13/2019 Programming Fundamental All Chapter
187/265
DDC1023 PROGRAMMING METHODOLOGY 187
Memory(a) Before and (b) After Execution of a Program
Program in Memory
REV00
Chapter 6: Executable Statements
8/13/2019 Programming Fundamental All Chapter
188/265
DDC1023 PROGRAMMING METHODOLOGY 188
kms = KMS_PER_MILE * miles;
Assignment Statements
REV00
Chapter 6: Executable StatementsBefore and After Assignment of a variable
8/13/2019 Programming Fundamental All Chapter
189/265
DDC1023 PROGRAMMING METHODOLOGY 189
sum = sum + item;
REV00
Chapter 6: Executable Statements
8/13/2019 Programming Fundamental All Chapter
190/265
DDC1023 PROGRAMMING METHODOLOGY 190
Input and Output Operations and FunctionsOperationsFunctions#include
C function: printfC function: scanf
REV00
Chapter 6: Executable StatementsFunction (printf)
http://www.mywickedspace.com/graphics/glitter/Animals/i86771984_77590.gif8/13/2019 Programming Fundamental All Chapter
191/265
DDC1023 PROGRAMMING METHODOLOGY 191
REV00
Chapter 6: Executable Statements
8/13/2019 Programming Fundamental All Chapter
192/265
DDC1023 PROGRAMMING METHODOLOGY 192
scanf("%lf", &miles);
Function (scanf)
REV00
Chapter 6: Executable Statements
Function (scanf)
8/13/2019 Programming Fundamental All Chapter
193/265
DDC1023 PROGRAMMING METHODOLOGY 193
scanf("%c%c%c", &letter_1, &letter_2, &letter_3 );
Function (scanf)
REV00
Chapter 6: General Form of a C program
8/13/2019 Programming Fundamental All Chapter
194/265
DDC1023 PROGRAMMING METHODOLOGY 194
Preprocessor directives: #include, #define Any used variable should be declared before the usage.
http://www.mywickedspace.com/graphics/glitter/Animals/penguin.gif8/13/2019 Programming Fundamental All Chapter
195/265
8/13/2019 Programming Fundamental All Chapter
196/265
REV00
Chapter 6: Formatting numbers in programoutput
8/13/2019 Programming Fundamental All Chapter
197/265
DDC1023 PROGRAMMING METHODOLOGY 197
8/13/2019 Programming Fundamental All Chapter
198/265
REV00
Chapter 6: Common Programming Errors
8/13/2019 Programming Fundamental All Chapter
199/265
DDC1023 PROGRAMMING METHODOLOGY 199
Syntax ErrorsRun-Time ErrorsUndetected ErrorsLogic Errors
8/13/2019 Programming Fundamental All Chapter
200/265
REV00
Chapter 6: Common Programming Errors
Run-time error occurs when theg di t th t t f
8/13/2019 Programming Fundamental All Chapter
201/265
DDC1023 PROGRAMMING METHODOLOGY 201
program directs the computer to performan illegal operation (e.g., divide by zero).
temp=0divide by zero
8/13/2019 Programming Fundamental All Chapter
202/265
REV00
Chapter 6: Summary
E C h di i d
8/13/2019 Programming Fundamental All Chapter
203/265
DDC1023 PROGRAMMING METHODOLOGY 203
Every C program has preprocessor directives and amain function.The main function contains variable declarations andexecutable statements.Variable names must begin with a letter or anunderscore and consist of letters, digits, and underscoresymbols.
A reserved word cannot be used as an identifier.
REV00
Chapter 7: Data Types, Operators and SimpleFunctions in C
http://www.mywickedspace.com/graphics/glitter/Animals/i53365827_9738.gif8/13/2019 Programming Fundamental All Chapter
204/265
DDC1023 PROGRAMMING METHODOLOGY 204
ObjectivesUnderstand the data types Able to write program with arithmetic operatorsLearn about the mixed-type assignment statement
Know how to use the expression with multiple operators
REV00
Chapter 7: Data Types
int
8/13/2019 Programming Fundamental All Chapter
205/265
DDC1023 PROGRAMMING METHODOLOGY 205
Range : -32767 ~ + 32767 --- in ANSI C-10500 435 +15 -25 32767
double
charA a z 2 9 * ?
REV00
Chapter 7: Arithmetic Operators
8/13/2019 Programming Fundamental All Chapter
206/265
DDC1023 PROGRAMMING METHODOLOGY 206
REV00
Chapter 7: Arithmetic Operators
Execution of Multiple Operators
8/13/2019 Programming Fundamental All Chapter
207/265
DDC1023 PROGRAMMING METHODOLOGY 207
Can be expressed as an Evaluation Tree .
area = PI * radius * radius;
REV00
Chapter 7: Arithmetic Operators
8/13/2019 Programming Fundamental All Chapter
208/265
DDC1023 PROGRAMMING METHODOLOGY 208
Step by Step Expression Evaluation
REV00
Chapter 7: Arithmetic OperatorsEvaluation Tree
8/13/2019 Programming Fundamental All Chapter
209/265
DDC1023 PROGRAMMING METHODOLOGY 209
v = (p2 - p1) / (t2 - t1);
REV00
Chapter 7: Arithmetic Operators
z - (a + b / 2) + w * -y
Evaluation Tree
8/13/2019 Programming Fundamental All Chapter
210/265
DDC1023 PROGRAMMING METHODOLOGY 210
z (a b / 2) w y
REV00
Chapter 7: Writing Mathematical Formulas in C
You may encounter two problems in writing a
8/13/2019 Programming Fundamental All Chapter
211/265
DDC1023 PROGRAMMING METHODOLOGY 211
You may encounter two problems in writing amathematical formula in C.First, multiplication often can be implied in a formula bywriting two letters to be multiplied next to each other. InC, you must state the * operator
For example, 2a should be written as 2 * a.Second, when dealing with division we often have:
This should be coded as (a + b) / (c + d).
REV00
Chapter 7: Library functionsFunction Header File Description
8/13/2019 Programming Fundamental All Chapter
212/265
DDC1023 PROGRAMMING METHODOLOGY 212
abs( x ) Return the absolute value of x
cos( x ) Return the cosine of angle x
exp( x ) Return the value of e x
pow( x , y ) Return the value of x y
sqrt( x ) Return the squre root of x
For I/O library functions ( printf, scanf )To use them, have to use #include
For Mathematical Functions ( sqrt, pow, sin, cos )To use them, have to use #include
8/13/2019 Programming Fundamental All Chapter
213/265
8/13/2019 Programming Fundamental All Chapter
214/265
REV00
Chapter 8: Selection Structures: If and SwitchStatement In C
Objectives
8/13/2019 Programming Fundamental All Chapter
215/265
DDC1023 PROGRAMMING METHODOLOGY 215
ObjectivesLearn about the control structureUnderstand the conditions
Apply the if statement with compound statements
Use decision steps in algorithmsLearn about the nested if statements and multiplealternative decisionsLearn about the switch Statement
8/13/2019 Programming Fundamental All Chapter
216/265
8/13/2019 Programming Fundamental All Chapter
217/265
REV00
Chapter 8: Conditions
Relational and Equality Operators
8/13/2019 Programming Fundamental All Chapter
218/265
DDC1023 PROGRAMMING METHODOLOGY 218
q y p
REV00
Chapter 8: Conditions
Sample Conditions
8/13/2019 Programming Fundamental All Chapter
219/265
DDC1023 PROGRAMMING METHODOLOGY 219
p
8/13/2019 Programming Fundamental All Chapter
220/265
8/13/2019 Programming Fundamental All Chapter
221/265
REV00
Chapter 8: Conditions
Operator Precedence
8/13/2019 Programming Fundamental All Chapter
222/265
DDC1023 PROGRAMMING METHODOLOGY 222
An operator s precedence determines its order of evaluation.
- x y * z
x + y < min + max
REV00
Chapter 8: Conditions Evaluation Tree & Step-by-Step Evaluation
8/13/2019 Programming Fundamental All Chapter
223/265
DDC1023 PROGRAMMING METHODOLOGY 223
REV00
Chapter 8: Conditions
Short Circuit Evaluation
8/13/2019 Programming Fundamental All Chapter
224/265
DDC1023 PROGRAMMING METHODOLOGY 224
Short Circuit Evaluation Stopping evaluation of a logical expression as soon asits value can be determined.
e.g. a && b must be false if a is 0 .
REV00
Chapter 8: Conditions
8/13/2019 Programming Fundamental All Chapter
225/265
DDC1023 PROGRAMMING METHODOLOGY 225
Writing English Conditions in C
REV00
Chapter 8: Conditions
8/13/2019 Programming Fundamental All Chapter
226/265
DDC1023 PROGRAMMING METHODOLOGY 226
Comparing Characters
REV00
Chapter 8: Conditions
Complement a logical expression
8/13/2019 Programming Fundamental All Chapter
227/265
DDC1023 PROGRAMMING METHODOLOGY 227
Complement a logical expressionwith the symbol !
just change its operator
item == SENT
! (item == SENT)item != SENT! ( a b
REV00
Chapter 8: The if Statement
Syntax
8/13/2019 Programming Fundamental All Chapter
228/265
DDC1023 PROGRAMMING METHODOLOGY 228
if (condition) statement ;else statement ;
Ex-1.if (rest_heart_rate > 56 )
printf(keep up your exercise program! \ n); else
printf(Your heart rate is in excellenthealth\ n);
Ex-2.if (x != 0.0)
product = product * x;
REV00
Chapter 8: If Statement with Compound Statements
8/13/2019 Programming Fundamental All Chapter
229/265
DDC1023 PROGRAMMING METHODOLOGY 229
if (condition){
true task}
else{false task
}
REV00
Chapter 8: Decision Steps in Algorithms
Select from a choice of actions
8/13/2019 Programming Fundamental All Chapter
230/265
DDC1023 PROGRAMMING METHODOLOGY 230
Select from a choice of actionsRefer slide 240 and 241 for the algorithms in makingdecision
REV00
Chapter 8: Nested if Statements and MultipleAlternative Decisions
http://www.mywickedspace.com/graphics/glitter/Animals/bunny2.gif8/13/2019 Programming Fundamental All Chapter
231/265
DDC1023 PROGRAMMING METHODOLOGY 231
An if statement with another if statement as its true task orits false task
Dangling Elseif (x > 0)
if (y > 0)a = a + 1;
elseb = b + 1;
REV00
Chapter 8: Nested if Statements and MultipleAlternative Decisions
Nested if Example: Road Sign Decision Process
8/13/2019 Programming Fundamental All Chapter
232/265
DDC1023 PROGRAMMING METHODOLOGY 232
REV00
Chapter 8: Nested if Statements and MultipleAlternative Decisions
Road Sign Decision Process
8/13/2019 Programming Fundamental All Chapter
233/265
DDC1023 PROGRAMMING METHODOLOGY 233
REV00
Chapter 8: Nested if Statements and MultipleAlternative Decisions
Multiple-Alternative Decision
8/13/2019 Programming Fundamental All Chapter
234/265
DDC1023 PROGRAMMING METHODOLOGY 234
REV00
Chapter 8: Nested if Statements and MultipleAlternative Decisions Multiple-Alternative Decision Example
8/13/2019 Programming Fundamental All Chapter
235/265
DDC1023 PROGRAMMING METHODOLOGY 235
REV00
Chapter 8: The switch Statement
8/13/2019 Programming Fundamental All Chapter
236/265
DDC1023 PROGRAMMING METHODOLOGY 236
When the selection isbased on the value of asingle variable or of asimple expression
(called the controllingexpression).
REV00
Chapter 8: The switch StatementExample of a switch Statement
http://www.mywickedspace.com/graphics/glitter/Animals/hamster.gif8/13/2019 Programming Fundamental All Chapter
237/265
DDC1023 PROGRAMMING METHODOLOGY 237
http://www.mywickedspace.com/graphics/glitter/Animals/hamster.gif8/13/2019 Programming Fundamental All Chapter
238/265
REV00
Chapter 9: Repetition and Loop Statement in C
Objectives
8/13/2019 Programming Fundamental All Chapter
239/265
DDC1023 PROGRAMMING METHODOLOGY 239
Learn about the repetition in programsCount loops and the while statementCompute a sum or a product in a loopUnderstand the for and do-while statementLearn about the conditional loops: counter-controlled,sentinel-controlled and flag-controlledDesign the loop
http://www.mywickedspace.com/graphics/glitter/Animals/cat6.gif8/13/2019 Programming Fundamental All Chapter
240/265
REV00
Chapter 9: Counting Loops and the while Statement
Counter-controlled loop (or counting loop)
8/13/2019 Programming Fundamental All Chapter
241/265
DDC1023 PROGRAMMING METHODOLOGY 241
A loop whose required number of iterations canbe determined before loop execution begins.
The syntax
while (loop repetition condition)statement;
Loop repetition condition: the condition that controlsloop repetition.
Infinite loop: a loop that executes forever
REV00
Chapter 9: Counting Loops and the while Statement
count_emp = 0; /* no employees processed yetExample
8/13/2019 Programming Fundamental All Chapter
242/265
DDC1023 PROGRAMMING METHODOLOGY 242
*/while (count_emp < 7) { /* test value of
count_emp */printf("Hours> ");scanf("%d", &hours);printf("Rate> ");scanf("%lf", &rate);pay = hours * rate;printf("Pay is $%6.2f\n", pay);count_emp = count_emp + 1; /* increment
count_emp */
}printf("\nAll employees processed\n");
REV00
Chapter 9: Counting Loops and the while Statement
8/13/2019 Programming Fundamental All Chapter
243/265
DDC1023 PROGRAMMING METHODOLOGY 243
Flowchart for a while Loop
REV00
Chapter 9: Computing a Sum or a Product in a Loop
Loops often accumulate a sum or a product by
8/13/2019 Programming Fundamental All Chapter
244/265
DDC1023 PROGRAMMING METHODOLOGY 244
repeating an addition or multiplication operation.
Accumulator A variable used to store a value being computedin increments during the execution of a loop.
REV00
Chapter 9: Computing a Sum or a Product in a Loop
Example
8/13/2019 Programming Fundamental All Chapter
245/265
DDC1023 PROGRAMMING METHODOLOGY 245
REV00
Chapter 9: Computing a Sum or a Product in a Loop
Compound Assignment Operators
8/13/2019 Programming Fundamental All Chapter
246/265
DDC1023 PROGRAMMING METHODOLOGY 246
C provide special assignment operators variable op = expression;
REV00
Chapter 9: The for Statements
Three loop control components with the loop body.
8/13/2019 Programming Fundamental All Chapter
247/265
DDC1023 PROGRAMMING METHODOLOGY 247
Initialization of the loop control variable,Test of the loop repetition condition, andChange (update) of the loop control variable.
The for statement in C supplies a designed place foreach of these three components.
REV00
Chapter 9: The for Statements
8/13/2019 Programming Fundamental All Chapter
248/265
DDC1023 PROGRAMMING METHODOLOGY 248
REV00
Chapter 9: The for Statements
8/13/2019 Programming Fundamental All Chapter
249/265
DDC1023 PROGRAMMING METHODOLOGY 249
REV00
Chapter 9: The for Statements
8/13/2019 Programming Fundamental All Chapter
250/265
DDC1023 PROGRAMMING METHODOLOGY 250
Increment and Decrement OperatorsThe increment (i.e., ++) or decrement (i.e., --)operators are the frequently used operators which takeonly one operand.
for(int i=0; i0; i-- ) {}
Side effect: the value of its operand isincremented/decremented by one .
REV00
Chapter 9: The for Statements
Prefix and Postfix Increments
h l f h h h h
http://www.mywickedspace.com/graphics/glitter/Animals/bee2.gif8/13/2019 Programming Fundamental All Chapter
251/265
DDC1023 PROGRAMMING METHODOLOGY 251
The value of the expression in which the ++/-- operatoris used depends on the position of the operator .
REV00
Chapter 9: The for StatementsExample: Factorial Function
8/13/2019 Programming Fundamental All Chapter
252/265
DDC1023 PROGRAMMING METHODOLOGY 252
REV00
Chapter 9: The for Statements
Inc. and Dec. Other Than 1
8/13/2019 Programming Fundamental All Chapter
253/265
DDC1023 PROGRAMMING METHODOLOGY 253
REV00
Chapter 9: Conditional Loops: counter-controlled,sentinel-controlled and flag-controlled
I i i i ill b bl
8/13/2019 Programming Fundamental All Chapter
254/265
DDC1023 PROGRAMMING METHODOLOGY 254
In many programming situations, you will not be able todetermine the exact number of loop repetitions beforeloop execution begins.
REV00
8/13/2019 Programming Fundamental All Chapter
255/265
DDC1023 PROGRAMMING METHODOLOGY 255
REV00
8/13/2019 Programming Fundamental All Chapter
256/265
DDC1023 PROGRAMMING METHODOLOGY 256
REV00
Chapter 9: Loop Design
Problem-Solving Questions for Loop DesignWhat are the inputs?
8/13/2019 Programming Fundamental All Chapter
257/265
DDC1023 PROGRAMMING METHODOLOGY 257
What are the outputs?Is there any repetition?Do I know in advance how many time steps willbe repeated?How do I know how long to keep repeating thesteps?
Sentinel-Controlled Loops
Endfile-Controlled LoopsInfinite Loops on Faulty Data
REV00
Chapter 9: Loop Design
http://www.mywickedspace.com/graphics/glitter/Animals/carbear6.gif8/13/2019 Programming Fundamental All Chapter
258/265
DDC1023 PROGRAMMING METHODOLOGY 258
REV00
Chapter 9: Loop DesignSentinel-Controlled Loops
One way to do this is to instruct the user to enter a unique data value,called a sentinel value , after the last data item.
8/13/2019 Programming Fundamental All Chapter
259/265
DDC1023 PROGRAMMING METHODOLOGY 259
8/13/2019 Programming Fundamental All Chapter
260/265
REV00
Chapter 9: Loop DesignExample of Endfile-Controlled Loops
8/13/2019 Programming Fundamental All Chapter
261/265
DDC1023 PROGRAMMING METHODOLOGY 261
REV00
Chapter 9: Loop Design
Infinite Loops on Faulty Data 70 7
8/13/2019 Programming Fundamental All Chapter
262/265
DDC1023 PROGRAMMING METHODOLOGY 262
70 7oDetect faulty data
REV00
Chapter 9: Nested Loops
Consist of an outer loop with one or more inner loops.
8/13/2019 Programming Fundamental All Chapter
263/265
DDC1023 PROGRAMMING METHODOLOGY 263
REV00
Chapter 9: The do-while Statement
When we know that a loop must execute at least onetime
8/13/2019 Programming Fundamental All Chapter
264/265
DDC1023 PROGRAMMING METHODOLOGY 264
time.
REV00
Chapter 9: Summary
Repetition and Loop StatementsCounter Controller Loop
8/13/2019 Programming Fundamental All Chapter
265/265
Counter-Controller LoopSentinel-Controller LoopEndfile-Controller Loop
Input Validation LoopGeneral Conditional Loopwhile for and do-while