Chapter 1 Logic

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 16

Chapter 1 Logic

1. Hardware and software: the two major components of any computer system
Hardware: equipment, or devices
Software: programs that contain instructions for the computer
2. Input devices: allow data to enter the computer
Mouse, keyboard, scanner
Processing: working on the data; such as:
Organizing data
Checking data for accuracy
Mathematical or other manipulations on data
Central Processing Unit (CPU): hardware that performs the tasks
3. 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: the rules governing word usage and punctuation in the language
Machine language: a language that controls the computers on/off circuitry
Compiler or interpreter: software that translates programming languages to machine language
4. A program must be free of syntax errors to be run, or executed, on a computer
To function properly, the logic must be correct
5. Logic errors, or semantic errors, are more difficult to locate than syntax errors
6. Two storage categories: internal and external
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

7. Six programming phases:


Understand the problem
Plan the logic
Code the program
Use software to translate the program to machine language
Test the program
Deploy the program into production
1) 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
2) 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: English-like representation of the logic
Walk through the logic before coding by desk-checking the logic
3) Coding the program:
Select the programming language
Write the instructions
4) Using software to translate the program into machine language:
Programmers write instructions in English-like high-level languages
Compilers change the programs into low-level machine language that can be executed
Syntax errors are identified by the compiler or interpreter
5) 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
6) Putting the program into production
Do this after testing is complete and all known errors have been corrected
May require coordination with other related activities or software

8. Data hierarchy: ordering of data types by size


