DDPC 1573PROGRAMMING FUNDAMENTAL
Main Reference Hanly and Koffman, Problem Solving and Program Design in C, Fifth Edition, Addison Wesley Reference Joyce Farrell Thomson, Programming Logic and Design, Fifth Edition
1
REV00
REV00
Chapter 1: Overview of Computers and Programming
Objectives
Understand computer components and operations Learn about the steps involved in the programming process Learn about the data hierarchy and file input Use flowchart symbols and pseudocode statements Use and name variables Use a sentinel, or dummy value, to end a program Manage large flowcharts Assign values to variables Recognize the proper format of assignment statements Describe data types Understand the evolution of programming techniques
DDC1023 PROGRAMMING METHODOLOGY
2
REV00
Chapter 1: Computer Components and Operations
2 major components of computer system: Hardware Software Hardware: equipment, or devices Software: programs that contain instructions for the computer 4 major operations in a computer: Input Processing Output Storage
DDC1023 PROGRAMMING METHODOLOGY
3
REV00
Chapter 1: Computer Components and Operations
Input devices: allow data to enter the computer Mouse, keyboard, scanner Processing: working on the data Organizing data Checking data for accuracy Mathematical or other manipulations on data Central Processing Unit (CPU): hardware that performs the tasks
DDC1023 PROGRAMMING METHODOLOGY
REV00
Chapter 1: Computer Components and Operations
Output devices: provide data to the user Printer, monitor, speakers Programming language: special language containing instructions for the computer Visual Basic, Java, C#, C++, COBOL Syntax: rules governing word usage and punctuation in the language
DDC1023 PROGRAMMING METHODOLOGY
REV00
Chapter 1: Computer Components and Operations
Machine language: controls the computers on/off circuitry Compiler or interpreter: software that translates programming languages to machine language Program must be free of syntax errors to be run, or executed, on a computer To function properly, the logic must be correct
DDC1023 PROGRAMMING METHODOLOGY
REV00
Chapter 1: Computer Components and Operations
What is wrong with this logic for making a cake? Stir Add two eggs Bake at 350 degrees for 45 minutes Add three cups of flour
DDC1023 PROGRAMMING METHODOLOGY
REV00
Chapter 1: Computer Components and Operations
Logic errors, or semantic errors, are more difficult to locate than syntax errors Logic for multiplying a number by 2 (includes input, processing, and output statements)
Get input number. Compute calculated answer as inputNumber times 2. Print calculatedAnswer.
DDC1023 PROGRAMMING METHODOLOGY
8
REV00
Chapter 1: Computer Components and Operations
2 storage categories: - internal - external
DDC1023 PROGRAMMING METHODOLOGY
REV00
Chapter 1: Computer Components and Operations
- Internal storage: Main memory, random access memory (RAM) Located inside the computer system Volatile: contents are lost when power goes down External storage: Persistent: contents are relatively permanent Floppy drive, hard drive, flash media, magnetic tape Located outside the computer system Non-volatile: contents remain eventhough power goes down
DDC1023 PROGRAMMING METHODOLOGY
10
REV00
Chapter 1: Steps Involved in the Programming Process
6 programming phases: Understand the problem Plan the logic Code the program Use software to translate the program to machine language Test the program Put the program into production
DDC1023 PROGRAMMING METHODOLOGY
11
REV00
Chapter 1: Steps Involved in the Programming Process
Understanding the Problem May be the most difficult phase Users may not be able to articulate their needs well User needs may be changing frequently Programmers may have to learn the users functional job tasks Failure to understand the problem is the major cause of most project failures
DDC1023 PROGRAMMING METHODOLOGY
12
REV00
Chapter 1: Steps Involved in the Programming Process
Planning the Logic Plan the steps that the program will take Use tools such as flowcharts and pseudocode Flowchart: a pictorial representation of the logic steps Pseudocode: Natural language representation of the logic Walk through the logic before coding by desk-checking the logic
DDC1023 PROGRAMMING METHODOLOGY
13
REV00
Chapter 1: Steps Involved in the Programming Process
Coding the Program Select the programming language Some languages more efficient for certain tasks All languages handle input, arithmetic processing, output, other standard functions Logic can be executed in any number of languages Write the instructions Planning generally more difficult than coding
DDC1023 PROGRAMMING METHODOLOGY
14
REV00
Chapter 1: Steps Involved in the Programming Process
Using Software to Translate the Program into Machine Language Programmers write instructions in high-level languages that resemble a natural language Compilers or interpreters change the programs into a low-level machine language that can be executed Syntax errors are identified by the compiler or interpreter
DDC1023 PROGRAMMING METHODOLOGY
15
REV00
Chapter 1: Steps Involved in the Programming Process
Using Software to Translate the Program into Machine Language
Creating an executable program
DDC1023 PROGRAMMING METHODOLOGY
16
REV00
Chapter 1: Steps Involved in the Programming Process
Testing the Program Execute it with sample data and check results Identify logic errors and correct them Choose test data carefully to exercise all branches of the logic
DDC1023 PROGRAMMING METHODOLOGY
17
REV00
Chapter 1: Steps Involved in the Programming Process
Putting the Program into Production Might mean simply running the program once Process might take months if program is used on regular basis or is part of larger development Train data-entry people and users Change existing data Conversion: entire set of actions organization must take to switch over to new program(s)
DDC1023 PROGRAMMING METHODOLOGY
18
REV00
Chapter 1: Steps Involved in the Programming Process
Software Development Method 1 Planning 4 Implementation
Writing the algorithm
2 Analysis 5 Testing Identify data objects Verify the program meets Goal to model properties requirements Determine Input / Output data System and Unit test Constraints on the problem 6 Maintaining 3 Design Maintain the system Decompose into smaller problems Top-down design (divide and conquer) Develop algorithm (Desk check)
DDC1023 PROGRAMMING METHODOLOGY
19
REV00
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 system Graphical User Interface (GUI): allows users to interact with a program in a graphical environment
DDC1023 PROGRAMMING METHODOLOGY
20
REV00
Chapter 1: Interactive Input
A prompt, response, and output in a command line environment
DDC1023 PROGRAMMING METHODOLOGY
21
REV00
Chapter 1: Interactive Input
A prompt, response, and output in a GUI environment
DDC1023 PROGRAMMING METHODOLOGY
22
REV00
Chapter 1: Data Hierarchy and File Input
Data hierarchy: ordering of data types by size Character: single symbol A, 7, $ Field: group of characters forming a single data item Smith Record: a group of related fields Customer record containing name and address fields
DDC1023 PROGRAMMING METHODOLOGY
23
REV00
Chapter 1: Data Hierarchy and File Input
File: a group of related records
Customer file, containing all customer records
Database: collection of related files, called tables, that serve the information needs of the organization
DDC1023 PROGRAMMING METHODOLOGY
24
REV00
Chapter 1: Data Hierarchy and File Input
The data hierarchy
DDC1023 PROGRAMMING METHODOLOGY
25
REV00
Chapter 1: Data Hierarchy and File Input
The EMPLOYEE file represented as a stack of index cards
DDC1023 PROGRAMMING METHODOLOGY
26
REV00
Chapter 1: Flowchart Symbols and Pseudocode Statements
Flowchart: pictorial representation of the logic Pseudocode: English-like representation of the logic Example: start
get inputNumber compute calculatedAnswer as inputNumber times 2 print calculatedAnswer
stop
DDC1023 PROGRAMMING METHODOLOGY
27
REV00
Chapter 1: Flowchart Symbols and Pseudocode Statements
Input symbol
Processing symbol
Output symbol
DDC1023 PROGRAMMING METHODOLOGY
28
REV00
Chapter 1: Flowchart Symbols and Pseudocode Statements
Flowlines: Connect the steps Show the sequence of statements Have arrows to show the direction Terminal symbol (start/stop symbol): Shows the start and end points of the statements Lozenge shape
DDC1023 PROGRAMMING METHODOLOGY
29
REV00
Chapter 1: Flowchart Symbols and Pseudocode Statements
Flowchart and pseudocode of program that doubles a number
DDC1023 PROGRAMMING METHODOLOGY
30
REV00
Chapter 1: Flowchart Symbols and Pseudocode Statements
Inefficient pseudocode for program that doubles 10,000 numbers
DDC1023 PROGRAMMING METHODOLOGY
31
REV00
Chapter 1: Flowchart Symbols and Pseudocode Statements
Flowchart of infinite number-doubling program
DDC1023 PROGRAMMING METHODOLOGY
32
REV00
Chapter 1: Name Variables, Assign Values to Variables
Variable: a memory location whose contents can vary; also called an identifier Each programming language has its own rules for naming identifiers, including: Legal characters Maximum length Use of upper- or lowercase Variable name must be a single word, but can be formed from several words rate, interestRate, interest_rate
DDC1023 PROGRAMMING METHODOLOGY
33
REV00
Chapter 1: Name Variables, Assign Values to Variables
Choose meaningful names for variables Improves the readability and maintainability of code
Suitability of suggested variable names for an employees last name
DDC1023 PROGRAMMING METHODOLOGY
34
REV00
Chapter 1: Ending a Program by Using Sentinel Values
Infinite loop: a sequence of statements that repeats forever with no escape Avoid infinite loops by testing for a predetermined value that means stop processing Decision: testing a value Flowchart decision symbol: a diamond shape with two flowlines, one for Yes and one for No
DDC1023 PROGRAMMING METHODOLOGY
35
REV00
Chapter 1: Sentinel, or Dummy Value to End A Program
Flowchart of number-doubling program with sentinel value of 0
DDC1023 PROGRAMMING METHODOLOGY
36
REV00
Chapter 1: Sentinel, or Dummy Value to End A Program
Sentinel value (or dummy value) Does not represent real data Signal to stop Can 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
DDC1023 PROGRAMMING METHODOLOGY
37
REV00
Chapter 1: Sentinel, or Dummy Value to End A Program
Flowchart using eof
DDC1023 PROGRAMMING METHODOLOGY
38
REV00
Chapter 1: Manage Large Flowcharts
Flowchart connector symbol: Marks a logic transfer to another location in the flowchart Transfer location can be on the same page or on another page On-page symbol: a circle with a number or letter to identify the matching transfer location Off-page symbol: a square with a pointed bottom, containing page number and a number of letter to identify the matching transfer location
DDC1023 PROGRAMMING METHODOLOGY
39
REV00
Chapter 1: Data Types, the Evolution of Programming Techniques
2 basic data types: Text Numeric Numeric data stored by numeric variables Text data stored by string, text, or character variables Constants: Values that do not change while the program is running Have identifiers, and can be used like variables for calculations, but cannot be assigned new values
DDC1023 PROGRAMMING METHODOLOGY
40
REV00
Chapter 1: Data Types, the Evolution of Programming Techniques
Some programming languages implement several numeric data types, such as: Integer: whole numbers only Floating-point: fractional numeric values with decimal points Character or string data is represented as characters enclosed in quotation marks x, color Data types must be used appropriately
DDC1023 PROGRAMMING METHODOLOGY
41
Chapter 1: Data Types, the Evolution of Programming Techniques
REV00
Some examples of legal and illegal assignments
DDC1023 PROGRAMMING METHODOLOGY
42
REV00
Chapter 1: Summary
4 major computer operations: Input Processing Output Storage 6 programming phases: Understand the problem Plan the logic Code the program Translate the program to machine language Test the program Deploy the program
DDC1023 PROGRAMMING METHODOLOGY
43
REV00
Chapter 1: Summary
Data hierarchy
Character Field Record File Database
Software Development Method
Planning Analysis Design Implementation Testing Maintaining
DDC1023 PROGRAMMING METHODOLOGY
44
REV00
Chapter 1: Summary
Flowchart: pictorial representation of program logic Variables: named memory locations that contain values Testing a value involves making a decision Assignment statements: store a value into a variable Assignment operator: the equal (=) sign in most languages 2 major data types: text numeric Procedural programming: focuses on actions performed on data Object-oriented programming: focuses on representing and manipulating objects
DDC1023 PROGRAMMING METHODOLOGY
45
REV00
Chapter 2: Understanding Structure Objectives
Learn about the features of unstructured spaghetti code Understand the three basic structures: sequence selection loop Use a priming read Appreciate the need for structure Recognize structure Learn about 3 special structures: case, do-while, and do-until
DDC1023 PROGRAMMING METHODOLOGY
46
REV00
Chapter 2: Features of Unstructured Spaghetti Code
Spaghetti code: logically snarled program statements Can be the result of poor program design Spaghetti code programs often work, but are difficult to read and maintain Convoluted logic usually requires more code
DDC1023 PROGRAMMING METHODOLOGY
47
REV00
Chapter 2: Features of Unstructured Spaghetti Code
Example: College Admissions Admit students who score >= 90 on admissions test if upper 75 percent of high-school graduating class Admit students who score >= 80 on test if upper 50 percent of high-school graduating class Admit students who score >= 70 on admission test if upper 25 percent of high-school graduating class
DDC1023 PROGRAMMING METHODOLOGY
48
REV00
Chapter 2: Features of Unstructured Spaghetti Code
DDC1023 PROGRAMMING METHODOLOGY
49
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
Structure: basic unit of programming logic Any program can be constructed from only 3 basic types of structures Sequence
Perform actions in order No branching or skipping any task
Selection (decision)
Ask a question, take one of 2 actions Dual-alternative or single-alternative
Loop
Repeat actions based on answer to a question
DDC1023 PROGRAMMING METHODOLOGY
50
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
Sequence structure
Sequence structure
DDC1023 PROGRAMMING METHODOLOGY
51
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
Selection structure
Selection structure
DDC1023 PROGRAMMING METHODOLOGY
52
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
Dual-alternative if: contains 2 alternatives
if someCondition is true then
do oneProcess else
do theOtherProcess
DDC1023 PROGRAMMING METHODOLOGY
53
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
Single-alternative if: contains 1 alternative
Single-alternative selection structure
DDC1023 PROGRAMMING METHODOLOGY
54
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
Single-alternative if
if employee belongs to dentalPlan then deduct $40 from employeeGrossPay Else clause is not required Null case: situation where nothing is done
DDC1023 PROGRAMMING METHODOLOGY
55
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
Loop structure Repeats a set of actions based on the answer to a question Also called repetition or iteration Question is asked first in the most common form of loop
Loop structure
DDC1023 PROGRAMMING METHODOLOGY
56
REV00
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
DDC1023 PROGRAMMING METHODOLOGY
57
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
All logic problems can be solved using only these 3 structures Structures can be combined in an infinite number of ways Stacking: attaching structures end-to-end End-structure statements: indicate the end of a structure The endif statement ends an if-then-else structure The endwhile ends a loop structure
DDC1023 PROGRAMMING METHODOLOGY
58
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
Structured flowchart and pseudocode
DDC1023 PROGRAMMING METHODOLOGY
59
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
Any individual task or step in a structure can be replaced by a structure Nesting: placing one structure within another Indent the nested structures statements Block: group of statements that execute as a single unit
DDC1023 PROGRAMMING METHODOLOGY
60
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
Flowchart and pseudocode showing a sequence nested within a selection
DDC1023 PROGRAMMING METHODOLOGY
61
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
Selection in a sequence within a selection
DDC1023 PROGRAMMING METHODOLOGY
62
REV00
Flowchart and pseudocode for loop within selection within sequence within selection
DDC1023 PROGRAMMING METHODOLOGY
63
REV00
Chapter 2: Three Basic Structures: Sequence, Selection and Loop
Each structure has 1 entry and 1 exit point Structures attach to others only at entry or exit points
The 3 structures
DDC1023 PROGRAMMING METHODOLOGY
64
REV00
Chapter 2: Reasons for Structure
Provides clarity Professionalism Efficiency Ease of maintenance Supports modularity
DDC1023 PROGRAMMING METHODOLOGY
65
REV00
Chapter 2: Reasons for Structure
Any set of instructions can be expressed in structured format Any task to which you can apply rules can be expressed logically using sequence, selection, loop It can be difficult to detect whether a flowchart is structured
DDC1023 PROGRAMMING METHODOLOGY
66
REV00
Chapter 2: Recognize Structure
Is this flowchart structured?
DDC1023 PROGRAMMING METHODOLOGY
67
REV00
Chapter 2: Recognize Structure
Is this flowchart structured?
Example 1
DDC1023 PROGRAMMING METHODOLOGY
68
REV00
Chapter 2: Recognize Structure
Single process like A is part of an unacceptable structure
At least the beginning of a sequence structure
Untangling Example 1, 1st step
DDC1023 PROGRAMMING METHODOLOGY
69
REV00
Chapter 2: Recognize Structure
B begins a selection structure Sequences never have decisions in them Logic never returns to B
Untangling Example 1, 2nd step
DDC1023 PROGRAMMING METHODOLOGY
70
REV00
Chapter 2: Recognize Structure
Pull up on the flowline from the left side of B
Untangling Example 1, 3rd step
DDC1023 PROGRAMMING METHODOLOGY
71
REV00
Chapter 2: Recognize Structure
Next, pull up the flowline on the right side of B
Untangling Example 1, 4th step
DDC1023 PROGRAMMING METHODOLOGY
72
REV00
Chapter 2: Recognize Structure
Pull up the flowline on the left side of D and untangle it from the B selection by repeating C
Untangling Example 1, 5th step
DDC1023 PROGRAMMING METHODOLOGY
73
REV00
Chapter 2: Recognize Structure
Now pull up the flowline on the right side of D
Untangling Example 1, 6th step
DDC1023 PROGRAMMING METHODOLOGY
74
REV00
Chapter 2: Recognize Structure
Bring together the loose ends of D and of B
Finished flowchart and pseudocode for untangling Example 1
DDC1023 PROGRAMMING METHODOLOGY
75
REV00
Chapter 2: Three Special Structures: case, do-while, and do-until
Many languages allow 3 additional structures: The case structure The do-while structure The do-until structure
CASE Structure: Decisions with more than 2 alternatives Tests a variable against a series of values and takes action based on a match Nested if-then-else statements will do what a case structure does
DDC1023 PROGRAMMING METHODOLOGY
76
Chapter 2: Three Special Structures: case, do-while, and do-until
Using nested if-then-else for multiple alternatives
REV00
Flowchart and pseudocode of tuition decisions
DDC1023 PROGRAMMING METHODOLOGY
77
REV00
Chapter 2: Three Special Structures: case, do-while, and do-until
Using a case structure for multiple alternatives
Flowchart and pseudocode of case structure
DDC1023 PROGRAMMING METHODOLOGY
78
REV00
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 structure Loop statements always used at least once
The while loop, which is a pretest loop
Structure of a do-while or dountil loop, which are posttest loops
79
DDC1023 PROGRAMMING METHODOLOGY
REV00
Chapter 2: Three Special Structures: case, do-while, and do-until
do-while: executes as long as the questions answer is Yes or True do-until: executes as long as the questions answer is No or False do wash a dish until all dishes are washed do wash a dish while more dishes remain to be washed
DDC1023 PROGRAMMING METHODOLOGY
80
REV00
Chapter 2: Three Special Structures: case, do-while, and do-until
while loop with question at beginning is called a pretest loop do-while and do-until with question at end are called posttest loops Posttest loop can be replaced with a sequence followed by a pretest while loop pay a bill while there are more bills to pay pay a bill endwhile
DDC1023 PROGRAMMING METHODOLOGY
81
REV00
Chapter 2: Three Special Structures: case, do-while, and do-until
Flowchart and pseudocode for do-while loop
DDC1023 PROGRAMMING METHODOLOGY
82
REV00
Chapter 2: Three Special Structures: case, do-while, and do-until
Flowchart and pseudocode for sequence followed by while loop
DDC1023 PROGRAMMING METHODOLOGY
83
REV00
Chapter 2: Three Special Structures: case, do-while, and do-until
How can this design be made structured?
Unstructured loop
DDC1023 PROGRAMMING METHODOLOGY
84
REV00
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
DDC1023 PROGRAMMING METHODOLOGY
85
REV00
Chapter 2: Summary
Spaghetti code: snarled program logic 3 basic structures: sequence, selection, loop Combined by stacking and nesting Structured techniques promote clarity, professionalism, efficiency, and modularity
Flowchart can be made structured by untangling
DDC1023 PROGRAMMING METHODOLOGY
86
REV00
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 ask the question last do-while and do-until loop statements are always executed at least once Posttest loop can be replaced by a sequence followed by a while loop
DDC1023 PROGRAMMING METHODOLOGY
87
REV00
Chapter 3: The Program Planning Process: Documentation and Design
Objectives Learn about documentation Learn about the advantages of modularization Learn how to modularize a program Declare local and global variables and constants Understand the mainline logic for many procedural programs Create hierarchy charts
DDC1023 PROGRAMMING METHODOLOGY
88
REV00
Chapter 3: Learn About Documentation
Documentation All supporting material that goes with a program Two major categories: for users and for programmers Usually created by system analysts and/or tech writers May be printed or electronic (Web or CD) End users: people who use computer programs Program Documentation Internal program documentation: comments within code External program documentation: supporting paperwork written before programming begins
DDC1023 PROGRAMMING METHODOLOGY
89
REV00
Chapter 3: Learn About Documentation
Output Documentation Describes the results the user can see when a program is complete Usually written first Planning done in consultation with the end user After desired output is known, programmer can plan processes needed to produce output Most common types of output: Printed reports Screen output
DDC1023 PROGRAMMING METHODOLOGY
90
REV00
Chapter 3: Learn About Documentation
Designing Printed Reports Printed reports: designed using a print chart Created using word-processor or design software Printed reports may contain: Detail lines: display data details Heading lines: contain title and column headings Total (or summary) lines: contain statistics or end of report indicators Printed reports may contain only summary information
DDC1023 PROGRAMMING METHODOLOGY
91
REV00
Chapter 3: Learn About Documentation
Designing Screen Output Program output may appear on a monitor screen In a GUI, user sees a screen and can interact with a mouse or pointing device Output design resembles a sketch of a screen GUI designed to allow user to scroll through records
DDC1023 PROGRAMMING METHODOLOGY
92
REV00
Chapter 3: Learn About Documentation
Designing Screen Output
Inventory records displayed in a GUI environment
Inventory records displayed in a running program
DDC1023 PROGRAMMING METHODOLOGY
93
REV00
Chapter 3: Learn About Documentation
Input Documentation Describes what input is available to produce the output File description: Describes data stored in a file Indicates fields, data types, and lengths
Inventory file description
DDC1023 PROGRAMMING METHODOLOGY
94
REV00
Chapter 3: Learn About Documentation
Input Documentation Input files organized in different ways Field may occupy exactly 15 characters for each record Adding characters to the end of a data field to force it to a specified size is padding the field Some names might be truncated or abbreviated Fields may be delimited Delimiter: character that separates fields Numeric fields may occupy a specified number of bytes
DDC1023 PROGRAMMING METHODOLOGY
95
REV00
Chapter 3: Learn About Documentation
Completing the Documentation Program documentation may contain: Output design Input description Flowcharts Pseudocode Program code listing User documentation may contain: Manuals Instructional material Operating instructions
DDC1023 PROGRAMMING METHODOLOGY
96
REV00
Chapter 3: Learn About Documentation
Completing the Documentation User documentation: Written clearly in plain language Usually prepared by system analysts and/or tech writers User documentation usually indicates: How to prepare input Output distribution and interpretation Error message information Run frequency
DDC1023 PROGRAMMING METHODOLOGY
97
REV00
Chapter 3: The Advantages of Modularization
Module: Unit of code that performs one small task Called a subroutine, procedure, function, or method Invoke (call) a method is to execute it Calling method invokes the called method Program contains unlimited number of methods Each method can be called unlimited number of times
DDC1023 PROGRAMMING METHODOLOGY
98
REV00
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 reuse Makes identifying structures easier
DDC1023 PROGRAMMING METHODOLOGY
99
REV00
Chapter 3: The Advantages of Modularization
Modularization Provides Abstraction Focuses on important properties while ignoring nonessential details Avoids low-level details Makes complex tasks look simple High-level programming languages allow English-like vocabulary One statement corresponds to dozens of machine instructions Modules provide another way to achieve abstraction
DDC1023 PROGRAMMING METHODOLOGY
100
REV00
Chapter 3: The Advantages of Modularization
Modularization Provides Abstraction
To-do list with abstraction Do laundry Call Aunt Nan Start term paper To-do list without abstraction Pick up laundry basket Put laundry basket in car Drive to laundromat Get out of car with basket Walk into laundromat Set basket down . . .
101
DDC1023 PROGRAMMING METHODOLOGY
REV00
Chapter 3: The Advantages of Modularization
Modularization Allows Multiple Programmers to Work on a Problem Commercial programs rarely written by a single programmer Development time is significantly reduced Large programming projects can be divided into modules Modules can be written by different programmers or programming teams
DDC1023 PROGRAMMING METHODOLOGY
102
REV00
Chapter 3: The Advantages of Modularization
Modularization Allows You to Reuse Your Work Subroutines that are useful should be used more than once in a program Example: routine that checks the current date Instructions placed in their own module are easy to port to other applications Reusability: the ability to use modules in a variety of applications Reliability: assurance that a module has been tested and proven to function correctly Reliable software saves times and money
DDC1023 PROGRAMMING METHODOLOGY
103
REV00
Chapter 3: How to Modularize A Program
Most programs contain a main program Contains the mainline logic Accesses other modules or subroutines Rules for naming modules different for every programming language For this text: Must be one word Should be meaningful Followed by a set of parentheses Corresponds to module naming in Java, C++, C#
DDC1023 PROGRAMMING METHODOLOGY
104
REV00
Chapter 3: How to Modularize A Program
Suggested identifiers for a module that calculates an employees gross pay
DDC1023 PROGRAMMING METHODOLOGY
105
REV00
Chapter 3: How to Modularize A Program
Calling program (or calling module): one that uses another module Flowchart symbol for calling a module: rectangle with bar across the top Flowchart for the module Start symbol: contains module name Stop symbol: contains exit or return
When a module is called, logic transfers to the model When module ends, logic transfers back to the caller
DDC1023 PROGRAMMING METHODOLOGY
106
REV00
Chapter 3: How to Modularize A Program
Sample logic
Logic from left figure using a method
107
DDC1023 PROGRAMMING METHODOLOGY
REV00
Chapter 3: How to Modularize A Program
Logic using two methods
DDC1023 PROGRAMMING METHODOLOGY
108
REV00
Chapter 3: How to Modularize A Program
Method is encapsulated in another method if it is contained in another method Knowing when to break a module into its own subroutines or submodules is an art Best practice: place together statements that contribute to one specific task Functional cohesion: extent to which the statements contribute to the same task
DDC1023 PROGRAMMING METHODOLOGY
109
REV00
Chapter 3: Declare Local and Global Variables and Constants
Arguments: data items required by a method Returning a value: data sent back by a method Method must include: Header: includes method identifier, other identifying information Body: contains all statements in the method Return statement: marks the end of the method Returns control to the calling method Data items are visible only within the method in which they are declared
DDC1023 PROGRAMMING METHODOLOGY
110
REV00
Chapter 3: Declare Local and Global Variables and Constants
Program that prints a bill using main program that calls nameAndAddress() method
DDC1023 PROGRAMMING METHODOLOGY
111
REV00
Chapter 3: Declare Local and Global Variables and Constants
Variables and constants are in scope only within method in which they are declared Variables and constants are local to the method Global variables and constants are known to the entire program Variables and constants declared outside any method are declared at the program level Reasons to declare variables globally: Needed in many methods throughout a program Declare classs data fields at class level
DDC1023 PROGRAMMING METHODOLOGY
112
REV00
Chapter 3: Declare Local and Global Variables and Constants
Declaring global variables and constants: violates encapsulation Declaring variables and constants within methods: methods are portable When two or more methods require access to same data, pass the data between methods
DDC1023 PROGRAMMING METHODOLOGY
113
REV00
Chapter 3: Declare Local and Global Variables and Constants
Program that prints a bill with some constants declared globally
DDC1023 PROGRAMMING METHODOLOGY
114
REV00
Chapter 3: Mainline Logic for Many Procedural Programs
Mainline logic of most procedural programs follows same general structure: Housekeeping tasks Variable and constant declarations Opening files Main loop tasks Processes that must occur for every data record End-of-job tasks Print footer lines Close open files
DDC1023 PROGRAMMING METHODOLOGY
115
REV00
Chapter 3: Mainline Logic for Many Procedural Programs
Flowchart and pseudocode of mainline logic for a typical procedural program
DDC1023 PROGRAMMING METHODOLOGY
116
REV00
Chapter 3: Mainline Logic for Many Procedural Programs
Sample payroll report
DDC1023 PROGRAMMING METHODOLOGY
117
REV00
Chapter 3: Mainline Logic for Many Procedural Programs
Logic for payroll report
DDC1023 PROGRAMMING METHODOLOGY
118
REV00
Chapter 3: Create Hierarchy Charts
Hierarchy chart: Illustrates modules relationships Tells which routines call which other routines Does not tell when or why the modules are called
Hierarchy chart program
DDC1023 PROGRAMMING METHODOLOGY
119
REV00
Chapter 3: Create Hierarchy Charts
An organizational hierarchy chart
DDC1023 PROGRAMMING METHODOLOGY
120
REV00
Chapter 3: Create Hierarchy Charts
Billing program hierarchy chart
DDC1023 PROGRAMMING METHODOLOGY
121
REV00
Chapter 3: Summary
Documentation: all supporting material for a program Output documentation: includes report designs File description: details data types and lengths of each field of data in the file User documentation: manuals and instructional materials, and operating instructions Modules: smaller, reasonable units of code that provide reusability Subroutines, procedures, functions, methods Modularization: Provides abstraction Allows multiple programmers to work on a problem Makes it easy to reuse work and identify structures
DDC1023 PROGRAMMING METHODOLOGY
122
REV00
Chapter 3: Summary
Modules can call other modules Flowchart symbol is a rectangle with a bar across the top Variable declarations define the name and type of the data to be stored Hierarchy chart illustrates modules relationships Common structure for procedural programs: Housekeeping tasks Main loop End-of-job tasks Hierarchy chart illustrates modules relationships
DDC1023 PROGRAMMING METHODOLOGY
123
REV00
Chapter 4: Making Decision Objectives
Evaluate Boolean expressions to make comparisons Use the relational comparison operators Learn about AND logic Learn about OR logic Make selections within ranges Learn about precedence when combining AND and OR selections Learn more about the case structure Use a decision table
DDC1023 PROGRAMMING METHODOLOGY
124
REV00
Chapter 4: Evaluating Boolean Expressions to Make Comparisons
Dual-alternative (or binary) selection structure: Provides an action for each of 2 possible outcomes
The dual-alternative selection structure
DDC1023 PROGRAMMING METHODOLOGY
125
REV00
Chapter 4: Evaluating Boolean Expressions to Make Comparisons
Single-alternative (or unary) selection structure Action is provided for only 1 outcome
The single-alternative selection structure
DDC1023 PROGRAMMING METHODOLOGY
126
REV00
Chapter 4: Evaluating Boolean Expressions to Make Comparisons
Flowchart and pseudocode for overtime payroll program
DDC1023 PROGRAMMING METHODOLOGY
127
REV00
Chapter 4: Evaluating Boolean Expressions to Make Comparisons
Pseudocode for payroll program with dental insurance determination
DDC1023 PROGRAMMING METHODOLOGY
128
REV00
Chapter 4: Evaluating Boolean Expressions to Make Comparisons
Boolean expression Represents only one of 2 states Evaluates to true or false Every decision in a computer program involves evaluating a Boolean expression Computer circuitry consists of two-state on-off switches Represented by 1 or 0 Every computer decision yields a true-false result
DDC1023 PROGRAMMING METHODOLOGY
129
REV00
Chapter 4: Relational Comparison Operators
For any 2 values, 3 types of comparisons: 2 values are equal 1st value greater than the 2nd value 1st value less than the 2nd value Relational comparison operators Express Boolean tests Different languages use different symbols
DDC1023 PROGRAMMING METHODOLOGY
130
REV00
Chapter 4: Relational Comparison Operators
Any logical situation can be expressed with only 3 types of comparisons: =, >, and < Operators >= and <= are not necessary, but make code more readable
Not equal operator Most confusing of comparisons Most likely to be different in different languages
DDC1023 PROGRAMMING METHODOLOGY
131
REV00
Chapter 4: Relational Comparison Operators
Using a negative comparison
DDC1023 PROGRAMMING METHODOLOGY
132
REV00
Chapter 4: Relational Comparison Operators
Using the positive equivalent of the negative comparison in Figure 4-5
DDC1023 PROGRAMMING METHODOLOGY
133
REV00
Chapter 4: Relational Comparison Operators
Relational comparisons
DDC1023 PROGRAMMING METHODOLOGY
134
REV00
Chapter 4: AND Logic OR Logic
Understanding AND Logic Compound condition Asks multiple questions before an outcome is determined AND decision
Requires that both of 2 tests evaluate to True Requires a nested decision (nested if) Using nested if statements Second selection structure is contained entirely within 1 side of 1st structure else clause paired with last if
DDC1023 PROGRAMMING METHODOLOGY
135
REV00
Chapter 4: AND Logic OR Logic
Understanding AND Logic
Flowchart and pseudocode for selection process in revised bonus-determining program
DDC1023 PROGRAMMING METHODOLOGY
136
REV00
Chapter 4: AND Logic OR Logic
Nesting AND Decisions for Efficiency When nesting decisions, either selection can come first Performance time can be improved by asking questions in the proper order In an AND decision, first ask the question that is less likely to be true Eliminates as many instances of the 2nd decision as possible Speeds up processing time
DDC1023 PROGRAMMING METHODOLOGY
137
REV00
Chapter 4: AND Logic OR Logic
Understanding OR Logic
When you want to take action when 1 or the other of 2 conditions is true
Example: Salespeople get bonus when they have achieved one of two goals: Sell at least five items Sell at least $2,000 in merchandise itemsSold >= ITEMS_MIN? If true, assign $300 bonus
DDC1023 PROGRAMMING METHODOLOGY
138
REV00
Chapter 4: AND Logic OR Logic
Writing OR Decisions for Efficiency May ask either question first Both produce the same output, but vary widely in number 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 true Eliminates as many repetitions as possible of second decision
DDC1023 PROGRAMMING METHODOLOGY
139
REV00
Chapter 4: Precedence When Combining AND and OR Selections
Combining Decisions in an AND Selection Conditional AND operator allows you to ask 2 or more questions in a single comparison Each Boolean expression must be true for entire expression to evaluate to true Truth tables describe the truth of an entire expression based on the truth of its parts Short-circuit evaluation: expression evaluated only as far as necessary to determine truth
DDC1023 PROGRAMMING METHODOLOGY
140
REV00
Chapter 4: Precedence When Combining AND and OR Selections
Combining Decisions in an OR Selection Conditional OR operator allows you to ask 2 or more questions in a single comparison Only one Boolean expression in an OR selection must be true to produce a result of true Question placed first will be asked first, so consider efficiency Computer can ask only one question at a time
DDC1023 PROGRAMMING METHODOLOGY
141
REV00
Chapter 4: Precedence When Combining AND and OR Selections
Combining Decisions in an AND Selection
Truth table for the AND operator
DDC1023 PROGRAMMING METHODOLOGY
142
REV00
Chapter 4: Precedence When Combining AND and OR Selections
Combining Decisions in an OR Selection
Truth table for the OR operator
DDC1023 PROGRAMMING METHODOLOGY
143
REV00
Chapter 4: Precedence When Combining AND and OR Selections
Combining Decisions in an AND Selection
Using an AND operator and the logic behind it
DDC1023 PROGRAMMING METHODOLOGY
144
REV00
Chapter 4: Precedence When Combining AND and OR Selections
Combining Decisions in an OR Selection
Using an OR operator and the logic behind it
DDC1023 PROGRAMMING METHODOLOGY
145
REV00
Chapter 4: Case Structure
Provides a series of alternatives based on the value of a single variable
Replaces a series of chained if-else statements Makes code easier to read
DDC1023 PROGRAMMING METHODOLOGY
146
REV00
Chapter 4: Case Structure
Flowchart and pseudocode that determines base price for house based on model number using the case structure
DDC1023 PROGRAMMING METHODOLOGY
147
REV00
Chapter 4: Decision Table
Managing multiple possible outcomes of multiple decisions can be difficult Decision table: four-part problem-analysis tool Conditions Possible combinations of Boolean values for each condition Possible actions based on the conditions Specific actions that correspond to each Boolean value of each condition
DDC1023 PROGRAMMING METHODOLOGY
148
REV00
Chapter 4: Decision Table
Sample residence hall assignments report
DDC1023 PROGRAMMING METHODOLOGY
149
REV00
Chapter 4: Decision Table
Rules for assigning residence halls Students under age 21 who request a hall with quiet study hours: Addams Hall Students under age 21 who do not request a hall with quiet study hours: Grant Hall Students age 21 and over who request a hall with quiet study hours: Lincoln Hall Students age 21 and over who do not request a hall with quiet study hours: Lincoln Hall
DDC1023 PROGRAMMING METHODOLOGY
150
REV00
Chapter 4: Decision Table
To create a decision table: List all possible conditions Determine the possible Boolean value combinations for each condition # combinations = 2 (number of conditions)
Conditions and possible values for residence hall determination
DDC1023 PROGRAMMING METHODOLOGY
151
REV00
Chapter 4: Decision Table
To create a decision table: Add rows to list possible outcome actions Choose one required outcome for each combination
Completed decision table for residence hall selection
DDC1023 PROGRAMMING METHODOLOGY
152
REV00
Chapter 4: Decision Table
Program that assigns a student to a residence hall
DDC1023 PROGRAMMING METHODOLOGY
153
REV00
Chapter 5: Looping Objectives
Learn about the advantages of looping Control loops with counters and sentinel values Nest loops Use posttest loops Recognize the characteristics shared by all loops Learn about common loop applications
DDC1023 PROGRAMMING METHODOLOGY
154
REV00
Chapter 5: Advantages of Looping
Looping makes computer programming efficient and worthwhile Write one set of instructions to operate on multiple, separate sets of data Loop: structure that repeats actions while some condition continues
DDC1023 PROGRAMMING METHODOLOGY
155
REV00
Chapter 5: Advantages of Looping
The while loop
DDC1023 PROGRAMMING METHODOLOGY
156
REV00
Chapter 5: Control Loops with Counters and Sentinel Values
As long as a Boolean expression remains true, while loops body executes Must control number of repetitions to avoid an infinite loop Repetitions controlled by Counter Sentinel value
DDC1023 PROGRAMMING METHODOLOGY
157
REV00
Chapter 5: Control Loops with Counters and Sentinel Values
Using a Definite while Loop with a Counter Three actions make a while loop end correctly: Loop control variable is initialized Prior to entering the loop Loop control variable is tested If result is true, loop body entered Loop control variable must be altered in loop body while expression eventually evaluates to false
Loop control variables altered by: Incrementing Decrementing
DDC1023 PROGRAMMING METHODOLOGY
158
REV00
Chapter 5: Control Loops with Counters and Sentinel Values
Using a Definite while Loop with a Counter
A while loop that prints Hello four times
DDC1023 PROGRAMMING METHODOLOGY
159
REV00
Chapter 5: Control Loops with Counters and Sentinel Values
Using a Definite while Loop with a Counter
Definite loop: number of iterations predetermined Also called counted loop Counter: numeric variable used to count number of times an event occurs Loop control variable may be altered by user input Indefinite loop: loop iterates until some condition is true Number of iterations may vary
DDC1023 PROGRAMMING METHODOLOGY
160
REV00
Chapter 5: Control Loops with Counters and Sentinel Values
Using an Indefinite while Loop with a Sentinel Value
Indefinite loop: loop performed a different number of times each time the program executes 3 crucial steps: Starting value to control the loop must be provided Comparison must be made using the value that controls the loop Within the loop, value that controls the loop must be altered Loop control variable: any variable that determines whether the loop will continue
DDC1023 PROGRAMMING METHODOLOGY
161
REV00
Looping bank balance program
DDC1023 PROGRAMMING METHODOLOGY
162
REV00
Chapter 5: Control Loops with Counters and Sentinel Values
Using an Indefinite while Loop with a Sentinel Value
Typical execution of the looping bank balance program
DDC1023 PROGRAMMING METHODOLOGY
163
REV00
Chapter 5: Control Loops with Counters and Sentinel Values
Using an Indefinite while Loop with a Sentinel Value
Crucial steps that must occur in every loop
DDC1023 PROGRAMMING METHODOLOGY
164
REV00
Chapter 5: Nested Loops
Nested loops: loops within loops Outer loop: loop that contains the other loop Inner loop: loop that is contained Needed when values of two (or more) variables repeat to produce every combination of values
DDC1023 PROGRAMMING METHODOLOGY
165
REV00
Flowchart and pseudocode for AnswerSheet program
DDC1023 PROGRAMMING METHODOLOGY
166
REV00
Chapter 5: Posttest Loops
Loop body may never execute in while loop and for loop Use posttest loop when loop body must execute at least once do-until loop do-while loop do-until loop executes until condition is true do-while loop executes until condition is false
DDC1023 PROGRAMMING METHODOLOGY
167
REV00
Chapter 5: Posttest Loops
Inner loop from label production program in Figure 5-9
DDC1023 PROGRAMMING METHODOLOGY
168
REV00
Chapter 5: Posttest Loops
Label production program using a do-until loop
DDC1023 PROGRAMMING METHODOLOGY
169
REV00
Chapter 5: The Characteristics Shared by All Loops
Every logical problem could be solved using only the while loop Other forms are conveniences while loop Loop-controlling question placed at beginning of steps that repeat do-until loop Loop-controlling question placed at end of steps that repeat
DDC1023 PROGRAMMING METHODOLOGY
170
REV00
Chapter 5: The Characteristics Shared by All Loops
Characteristics of all structured loops: Loop-controlling question must provide entry or exit from repeating structure Loop-controlling question provides the only entry to or exit from the repeating structure Exactly one loop-controlling value Provides only entry to or exit from the loop
DDC1023 PROGRAMMING METHODOLOGY
171
REV00
Chapter 5: The Characteristics Shared by All Loops
Examples of unstructured loops
DDC1023 PROGRAMMING METHODOLOGY
172
REV00
Chapter 5: Common Loop Applications
Using a loop to accumulate totals Examples: Business reports often include totals Telephone bill provides a total List of real estate sold and total value Accumulator: variable that gathers values Similar to a counter Counter increments by one Accumulator increments by some value
DDC1023 PROGRAMMING METHODOLOGY
173
REV00
Chapter 5: Common Loop Applications
Accumulate total real estate prices Declare numeric variable at beginning Initialize the accumulator to 0 Read each transactions data record Add its value to accumulator variable Read the next record until eof Variables exist only for the life of the application Run the application a second time, variables occupy different memory location
DDC1023 PROGRAMMING METHODOLOGY
174
REV00
Chapter 5: Common Loop Applications
Month-end real estate sales report
DDC1023 PROGRAMMING METHODOLOGY
175
REV00
Flowchart and pseudocode for real estate sales report program
DDC1023 PROGRAMMING METHODOLOGY
176
REV00
Chapter 5: Common Loop Applications
Using a loop to validate data When prompting a user for data, no guarantee that data is valid Validate data: make sure data falls in acceptable ranges Example: user enters birth month If number less than 1 or greater than 12 Display error message and stop the program Assign default value for the month Reprompt the user for valid input
DDC1023 PROGRAMMING METHODOLOGY
177
REV00
Chapter 5: Common Loop Applications
Reprompting a user once after an invalid month is entered
DDC1023 PROGRAMMING METHODOLOGY
178
REV00
Chapter 5: Common Loop Applications
Reprompting a user continuously after an invalid month is entered
DDC1023 PROGRAMMING METHODOLOGY
179
REV00
Chapter 5: Summary
When using a loop, write one set of instructions that operates on multiple, separate data Three 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 loops Nested loops maintain two individual loop control variables Alter each at the appropriate time
DDC1023 PROGRAMMING METHODOLOGY
180
REV00
Chapter 5: Summary
Use posttest loop when loop body must execute at least one time Control variable evaluated after loop body executes Characteristics of all structured loops: Loop-controlling question provides entry or exit from repeating structure Loop-controlling question provides the only entry or exit from repeating structure Accumulator: variable that gathers values Loops used to ensure user data is valid by reprompting the user
DDC1023 PROGRAMMING METHODOLOGY
181
REV00
Chapter 6: Overview of C 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 operators Learn about the general form of a C program Apply the formatting numbers in program output Know the interactive mode Identify the common programming errors
DDC1023 PROGRAMMING METHODOLOGY
182
REV00
Chapter 6: C Language Elements
Preprocessor directives
Main function
DDC1023 PROGRAMMING METHODOLOGY
183
REV00
Chapter 6: Variable Declarations and Data Types
Variables: values stored in variables can changes Variables Declarations: What kind of information will be stored in each variable How that information will be represented in memory
DDC1023 PROGRAMMING METHODOLOGY
184
REV00
Chapter 6: Variable Declarations and Data Types
Variable declaration according to its data type. EXAMPLES: int count,large; double x, y, z; char first_initial; char ans;
DDC1023 PROGRAMMING METHODOLOGY
185
REV00
Chapter 6: Executable Statements
Program in Memory Assignment Statements Input/Output Operations and Functions
DDC1023 PROGRAMMING METHODOLOGY
186
REV00
Chapter 6: Executable Statements
Program in Memory
Memory(a) Before and (b) After Execution of a Program
DDC1023 PROGRAMMING METHODOLOGY
187
REV00
Chapter 6: Executable Statements
Assignment Statements
kms = KMS_PER_MILE * miles;
DDC1023 PROGRAMMING METHODOLOGY
188
REV00
Chapter 6: Executable Statements
Before and After Assignment of a variable
sum = sum + item;
DDC1023 PROGRAMMING METHODOLOGY
189
REV00
Chapter 6: Executable Statements
Input and Output Operations and Functions Operations Functions #include <stdio.h> C function: printf C function: scanf
DDC1023 PROGRAMMING METHODOLOGY
190
REV00
Chapter 6: Executable Statements
Function (printf)
DDC1023 PROGRAMMING METHODOLOGY
191
REV00
Chapter 6: Executable Statements
Function (scanf)
scanf("%lf", &miles);
DDC1023 PROGRAMMING METHODOLOGY
192
REV00
Chapter 6: Executable Statements
Function (scanf) scanf("%c%c%c", &letter_1, &letter_2, &letter_3 );
DDC1023 PROGRAMMING METHODOLOGY
193
REV00
Chapter 6: General Form of a C program
Preprocessor directives: #include, #define Any used variable should be declared before the usage.
DDC1023 PROGRAMMING METHODOLOGY
194
REV00
Chapter 6: Formatting numbers in program output
All numbers are displayed in their default format, unless the program specifies otherwise.
Value Format Display Value Format Display
234
234 234 234
%4d
%5d %6d %1d
#234
##234 ###234 234
-234
-234 -234 -234
%4d
%5d %6d %2d
-234
#-234 ##-234 -234
DDC1023 PROGRAMMING METHODOLOGY
195
REV00
Chapter 6: Formatting numbers in program output
Value Format Display #3.14 3.14 3.142 0.12 Value 3.14159 3.14159 3.14159 -.006 Format Display %4.2f %5.1f %8.5f %4.2f 3.14 ##3.1 #3.14159 -0.01 3.14159 %5.2f 3.14159 %3.2f 3.14159 %5.3f .1234 %4.2f
-.006
-.006
%8.3f
%.3f
##-0.006 -.006
-0.006
%8.5f
-0.00600
-3.1416
-3.14159 %.4f
DDC1023 PROGRAMMING METHODOLOGY
196
REV00
Chapter 6: Formatting numbers in program output
DDC1023 PROGRAMMING METHODOLOGY
197
REV00
Chapter 6: Interactive mode
A mode of program execution in which the user responds to prompts by entering (typing in) data. scanf(%lf, &x); printf(Your mark is: %.2f, x); If user entered 85.355 Output: Your mark is: 85.36
DDC1023 PROGRAMMING METHODOLOGY
198
REV00
Chapter 6: Common Programming Errors
Syntax Errors Run-Time Errors Undetected Errors Logic Errors
DDC1023 PROGRAMMING METHODOLOGY
199
REV00
Chapter 6: Common Programming Errors
Syntax error occurs when the code violates grammar rules of C and is detected by the compiler.
DDC1023 PROGRAMMING METHODOLOGY
200
REV00
Chapter 6: Common Programming Errors
Run-time error occurs when the program directs the computer to perform an illegal operation (e.g., divide by zero).
temp=0 divide by zero
DDC1023 PROGRAMMING METHODOLOGY
201
REV00
Chapter 6: Common Programming Errors
A Program That Produces Incorrect Results Due to & Omission
DDC1023 PROGRAMMING METHODOLOGY
202
REV00
Chapter 6: Summary
Every C program has preprocessor directives and a main function. The main function contains variable declarations and executable statements. Variable names must begin with a letter or an underscore and consist of letters, digits, and underscore symbols. A reserved word cannot be used as an identifier.
DDC1023 PROGRAMMING METHODOLOGY
203
REV00
Chapter 7: Data Types, Operators and Simple Functions in C
Objectives
Understand the data types Able to write program with arithmetic operators Learn about the mixed-type assignment statement Know how to use the expression with multiple operators
DDC1023 PROGRAMMING METHODOLOGY
204
REV00
Chapter 7: Data Types
int Range : -32767 ~ + 32767 --- in ANSI C -10500 435 +15 -25 32767 double
char A a z
* ?
205
DDC1023 PROGRAMMING METHODOLOGY
REV00
Chapter 7: Arithmetic Operators
DDC1023 PROGRAMMING METHODOLOGY
206
REV00
Chapter 7: Arithmetic Operators
Execution of Multiple Operators Can be expressed as an Evaluation Tree.
area = PI * radius * radius;
DDC1023 PROGRAMMING METHODOLOGY
207
REV00
Chapter 7: Arithmetic Operators
Step by Step Expression Evaluation
DDC1023 PROGRAMMING METHODOLOGY
208
REV00
Chapter 7: Arithmetic Operators
Evaluation Tree
v = (p2 - p1) / (t2 - t1);
DDC1023 PROGRAMMING METHODOLOGY
209
REV00
Chapter 7: Arithmetic Operators
Evaluation Tree
z - (a + b / 2) + w * -y
DDC1023 PROGRAMMING METHODOLOGY
210
REV00
Chapter 7: Writing Mathematical Formulas in C
You may encounter two problems in writing a mathematical formula in C. First, multiplication often can be implied in a formula by writing two letters to be multiplied next to each other. In C, 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).
DDC1023 PROGRAMMING METHODOLOGY
211
REV00
Chapter 7: Library functions
Function Header File abs(x) cos(x) exp(x) pow(x, y) sqrt(x) <stdlib.h> <math.h> <math.h> <math.h> <math.h> Description Return the absolute value of x Return the cosine of angle x Return the value of ex Return the value of xy Return the squre root of x
For I/O library functions (printf, scanf) To use them, have to use #include <stdio.h> For Mathematical Functions (sqrt, pow, sin, cos) To use them, have to use #include <math.h>
DDC1023 PROGRAMMING METHODOLOGY
212
REV00
Chapter 7: Library functions
Example: Display the square root of 2 numbers provided as the input data (first and second) and the square root of their sum.
DDC1023 PROGRAMMING METHODOLOGY
213
REV00
Chapter 7: Summary
Cs data types enable the compiler to determine how to store a particular value in memory and what operations can be performed on that value. Three standard data types are int, double, and char. The data type of each variable must be declared. Assignment statements are used to perform computations and store results in memory. Function calls are used to get data (scanf) and to display values stored in memory (printf).
DDC1023 PROGRAMMING METHODOLOGY
214
REV00
Chapter 8: Selection Structures: If and Switch Statement In C
Objectives
Learn about the control structure Understand the conditions Apply the if statement with compound statements Use decision steps in algorithms Learn about the nested if statements and multiple alternative decisions Learn about the switch Statement
DDC1023 PROGRAMMING METHODOLOGY
215
REV00
Chapter 8: Control Structures
Control Structures control the flow of execution Three kinds of execution flow: Sequence
The execution of the program is sequential Selection A control structure which chooses alternative to execute Repetition A control structure which repeats a group of statements.
We will focus on the selection control structure this week.
DDC1023 PROGRAMMING METHODOLOGY
216
REV00
Chapter 8: Conditions
A program may choose among alternative statements by testing the value of key variables. if (your_grade > 60) printf(you are passed!)
Condition is an expression that is either false (represented by 0) or true (represented by 1). your_grade > 60
Conditions may contain relational or equality operators.
DDC1023 PROGRAMMING METHODOLOGY
217
REV00
Chapter 8: Conditions
Relational and Equality Operators
DDC1023 PROGRAMMING METHODOLOGY
218
REV00
Chapter 8: Conditions
Sample Conditions
DDC1023 PROGRAMMING METHODOLOGY
219
REV00
Chapter 8: Conditions
Logical Operators To form more complicated conditions by the three logical operators && (and) || (or) ! (not) Logical Expressions is an expression which uses one or more logical operators, e.g., salary < MIN_SALARY || dependents > 5 temperature > 90.0 && humidity > 0.9 !(0 <= n && n<= 100)
DDC1023 PROGRAMMING METHODOLOGY
220
REV00
Chapter 8: Conditions
DDC1023 PROGRAMMING METHODOLOGY
221
REV00
Chapter 8: Conditions
Operator Precedence An operators precedence determines its order of evaluation.
- x y * z x + y < min + max
DDC1023 PROGRAMMING METHODOLOGY
222
REV00
Chapter 8: Conditions
Evaluation Tree & Step-by-Step Evaluation
DDC1023 PROGRAMMING METHODOLOGY
223
REV00
Chapter 8: Conditions
Short Circuit Evaluation Stopping evaluation of a logical expression as soon as its value can be determined. e.g. a && b must be false if a is 0.
DDC1023 PROGRAMMING METHODOLOGY
224
REV00
Chapter 8: Conditions
Writing English Conditions in C
DDC1023 PROGRAMMING METHODOLOGY
225
REV00
Chapter 8: Conditions
Comparing Characters
DDC1023 PROGRAMMING METHODOLOGY
226
REV00
Chapter 8: Conditions
Complement a logical expression with the symbol ! just change its operator
item == SENT !(item == SENT) item != SENT !(a <= b)
a>b
DDC1023 PROGRAMMING METHODOLOGY
227
REV00
Chapter 8: The if Statement
Syntax 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 excellent health\n);
Ex-2.
if (x != 0.0) product = product * x;
DDC1023 PROGRAMMING METHODOLOGY
228
REV00
Chapter 8: If Statement with Compound Statements
if (condition) { true task } else { false task }
DDC1023 PROGRAMMING METHODOLOGY
229
REV00
Chapter 8: Decision Steps in Algorithms
Select from a choice of actions Refer slide 240 and 241 for the algorithms in making decision
DDC1023 PROGRAMMING METHODOLOGY
230
REV00
Chapter 8: Nested if Statements and Multiple Alternative Decisions
An if statement with another if statement as its true task or its false task
Dangling Else
if (x > 0) if (y > 0) a = a + 1; else b = b + 1;
DDC1023 PROGRAMMING METHODOLOGY
231
REV00
Chapter 8: Nested if Statements and Multiple Alternative Decisions
Nested if Example: Road Sign Decision Process
DDC1023 PROGRAMMING METHODOLOGY
232
REV00
Chapter 8: Nested if Statements and Multiple Alternative Decisions
Road Sign Decision Process
DDC1023 PROGRAMMING METHODOLOGY
233
REV00
Chapter 8: Nested if Statements and Multiple Alternative Decisions
Multiple-Alternative Decision
DDC1023 PROGRAMMING METHODOLOGY
234
Chapter 8: Nested if Statements and Multiple Alternative Decisions
Multiple-Alternative Decision Example
REV00
DDC1023 PROGRAMMING METHODOLOGY
235
REV00
Chapter 8: The switch Statement
When the selection is based on the value of a single variable or of a simple expression (called the controlling expression).
DDC1023 PROGRAMMING METHODOLOGY
236
REV00
Chapter 8: The switch Statement
Example of a switch Statement
DDC1023 PROGRAMMING METHODOLOGY
237
REV00
Chapter 8: Summary
Use if statement or switch statement to code decision steps in C. Using the relational operators (<, <=, >, >=) and equality operators (==, !=) to compare variables and constants Using the logical operators (&& (and), || (or), !(not)) to form more complex conditions Nested if statements are common in C and are used to represent decisions with multiple alternatives. Programmers use indentation and the multiple-alternative decision form when applicable to enhance readability of nested if statements. The switch statement implements decisions with more than 2 alternatives, where the alternative selected depends on the value of a variable or expression (the controlling expression). The controlling expression can be type int or char, but not type double.
DDC1023 PROGRAMMING METHODOLOGY
238
REV00
Chapter 9: Repetition and Loop Statement in C
Objectives Learn about the repetition in programs Count loops and the while statement Compute a sum or a product in a loop Understand the for and do-while statement Learn about the conditional loops: counter-controlled, sentinel-controlled and flag-controlled Design the loop
DDC1023 PROGRAMMING METHODOLOGY
239
REV00
Chapter 9: Repetition in Programs
In most commercial software, you can repeat a process many times. When using an editor program, you can move the cursor to a program line and perform as many edit operations as you need to. Loop is a control structure that repeats a group of steps in a program. Three C loop control statements while for do-while
DDC1023 PROGRAMMING METHODOLOGY
240
REV00
Chapter 9: Counting Loops and the while Statement
Counter-controlled loop (or counting loop) A loop whose required number of iterations can be determined before loop execution begins. The syntax
while (loop repetition condition) statement;
Loop repetition condition: the condition that controls loop repetition. Infinite loop: a loop that executes forever
DDC1023 PROGRAMMING METHODOLOGY
241
REV00
Chapter 9: Counting Loops and the while Statement
Example
count_emp = 0; /* no employees processed yet */ 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");
DDC1023 PROGRAMMING METHODOLOGY
242
REV00
Chapter 9: Counting Loops and the while Statement
Flowchart for a while Loop
DDC1023 PROGRAMMING METHODOLOGY
243
REV00
Chapter 9: Computing a Sum or a Product in a Loop
Loops often accumulate a sum or a product by repeating an addition or multiplication operation. Accumulator A variable used to store a value being computed in increments during the execution of a loop.
DDC1023 PROGRAMMING METHODOLOGY
244
REV00
Chapter 9: Computing a Sum or a Product in a Loop
Example
DDC1023 PROGRAMMING METHODOLOGY
245
REV00
Chapter 9: Computing a Sum or a Product in a Loop
Compound Assignment Operators
C provide special assignment operators variable op = expression;
DDC1023 PROGRAMMING METHODOLOGY
246
REV00
Chapter 9: The for Statements
Three loop control components with the loop body. Initialization of the loop control variable, Test of the loop repetition condition, and Change (update) of the loop control variable. The for statement in C supplies a designed place for each of these three components.
DDC1023 PROGRAMMING METHODOLOGY
247
REV00
Chapter 9: The for Statements
DDC1023 PROGRAMMING METHODOLOGY
248
REV00
Chapter 9: The for Statements
DDC1023 PROGRAMMING METHODOLOGY
249
REV00
Chapter 9: The for Statements
Increment and Decrement Operators
The increment (i.e., ++) or decrement (i.e., --) operators are the frequently used operators which take only one operand. for(int i=0; i<100; i++) {} for(int i=100; i>0; i--) {}
Side effect: the value of its operand is incremented/decremented by one.
DDC1023 PROGRAMMING METHODOLOGY
250
REV00
Chapter 9: The for Statements
Prefix and Postfix Increments The value of the expression in which the ++/-- operator is used depends on the position of the operator.
DDC1023 PROGRAMMING METHODOLOGY
251
REV00
Chapter 9: The for Statements
Example: Factorial Function
DDC1023 PROGRAMMING METHODOLOGY
252
REV00
Chapter 9: The for Statements
Inc. and Dec. Other Than 1
DDC1023 PROGRAMMING METHODOLOGY
253
REV00
Chapter 9: Conditional Loops: counter-controlled, sentinel-controlled and flag-controlled
In many programming situations, you will not be able to determine the exact number of loop repetitions before loop execution begins.
DDC1023 PROGRAMMING METHODOLOGY
254
REV00
DDC1023 PROGRAMMING METHODOLOGY
255
REV00
DDC1023 PROGRAMMING METHODOLOGY
256
REV00
Chapter 9: Loop Design
Problem-Solving Questions for Loop Design What are the inputs? What are the outputs? Is there any repetition? Do I know in advance how many time steps will be repeated? How do I know how long to keep repeating the steps? Sentinel-Controlled Loops Endfile-Controlled Loops Infinite Loops on Faulty Data
DDC1023 PROGRAMMING METHODOLOGY
257
REV00
Chapter 9: Loop Design
DDC1023 PROGRAMMING METHODOLOGY
258
REV00
Chapter 9: Loop Design
Sentinel-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.
DDC1023 PROGRAMMING METHODOLOGY
259
REV00
Chapter 9: Loop Design
Endfile-Controlled Loops A data file is always terminated by an endfile character that can be detected by the scanf and fscanf functions.
EOF stands for the endfile character.
DDC1023 PROGRAMMING METHODOLOGY
260
REV00
Chapter 9: Loop Design
Example of Endfile-Controlled Loops
DDC1023 PROGRAMMING METHODOLOGY
261
REV00
Chapter 9: Loop Design
Infinite Loops on Faulty Data 70 7o Detect faulty data
DDC1023 PROGRAMMING METHODOLOGY
262
REV00
Chapter 9: Nested Loops
Consist of an outer loop with one or more inner loops.
DDC1023 PROGRAMMING METHODOLOGY
263
REV00
Chapter 9: The do-while Statement
When we know that a loop must execute at least one time.
DDC1023 PROGRAMMING METHODOLOGY
264
REV00
Chapter 9: Summary
Repetition and Loop Statements Counter-Controller Loop Sentinel-Controller Loop Endfile-Controller Loop Input Validation Loop General Conditional Loop while, for, and do-while Compound Assignment Operators
DDC1023 PROGRAMMING METHODOLOGY
265