Character: single symbol (letter, number, special 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
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
9. Flowchart input symbol:

10. Flowchart processing symbol

11. Flowchart output symbol:

12.

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

13. Back-pointing arrows show statements that will be repeated.


14.

Variable: a memory location whose contents can vary; also called an identifier
Each programming language has it own rules for naming identifiers, including:
Legal characters
Maximum length
Use of upper or lower case
Variable name must be a single word, but can be formed from several words
rate, interestRate, interest_rate
Choose meaningful names for variables
Improves the readability and maintainability of code

15.

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

16.

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

17. 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

18.

Assignment statement:
Assigns a value to a variable
Variable must appear on the left side, value on the right side of the assignment operator
Right side may be an expression that will be evaluated before storing the value in the variable
Assignment operator: the equal sign (=) in most languages
Variable:
Memory location: has an address and a value
Value (contents) is used for various operations

19.

Two 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
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

20.

Programming began in the 1940s, using memory addresses and machine code directly
Higher level languages were developed to allow English-like instructions
Older programs were monolithic, and ran from beginning to end
Newer programs contain modules that can be combined to form programs
Two major programming techniques:
Procedural programming
Object-oriented programming
Procedural programming: focuses on the procedures that programmers create
Object-oriented programming: focuses on objects that represent real-world things and their attributes
and behaviors
Both techniques employ reusable program modules

21

Translator program
Compiler or interpreter
Changes the programmers English-like high-level programming language into the low-level
machine language
Syntax error
Misuse of a languages grammar rules
Programmer corrects listed syntax errors
Might need to recompile the code several times
Logical error
Use a syntactically correct statement but use the wrong one for the current context
Programs should be tested with many sets of data

22. Conversion
Entire set of actions an organization must take to switch over to using a new program or set of programs
23. Maintaining the Program
Maintenance
Making changes after program is put into production
Common first programming job
Maintaining previously written programs
Make changes to existing programs
Repeat the development cycle
24. Two Truths & A Lie
Hardware is the equipment, or the devices, associated with a computer. Software is computer
instructions. (T)
The grammar rules of a computer programming language are its syntax. (T)
You write programs using machine language, and translation software converts the statements to a
programming language. (F)
25. Drawing Flowcharts
Create a flowchart
Draw geometric shapes that contain the individual statements
Connect shapes with arrows
Input symbol
Indicates input operation
Parallelogram
Processing symbol
Processing statements such as arithmetic
Rectangle

Output symbol
Represents output statements
Parallelogram
Flowlines
Arrows that connect steps
Terminal symbols
Start/stop symbols
Shaped like a racetrack
Also called lozenge
26. Two Truths and A Lie
A program with syntax errors can execute but might produce incorrect results.
Although the syntax of programming languages differs, the same program logic can be expressed
in different languages.
Most simple computer programs include steps that perform input, processing, and output.
27. Syntax
Compilers dont always know exactly what you mean, nor do they know what the proper correction
should be, but they do know when something is wrong with your syntax.
When writing a program, a programmer might need to recompile the code several times.
Remember, an executable program is created only when the code is free of syntax errors.
28. Two Truths and A Lie
Understanding the problem that must be solved can be one of the most difficult aspects of programming.
The two most commonly used logic-planning tools are flowcharts and pseudocode.
Flowcharting a program is a very different process if you use an older programming language instead of
a newer one.
29. Two Truths and A Lie
When you draw a flowchart, you use a parallelogram to represent an input operation.
When you draw a flowchart, you use a parallelogram to represent a processing operation.
When you draw a flowchart, you use a parallelogram to represent an output operation.
30. Pseudocode is Fairly Flexible
Instead of start and stop begin and end
Instead of writing input myNumber get or read myNumber
Instead of writing set myAnswer calculate or compute myAnswer = myNumber * 2
Instead of writing output myAnswer display, print or write myAnswer

31. After the flowchart or pseudocode has been developed, the programmer only needs to:
Buy a computer
Buy a language compiler
Learn a programming language
Code the program
Attempt to compile it
Fix the syntax errors
Compile it again
Test it with several sets of data
Put it into production
32. Loop: repetition of a series of steps
Infinite loop: repeating flow of logic with no end
33. Two Truths and A Lie
A program that contains an infinite loop is one that never ends.
A preselected value that stops the execution of a program is often called a dummy value or sentinel
value.
Many programming languages use the term fe (for file end) to refer to a marker that automatically acts
as a sentinel.
34. Use a keyboard to type program statements into an editor
Plain text editor
Similar to a word processor but without as many features
Text editor that is part of an integrated development environment (IDE)
Software package that provides an editor, compiler, and other programming tools
35.

Command line
Location on your computer screen at which you type text entries to communicate with the
computers operating system
Graphical user interface (GUI)
Allows users to interact with a program in a graphical environment

36. Declaring and Using Variables and Constants


Data items
All the text, numbers, and other information that are processed by a computer
Stored in variables in memory
Different forms
Variables
Literals, or unnamed constants
Named constants

37. Working with Variables


Named memory locations
Contents can vary or differ over time
Declaration
Statement that provides a data type and an identifier for a variable
Identifier
Variables name
Data type
Classification that describes:
What values can be held by the item
How the item is stored in computer memory
What operations can be performed on the data item
Initializing a variable
Declare a starting value for any variable
num mySalary, num yourSalary = 14.55, string myName, string yourName = Juanita
Garbage
Variables unknown value before initialization (you declare a variable, but do not initialize it)
38. Naming Variables
Programmer chooses reasonable and descriptive names for variables
Programming languages have rules for creating identifiers
Most languages allow letters and digits
Some languages allow hyphens
Some languages allow dollar signs or other special characters
Different limits on the length of variable names
39. Two Truths and A Lie
A variables data type describes the kind of values the variable can hold and the types of operations that
can be performed with it.
If name is a string variable, then the statement set name = Ed is valid.
If salary is a numeric variable, then the statement set salary = 12.50 is valid

40. String Data


Write a program using Visual Logic that requests or inputs the name of the program user then displays a
greeting message such as Hello Name, where Name is the name entered.
The text must be in quotes

Simply type: Hello & name before the line feed

41. You can also refer to a variable as a mnemonic


A mnemonic is a memory device, like the musical reference Every good boy does fine, which makes
it easier to remember the notes that occupy the lines on the staff in sheet music.
In programming a variable name is a device that makes it easier to reference a memory address.
Different languages put limits on the length of variable names, although in general, the length of
identifiers in newer languages is virtually unlimited.
42. Camel casing
Variable names such as hourlyWage have a hump in the middle
When the variable starts with a lowercase letter and any subsequent words begins with an
uppercase letter
Pascal casing
Variable names such as HourlyWage
When the first letter of a variable name is uppercase

43.

Numeric constant (or literal numeric constant)


Specific numeric value
Example: 43
Does not change
String constant (or literal string constant)
String of characters enclosed within quotation marks
Example: Amanda
Unnamed constants
Do not have identifiers like variables do

44.

Numeric variable
Holds digits
Can perform mathematical operations on it
String variable
Can hold text
Letters of the alphabet
Special characters such as punctuation marks
Assign data to a variable
Only if it is the correct type

45.

Named constant
Similar to a variable
Can be assigned a value only once
Assign a useful name to a value that will never be changed during a programs execution
43 and Amanda
Magic number
Unnamed constant like 0.06
Purpose is not immediately apparent
Avoid this (use num salesTax = 0.06 instead)

46.

Assignment statement
set myAnswer = myNumber * 2
Assignment operator
Equal sign
Always operates from right to left
Valid
set someNumber = 2
set someNumber = someOtherNumber
Not valid
set 2 + 4 = someNumber

47. Standard arithmetic operators:


+ (plus sign)addition
(minus sign)subtraction
* (asterisk)multiplication
/ (slash)division
48. Rules of precedence
Also called the order of operations
Dictate the order in which operations in the same statement are carried out
Expressions within parentheses are evaluated first
Multiplication and division are evaluated next
From left to right
Addition and subtraction are evaluated next
From left to right
Left-to-right associativity
Operations with the same precedence take place from left to right
answer = a + b + c * d / e f
answer = a + b + (temporary result calculated) f
answer = a + b + ((c*d) / e) - f
50. Two Truths and A Lie
The assignment operator always operates from right to left; programmers say it has right- associativity
or right-to-left associativity.
The operand to the right of an assignment operator must be a name that represents a memory
address.
The following adds 5 to a variable named points;
points = points + 5
51. Modularization
Programmers seldom write programs as one long series of steps.
Instead they break down the programming problem into reasonable units, and tackle one small task at
a time.
These reasonable units are called
Modules, subroutines, procedures, functions or methods
The name that programmers use for their modules usually reflects the actual programming language they
use.
For example:
Visual Basic programmers use procedures or sub procedures,
C and C++ programmers call their modules functions,
Java, Alice and other object-oriented programmers are more likely to use methods,
Programmers in Cobol, Basic (older languages) are most likely to use subroutines.

The process of breaking down a large program into modules is called modularization.
You are not required to modularize a large program in order to make it run but,
Modularization provides abstraction
Modularization allows multiple programmers to work on a problem.
Modularization allows you to reuse your work more easily.
52.

Abstraction
Paying attention to important properties while ignoring nonessential details
Selective ignorance
Newer high-level programming languages
Use English-like vocabulary
One broad statement corresponds to dozens of machine instructions
Modules provide another way to achieve abstraction
With Abstraction
Do laundry
Call Aunt Nan
Start term paper
Without Abstraction
Pick up laundry basket
Put laundry basket in car
Drive to laundry mat

53. Modularization Allows Multiple Programmers to Work on a Problem


More easily divide the task among various people
Rarely does a single programmer write a commercial program
Professional software developers can write new programs quickly by dividing large programs
into modules
Assign each module to an individual programmer or team
Modularization Allows You to Reuse Your Work
Reusability
Feature of modular programs
Allows individual modules to be used in a variety of applications
Many real-world examples of reusability
Reliability
Feature of programs that assures you a module has been tested and proven to function correctly

54. Modularizing a Program


Main program
Basic steps (mainline logic) of the program
Include in a module
Header
Body
Return statement
Naming a module
Similar to naming a variable
Module names are followed by a set of parentheses
When a main program wants to use a module
Calls the modules name
Flowchart
Symbol used to call a module is a rectangle with a bar across the top
Place the name of the module you are calling inside the rectangle
Draw each module separately with its own sentinel symbols
Determine when to break down any particular program into modules
Does not depend on a fixed set of rules
Programmers do follow some guidelines
Statements should contribute to the same job
Functional cohesion
55. Declaring Variables and Constants within Modules
Place any statements within modules
Input, processing, and output statements
Variable and constant declarations
Variables and constants declared in a module are usable only within the module
Visible
In scope
Portable
Self-contained units that are easily transported
Global variables and constants
Declared at the program level
Visible to and usable in all the modules called by the program
56. Mainline logic of almost every procedural computer program follows a general structure
Declarations for global variables and constants
Housekeeping tasks
Detail loop tasks
End-of-job tasks

57.

Hierarchy chart
Shows the overall picture of how modules are related to one another
Tells you which modules exist within a program and which modules call others
Specific module may be called from several locations within a program
Planning tool
Develop the overall relationship of program modules before you write them
Documentation tool

58. Features of Good Program Design


Use program comments where appropriate
Identifiers should be well-chosen
Strive to design clear statements within your programs and modules
Write clear prompts and echo input
Continue to maintain good programming habits as you develop your programming skills
59.

Program comments
Written explanations
Not part of the program logic
Serve as documentation for readers of the program
Syntax used differs among programming languages
Flowchart
Use an annotation symbol to hold information that expands on what is stored within another
flowchart symbol

60. Choosing Identifiers


General guidelines
Give a variable or a constant a name that is a noun
Give a module an identifier that is a verb
Use meaningful names
Self-documenting
Use pronounceable names
Be judicious in your use of abbreviations
Avoid digits in a name
General guidelines (continued)
Use the system your language allows to separate words in long, multiword variable names
Consider including a form of the verb to be
Name constants using all uppercase letters separated by underscores (_)
Organizations sometimes enforce different rules for programmers to follow when naming variables
Hungarian notation

61. Designing Clear Statements


Avoid confusing line breaks
Use temporary variables to clarify long statements
62. Avoiding Confusing Line Breaks
Most modern programming languages are free-form
Take care to make sure your meaning is clear
Do not combine multiple statements on one line
63.

Prompt
Message displayed on a monitor to ask the user for a response
Used both in command-line and GUI interactive programs
Echoing input
Repeating input back to a user either in a subsequent prompt or in output

64. Every program you write will be better if you:


Plan before you code
Maintain the habit of first drawing flowcharts or writing pseudocode
Desk-check your program logic on paper
Think carefully about the variable and module names you use
Design your program statements to be easy to read and use

You might also like