CPS120 Introduction to Computer Science

Download Report

Transcript CPS120 Introduction to Computer Science

CPS120 Introduction to
Computer Science
Exam Review
Lecture 9
Introduction To Computers
System Components
• Hardware
– I/O devices (input/output)
• keyboard, mouse, monitor, etc.
– CPU
– Primary Storage
– Secondary Storage
• Software
Storage Devices
• Primary storage
– RAM (Random Access Memory, or just “memory” for
short)
• active data that is being stored, lost if power is cut off so save
often
– ROM (Read-Only Memory)
• commands that are permanently stored on chips
• PC’s use BIOS, Macs use the Toolbox
• Secondary storage
– Hard disk, floppy disks
– Slower method of storage & retrieval but “safer”
Representing Data: Bits
• Computer only uses “on” & “off” within its
circuits
• Binary number system
– “On”, 1, high state of electricity
– “Off”, 0, low state of electricity
– Bits (0’s and 1’s)
Typical System
•
•
•
•
•
•
•
Computer case
Monitor
Printer
Speakers
Modem
Keyboard
Mouse
Types of Ports
• Parallel port – 25 holes; female connector; LPT1; printer or
storage devices
• Monitor port
• Keyboard port
• Serial port – 9 or 25 pins; male connector; COM1; mouse
or modem
• Game port
• Network port
• USB port
– 127 devices
– Printer, modem, joy stick
Types of Printers
• Ink-jet: has a print head that sprays ink
through tiny nozzles onto a page
– 2 to 10 pages (ppm)
– 360 to 2400 dots per inch
– Color printers spray cyan, magenta, yellow
and black to create different colors
• Laser-printer
–
–
–
–
–
Works like a photo copier
Speed of 4 to 16 pages
Have a CPU
600 to 2400
Memory – 2mb to 8 Mb
Communications
• Modems let a computer exchange
information through telephone lines
• Speed of a modem determines how fast it
sends and receives messages
– 56,000 bps (56 Kbps)
• V.90 standard: receive 56K and send 33.6K
– Speed at which information flows depend on
the quality of the phone line
• A modem needs a communications
package to manage the transmission of
information
• Data compression – squeezes together data
High-speed Connections
• ISDN – Integrated Services Digital Network
– Digital phone line
– 56 Kbps to 128 Kbps
• Cable Modem
– Same cable as TV
– 4000 Kbps
• DSL – Digital subscriber line
– High speed digital phone line
– 1000 – 6000 Kbps
• Satellite
USB and Firewire
• High-speed ports that allow information to quickly
transfer between a computer and an external
device
– USB
• Supports up to 127 device
– USB 1.0: 12 megabits per second
– USB 2.0: 480 Mbps
– FIREWIRE
• 63 devices at 400 Mbps
• Can purchase Firewire expansion card
CPU (Central Processing Unit)
• Processes instructions, performs calculations,
and manages the flow of information
• Performance:
– CPU speed is a major factor in determining how fast a
computer operates (faster the speed, faster computer
operates)
• Measured in megahertz (MHz) A clock cycle relates to the
clock that controls the timing in the microprocessor.
• For example, a 900MHz (megahertz) clocked
microprocessor generates 900 million clock cycles per
second.
– Each generation of CPU is more powerful than the
one before. It's clock cycles are faster at a given speed
BUS
• Electronic pathway that carries information
between devices in a computer
– Bus Width (think lanes of a highway)
• 8 bits is one character
– Bus Speed (think speed limit)
• Measured in MHz (millions of cycles per second)
Processing
• Random Access Memory – Temporarily stores data
inside a computer
– Constantly overwritten
– Measured in megabytes (MB)
• 64 minimum these days100 MHz (millions of cycles per
second)
– Dynamic RAM is type of memory chip that makes up
memory in many computer systems. Access speed measured
in megabits
• Most system boards can support access speed of Single Inline
Memory Module (SIMM) – 9 memory chips
• Dual Inline Module (DIMM) – 18 memory chips
• If you have limited memory or you have many
programs open, your computer may need to use part of
the hard drive to simulate more memory
Using Memory Cache
1. Look through documents on your desk
(internal cache)
2. Look through documents in your desk
drawer (external cache)
3. Looking through documents in your filing
cabinet (RAM)
Relation of Cache & Hard Drives
• Disk cache speeds up the computer by
storing the data the computer has most
recently used
–
–
–
–
Constantly updated
Area of memory
Fast access
Then hard drive is searched
Hard Drives
• Magnetically stores data on rotating disks
called platters
• Stores your operating system and programs
• Document will not be lost when you turn off
the computer
• Capacity is measured in bytes
• Speed is measured in revolutions per minute
CD-R & CD-RW Drives
• CD-R (Compact Disc – Recordable)
– Permanent store; not erasable
• CD-RW
– Can be erased and rewritten
– Read / Write and Re-write speeds
– Usually 74 minutes
• Special software needed to record onto a disk
– Referred to as burning a CD
DVD-ROM Drive
• DVD – Digital Versatile Disk
– Generally cannot change the information stored on a
disk
– Similar to CD but stores more information
– Speed determines transfer rate (6 X)
– Capacity
•
•
•
•
1 side / 1 layer – 4.7 GB
1 side / 2 layer – 8.5 GB
2 sides / 1 layer – 9.4 GB
2 sides / 2 layers – 17 GB
Removable Storage Devices
• Jazz Drive – 2 GB
• Zip Drive – 250 MB
• LS-120 Drive – 120 MB
Databases
• Organized in:
– Tables
• Collection of information about a specific topic
– Field
• Category of information
– Record
• Single instance of information
Operating Systems
• Software that controls the overall activity of the
computer
– Ensure that all of the parts of the computer work
together smoothly
– Functions:
• Control hardware
• Run software
• Manage information
– Programs that run on one operating system platform do
not generally run on others
Characteristics of Specific OS
•
•
•
•
•
•
•
•
•
DOS
Windows 3.1
Windows 9X
Windows ME
Windows XP
Windows NT/2000
MAC OS9 & 10
UNIX
LINUX
Compilers
• An engine that works on your behalf to
process instructions and allow you to deal
with various basic rules of the language
– The compiler’s job is to make sure you follow
the rules, to require that you provide enough
information that the compiler can translate you
instructions into languages the components can
understand
Interpreter vs. Compiler
• Interpreter
– Translates instructions to machine code line-byline.
• Compiler
– Translates the entire program to machine code
before running it.
What Is a Network
• A network is a group of connected
computers that allow people to share
information and equipment
Physical Networking
• Hubs
– A hub is a device that provides a central location where
all the cables on a network come together
• NICs (Network Interface Card)
– An expansion card that physically connects each
computer to the network
• Cables
– Coaxial, Unshielded Twisted Pair (UTP), Shielded
Twisted Pair, Fiber-optic
– Wireless
Client-Server Networks
• Used for large networks
• Files are stored on a central computer and
everyone who can access the network can be
given access them
• Easy to create scheme to backup and protect files
• Client: a computer that can access information
stored on the server
• Server: Central computer that stores files
– NetWare, UNIX, Windows NT/2000
Peer-to-Peer
• Used for a small number of computes (e.g.
10)
• Files stored on own computers; access
given to them to others on the network
– LANtastic, Windows-98, Windows-ME
Information Exchange
• Ethernet:
– Most popular and least expensive solution
– Each computer waits for a pause before sending
information
• Like polite conversation
– Collisions between information often occur
• Computers wait a moment, then resend
– Ethernet – 10 Mbps, Fast Ethernet – 100 Mbps,
Gigabit Ethernet 1000 Mbps
Information Exchange
• Token-ring is a type of network where a token that
collects and delivers information is passed from
compute to computer
– Speeds of 4 or 16 Mbps
• Asynchronous Transfer Mode (ATM) is a type of
network that works by sending information in
equal-sized pieces called cells
– 25, 155, 622 or 2488 Mbps
– Often networks networks
Intranet
• Small version of the Internet in a company
• Uses familiar web-browsers and email
packages
• Allows hyper-linking
• VPNs (Virtual Private Network)
– End-to-end encryption
– More cost efficient than private lines
World Wide Web
• Part of the Internet consisting of a huge
collection of documents stored on
computers around the world
– Web server: computer that stores and delivers
web pages
– Web site: collection of web pages
• URL (Uniform Resource Locator) – unique address
– HTTP, Computer, Directory, Name of Page
– Hyperlinks jump to different web pages
Creating Good Passwords
• In order to be useful in authentication and
authorization, a password should meet the
following criteria:
– Passwords must be at least six characters
– Passwords must include three of four types of
characters:
–
–
–
–
Uppercase letters
Lowercase letters
Numbers
Non-alphabetic characters such as punctuation marks
• Passwords shouldn't contain personal information
Pass-phrases
• If you are serious about good password
security, get in the habit of using ‘passphrases’. For example, it is easy enough to
remember a phrase like ‘…born on the 4th
of July’, but creating a password from it like
bot4thoJ would create a password that
meets the criteria discussed above.
Virus Definition
• A computer virus is a computer program that
can infect other computer programs by
modifying them in such a way as to include a
copy of itself. A virus, by definition, can't
exist by itself. It must infect an executable
program.
– A simple virus that can make a copy of itself over
and over again is relatively easy to produce. Even
such a simple virus is dangerous because it will
quickly use all available memory and bring the
system to a halt.
Other Types of Viruses
• An e-mail virus is not any different from a regular
virus; it just has a different mode of transportation
ILOVEYOU"
– Melissa
• Script viruses are destructive code that does its
damage by executing a program on a client
machine
• A macro virus is a type of computer virus that is
encoded as a macro embedded in a document
Anti-Virus Software
• Anti-viral software can be set up to run automatically each time you
boot up the machine or run an executable. You can also execute antiviral software manually if you suspect you have had a problem or you
have received a suspicious attachment or some sort of un-trusted
media.
• There are two parts to most pieces of anti-viral software; the engine
and the definitions.
– The definitions change all the time. This is the part of anti-viral software
that needs to be updated constantly, because the population of viruses
changes rapidly, with newly developed viruses springing up along with
minor modifications of existing viruses (mutations) appearing constantly.
– The engine, on the other hand, is static and changes only at major release
points. The engine is the driving force behind a virus program that checks
for virus signatures on you machine and in your software.
Stay Current
• The program you use isn't as important as
how often you use it and that you keep it
updated with the most recent virus
definitions
– To be effective, antiviral software must be
current -- even two-month-old software can be
dangerously outdated
Other Types of 'Malware'
• A worm is a special type of virus that can replicate
itself and use memory, but cannot attach itself to
other programs
– 'Code Red'
– Nimda
• A Trojan horse is a program that pretends to do
something useful, but instead does something
nefarious.
– Trojans aren't infectious
– Often they place executables on the drive
Hardening Your System
• The term "hardening" refers to the process of
configuring software so as to minimize potential
security risks
• Hardening security-specific applications like
firewalls, intrusion detection systems, and
antiviral tools involves turning on features and
setting restrictive access rules
Your Security Profile
• A port is an interface on a computer to which you
can connect a device
– A port is an endpoint to a logical connection
– The port number identifies what type of port it is
• Personal computers have various types of ports. In
this context
• A key to determining your computer’s security
profile is to determine port usage
How do Firewalls Work?
• A firewall is analogous to a moat around a
medieval castle. In essence, the moat and
drawbridge represent a "choke" point for all
traffic in and out
• A single point is much easier to monitor and
can be closed if needed
– All messages entering or leaving the intranet pass
through the firewall, which examines each
message and blocks those that do not meet the
specified security criteria
How Does it Work Technically?
• Firewalls act as proxy servers, by masking
the address of internal machines
• Or packet filters using a "wall of code" that
inspects each individual "packet" of data as
it arrives at either side of the firewall
Different Types of Backups
• Different types
– Full
– Incremental
– Differential
Introduction to Programming
The Program Development Cycle
Understand the problem
Plan the program's logic
Code the program
Get the program into machine-readable form
Translate the program
Test and debug the program
Document the program
What Can a Program Do?
• A program can only instruct a computer to:
–
–
–
–
–
–
–
Read Input
Sequence
Calculate
Store data
Compare and branch
Iterate or Loop
Write Output
Fundamental Programming Concepts
• Assignment of values to a variable
• Iteration (Looping)
– Over a set of set of statements
– With respect to a logical expressions
(conditions)
• Delegation of sub-tasks to functions /
procedures
The Structure Theorem
•
•
The Structure Theorem states that any algorithm
can be built from three basic control structures.
One-after-another (Sequence)
Decision-making (Selection)
–
•
Making choices between 2 or more alternatives
Repetition (Iteration)
–
Concerned with repetitive tasks (and the termination
conditions of loops)
What is an Algorithm?
• An algorithm is merely the sequence of steps
taken to solve a problem
– Two parts
• Actions to be executed
• Order in which those actions are to be done
– Computational steps that transform the input data into
useful output data.
• Algorithms are not programs
– They need to be coded in a programming language like
C++
Pseudocode & Flowcharts are Important
• Pseudocode –
– Make a detailed description of your algorithm’s logic
before worrying about C++ syntax and data layout.
– An algorithm you develop using pseudocode should be
capable of implementation in any procedural
programming language
• Pseudocode is generally independent of the implementation
language
• Flowcharts –
– A graphical layout of the algorithm is often very useful
in spotting “illogical” logic!
Reasons Programmers Draw Flowcharts
• Drawing a flowchart gives the programmer a good
visual reference of what the program will do
• Flowcharts serve as program documentation
• Flowcharts allow a programmer to test alternative
solution to a problem before coding
• Flowcharts provide a method for easy desk
checking
Common Flowchart Symbols
Common Flowchart Symbols
Terminator. Shows the starting and ending points of the program. A terminator has
flow lines in only one direction, either in (a stop node) or out (a start node).
Data Input or Output. Allows the user to input data and results to be displayed.
Processing. Indicates an operation performed by the computer, such as a variable
assignment or mathematical operation. With a heading – an internal subroutine
Decision. The diamond indicates a decision structure. A diamond always has two
flow lines out. One flow lineout is labeled the “yes” branch and the other is labeled the
“no” branch.
Predefined Process. One statement denotes a group of previously defined statements.
Such as a function or a subroutine created externally
Connector. Connectors avoid crossing flow lines, making the flowchart easier to read.
Connectors indicate where flow lines are connected. Connectors come in pairs, one with
a flow line in and the other with a flow line out.
Off-page connector. Even fairly small programs can have flowcharts that extend several
pages. The off-page connector indicates the continuation of the flowchart on another
page. Just like connectors, off-page connectors come in pairs.
Flow line. Flow lines connect the flowchart symbols and show the sequence of operations
during the program execution.
Rules for Drawing Flowcharts
• Top to bottom and left to right
– Draw the flowchart the way you like to read
– Use arrowheads on flow lines whenever the
flow is not top to bottom, left to right
• Be neat ! Use graphics software
• Avoid intersecting lines
Disadvantages to Flowcharts
• Time consuming
• A program flowchart shows how the input
becomes output, but it does not show why a
particular step is done
• Flowcharts are subjective
Pseudocode
• This device is not visual but is considered a
“first draft” of the actual program.
• Pseudocode is written in the programmer’s
native language and concentrates on the logic
in a program—not the syntax of a
programming language.
General Rules for Pseudocode
• There is no standard pseudocode
• The rules of Pseudocode are generally
straightforward
– Should be easily read and understood by nonprogrammers
– All statements showing "dependency" are to be
indented.
• These include while, do, for, if, switch
Pseudocode Statement Rules
– Statements are written in a simple English-like
language
– Each instruction is started on a separate line
– Logic-showing keywords are written in UPPER CASE
or typed in BOLD UPPERCASE
• (e.g. IF, THEN, FOR, DO etc.)
• These are the only uppercase words in this form of
pseudocode.
– Indentation is used to show structure
– Instructions are written from top to bottom, with only
one entry point and one exit point
– Logically related groups of instructions can be formed
into modules and given a name
Rules for Pseudocode
1. Make the pseudocode language-independent
2. Indent lines for readability
3. Make key words stick out by showing them
capitalized, in a different color or a different font
4. Punctuation is optional
5. End every IF with ENDIF
6. Begin loop with LOOP and end with ENDLOOP
7. Show MAINLINE first; all others follow
8. TERMINAE all routines with an END
instruction
Compilation Process
1. Get the set of instructions from you
2. Review the instructions to see if they violate the
rules (syntax) of the language
3. If all the rules are obeyed, create a working file
in the language of the computer (machine
language)
4. Attach to the working file full instructions for
any shortcuts you may have used (linkage)
5. Assemble a final file in machine language
Compiling and Debugging
• Executable code will not be created until
you correct all of the syntax errors in your
source code
• Then the fun (with logic errors) begins
Syntax & Logic Errors
• A syntax error is simply the violation of the rules
of a language; misuse of structure and form in
programming or a violation of the compiler’s
rules. These errors are detected by the compiler
– Also know as 'fatal compilation errors'
• A logic error is a mistake that complies with the
rules of the compiler that causes the program to
generate incorrect output
Error Prevention & Testing
• Use good design and programming style
– Don't use global variables
• Study your code before typing and running it
– Have someone else look at it
• Make your program self-documented
• Program defensively – put in assertions and self-checking
code and comment them out
• Test your code at boundary values for variables
• Log your bugs
• Test code in pieces using "stubs"
• Consider – correctness, reliability, utility and performance
Semantic Error Detection
• Use the tracing method to display the value of
critical variables
• Make the error reproducible
• Get a stack trace of function calls to verify
sequencing
• Correct the error immediately when you find it
and check if you made it somewhere else
• Examine your last code changes for errors
• Ensure that you have saved and run the corrected
programs
Debugging
• Debugging is the process of locating and
fixing or bypassing bugs (errors) in computer
program code or the engineering of a hardware
device.
• To debug a program is to start with a problem,
isolate the source of the problem, and then fix
it.
Debugging Steps
1. Proofread before compiling
2. Compile
3. Correct all the obvious errors
•
•
•
•
Start at the beginning of the list of errors and warnings
A single syntax error may cause the compiler to believe numerous
other syntax errors are occurring
Look at the error lines and if you see the error, fix it. Otherwise,
leave it for later. It may vanish when you fix something else
Don’t worry if more errors appear. Some errors mask other errors
4. Recompile when you have fixed what you recognize
Debugging Steps
5. Repeat 3 & 4 until no further errors are
obvious
6. Attempt to solve the remaining errors in a
top-down fashion
7. Solve whatever errors you can without
spending long periods of time on any given
error
8. Recompile whenever you feel you don’t see
any further solutions
A Debugging Mindset
• Assume your syntax is wrong. Look it up!
• Add working comments as you change things
• If you are 100% sure a line is correct, then
search for a syntax error in the lines
ABOVE that line
– Start with the immediately previous line and
work backward
• Never make a change you can’t explain
Debugging Checklist
1.
Visually verify the spelling and case of keywords and
identifiers
-- Remember, in the editor, keywords are blue, literals are black
and comments are green
-- Look for problems with l and 1 and o and 0
2.
Verify syntax with a reference book, not just visually
-- Don’t trust your eyes; you see what is supposed to be there
3.
4.
Try to find an example in the reference book that does
something similar and compare the code
Verify that the necessary delimiters used for that line are
there
-- Check the lines above and below as well
Debugging Checklist
5.
6.
Without looking at your source code or notes, rewrite the
instruction on a piece of paper and then compare it to
your actual code; don’t cheat
Verify that the line is really the source of the error by
commenting the line using //
a)
b)
c)
d)
Don’t worry about other errors that result from this
If the error disappears, it probably results from the line you are
working on
If it moves to the next line it is probably caused earlier in the
code
Remember that the compiler cannot be trusted to pinpoint lines
Warnings
• Even though an executable has been
generated, you may not be done with syntax
errors
• Compilers generate syntax warning
messages which are not fatal errors but
represent special error checking functions
for certain common programming errors
Linker Errors
• Not all syntax errors are detectable by the
compiler
– These errors do not become apparent until files
are put together to create an executable
– These errors are not linked to a specific line of
code
• Look for the name of the variable and see what lines
of code it occurs on using EDIT and FIND
– LNIK2001: unresolved external
– LNK1120: unresolved externals
Logic/Semantic Errors
• If the data is good and a program does not
do what it is supposed to do, there must be
at least one logic error present
– The syntax rules of C++ have been correctly
followed, but the meaning of the code is
incorrect
Semantic Errors
• A semantic error is a violation of the rules of
meaning of a programming language
– E.g. My refrigerator just drove a car to Chicago
– Overt logic errors
• Something is obviously wrong even though the program is
running
– Covert logic errors
• Not so obvious something is wrong
Run things various ways to highlight these errors
Approaches to Correction
• Desk-checking
• Inserting Tracing Statements
– Used when program "crashes"
– Runs to completion with incorrect output
• Using an interactive debugger
Common Semantic Errors
1.
Infinite Loop
–
2.
3.
4.
Misunderstanding operator precedence
Dangling else
Off-By-One Error
–
5.
6.
7.
Created when a loop in which the expression tested never
becomes false
Loop that iterates one fewer or one more than is correct
Code inside a loop that doesn’t belong there
Not using a compound statement when one is required
Array index bounds error
Computer Mathematics
Representing Data
• The computer knows the type of data stored
in a particular location from the context in
which the data are being used;
– i.e. individual bytes, a word, a longword, etc
– 01100011 01100101 01000100 01000000
• Bytes: 99(10, 101 (10, 68 (10, 64(10
• Two byte words: 24,445 (10 and 17,472 (10
• Longword: 1,667,580,992 (10
Alphanumeric Codes
• American Standard Code for Information
Interchange (ASCII)
– 7-bit code
– Since the unit of storage is a bit, all ASCII codes are
represented by 8 bits, with a zero in the most significant
digit
– H e l l o W o r l d
– 48 65 6C 6C 6F 20 57 6F 72 6C 64
• Extended Binary Coded Decimal Interchange
Code (EBCDIC)
Decimal Equivalents
•
Assuming the bits are unsigned, the decimal
value represented by the bits of a byte can be
calculated as follows:
1. Number the bits beginning on the right using
superscripts beginning with 0 and increasing as you
move left
•
Note: 20, by definition is 1
2. Use each superscript as an exponent of a power of 2
3. Multiply the value of each bit by its corresponding
power of 2
4. Add the products obtained
Binary to Hex
• Step 1: Form four-bit groups beginning from the
rightmost bit of the binary number
– If the last group (at the leftmost position) has less than
four bits, add extra zeros to the left of the group to
make it a four-bit group
• 0110011110101010100111 becomes
• 0001 1001 1110 1010 1010 0111
• Step 2: Replace each four-bit group by its
hexadecimal equivalent
– 19EAA7(16
Converting Decimal to Other Bases
• Step 1: Divide the number by the base you are
converting to (r)
• Step 2: Successively divide the quotients by (r)
until a zero quotient is obtained
• Step 3: The decimal equivalent is obtained by
writing the remainders of the successive division
in the opposite order in which they were obtained
– Know as modulus arithmetic
• Step 4: Verify the result by multiplying it out
Representing Signed Numbers
• Remember, all numeric data is represented inside
the computer as 1s and 0s
– Arithmetic operations, particularly subtraction raise the
possibility that the result might be negative
• Any numerical convention needs to differentiate
two basic elements of any given number, its sign
and its magnitude
– Conventions
• Sign-magnitude
• Two’s complement
• One’s complement
Representing Negatives
• It is necessary to choose one of the bits of the
“basic unit” as a sign bit
– Usually the leftmost bit
– By convention, 0 is positive and 1 is negative
• Positive values have the same representation in all
conventions
• However, in order to interpret the content of any
memory location correctly, it necessary to know
the convention being used used for negative
numbers
Sign-Magnitude
• For a basic unit of N bits, the leftmost bit is
used exclusively to represent the sign
• The remaining (N-1) bits are used for the
magnitude
• The range of number represented in this
convention is –2 N+1 to +2 N-1 -1
Sign-magnitude Operations
• Addition of two numbers in sign-magnitude is
carried out using the usual conventions of binary
arithmetic
– If both numbers are the same sign, we add their
magnitude and copy the same sign
– If different signs, determine which number has the
larger magnitude and subtract the other from it. The
sign of the result is the sign of the operand with the
larger magnitude
– If the result is outside the bounds of –2 n+1 to +2 n-1 –1,
an overflow results
Two’s Complement Convention
•
•
A positive number is represented using a
procedure similar to sign-magnitude
To express a negative number
1.
2.
3.
–
–
Express the absolute value of the number in binary
Change all the zeros to ones and all the ones to zeros (called
“complementing the bits”)
Add one to the number obtained in Step 2
The range of negative numbers is one larger than
the range of positive numbers
Given a negative number, to find its positive
counterpart, use steps 2 & 3 above
Two’s Complement Operations
• Addition:
– Treat the numbers as unsigned integers
• The sign bit is treated as any other number
– Ignore any carry on the leftmost position
• Subtraction
– Treat the numbers as unsigned integers
– If a "borrow" is necessary in the leftmost place,
borrow as if there were another “invisible” onebit to the left of the minuend
One’s Complement
• Devised to make the addition of two numbers
with different signs the same as two numbers
with the same sign
• Positive numbers are represented in the usual
way
• For negatives
– STEP 1: Start with the binary representation of the
absolute value
– STEP 2: Complement all of its bits
One's Complement Operations
– Treat the sign bit as any other bit
– For addition, carry out of the leftmost bit is
added to the rightmost bit – end-around carry
Introduction to C++
C++ Usages & Conventions
• C++ is absolutely case sensitive
–For Instance: A is 97 in ASCII and a is 65
–Remember: in ASCII {, [, and ( are not equivalent
• No keywords in ANSI standard are even partially
uppercase
–‘While’ is not a keyword, ‘while’ is
–Be careful if you define new keywords
• The most common practice in C+++ is to use small
letters of the first part of a variable name and
capitals for the rest of it
Characteristics of a C++ Program
•
•
•
•
•
Comments
Compiler Directives
Functions
Braces
Statements
A Simple C++ Program
Comments
program
Compiler Directive
Main Function
Braces
Statements
program ";
//Simple C++ Program
//
// Purpose: To demonstrate the
// parts of a simple C++
#include <iostream.h>
main ( )
{
cout << "This is a simple
return 0;
}
Comments
• Document what is happening, why it is happening
and other issues
• Commentary is ignored by the compiler
• C++ has inline, block and documentary comments
–Inline comments are within line of code
• Use the // symbols
–Block comments are long comments delimited with /*
and */
Compiler Directives
• Instructions to the compiler rather than part
of the C++ language
– Most common directive is #include
• For Example: #include <iostream.h>
– A .h file is a header file. It serves as a link between
program code and standard C++ code needed to make
programs run
Functions
• A function is a block of code that carries out
a specific task
• Every C++ program has a main function
that executes when a program initiates
– Includes open parenthesis to designate a
function
– Ends with a return 0; statement
Scope Delimiters
• A symbol or pair of symbols used to define
a region or area which is considered a locale
• In programming, many structures need to
have their scope defined because they
should not affect the entire program
– In C++, the symbols ‘{‘ and ‘}’ are used
Semicolons
• There must be a semicolon after every
statement
– To tell the compiler that the statement is
complete
– Function definitions and compiler directives are
exempt
Columns and White Space
• Modern programming languages are free form with
delimiters instead of columns to determine the end
of instructions
–The ; (semi-colon) is the delimiter used in C++
• Use tabs, indents, and blank lines in any manner
that makes code easier to understand
• Many programming instructions become
subordinate to other instructions due to scope and
other restrictions. Formatting code to reflect this
makes it easier to read
Uppercase or Lowercase
• Be careful to use the same combination of
uppercase or lowercase lettering when you
enter source code
• Commands and other reserved words are all
lower case
Variables
• Variables or identifiers are used to hold
information
– Usually mixed case with the first letters small
and the rest starting with a capital
– e.g. theWeight
Literals
• Literals are system commands and other
pieces of information that the compiler
doesn’t understand, and therefore, takes
your word for them
• In C++, literals are enclosed in straight
double quotes " " which is the shift of the
apostrophe
C++ Control Structures
1. "Sequence statements" are imperatives
2. "Selection" is the "if then else" statement
–
AND, OR, NOT and parentheses ( ) can be used for compound
conditions
3. "Iteration" is satisfied by a number of statements
–
–
–
"while"
" do "
"for"
4. The case-type statement is satisfied by the
"switch" statement.
–
CASE statements are used for most non-trivial
selection decisions
Variables
• Used to store values in virtually every
computer program
– Used for “remembering” things during
program execution
– Variables have names, types and values
• Values can change during execution
Data Types - Whole Numbers
• To store whole numbers in a variable, we
use a variable of the int data type.
– An int variable uses 4 bytes of memory.
– An int variable can store a number as low as
-2,147,483,648.
– An int variable can store a number as high as
2,147,483,647.
Data Types - Decimal Numbers
• To store decimal numbers in a variable, we
use a variable of the double data type
– A double variable uses 8 bytes of memory
– A double variable can store a number as low as
-1.7 x 10308
– A double variable can store a number as high
as 1.7 x 10308
– A double variable can store a number with up
to 15 digits of precision (significant digits)
Data Types - Characters
• To store a letter or a single character (such
as #, $, *, etc.), we use a variable of the
char data type.
– A char variable only uses 1 byte of memory.
– A char variable can only hold one letter, digit,
or character.
Data Types – Words / Phrases
• To store a word or phrase (string value), we
use a variable that is a string
– Technically string is not a data type
– You can think of it as a data type for now
Using Variables in C++
• Variables must be declared before they are used in
C++. Get into the habit of doing this at the top of
your functions
char grade;
// a students semester grade
int numStudents; // number of students in our class
double price;
// price of item
string userName; // user's name
Variable Names
• Variable names are technically known as
identifiers
• Choose your own variable names but you must be
careful to use valid ones. Otherwise, the compiler
will be confused and errors will result. When
choosing your variable names:
– do not use keywords that are defined in the
programming language (Reserved Words)
– do not include spaces or other disallowed characters
– do not use more than 31 characters
– do begin the identifier with a letter
• Remember, C++ is completely case sensitive
Initializing Variables
• C++ does not automatically initialize all variables
to the value 0
• If you do not initialize a variable to a certain
value, the variable will have an indeterminate
value that can corrupt the logic of your program
– You should usually initialize your variables at the same
time that you declare them. This is done with a
declaration statement that is also an initialization
statement
int numberOfPizzas = 3;
double monthlyCarPayment = 685;
char letterGrade = 'A';
string firstName = "Paul";
Constants
• Sometimes you need to use the same value
many times throughout a program. In this
case, it is proper to use a constant rather
than a variable
• Constants allow you to give a name to a
value used several times in a program
• The value never changes
Type Compatibilities
• You cannot store a value of one type in a
variable of a different type – a type
mismatch occurs
• You can typecast
– Supply the name of the data type you want to
use to interpret the variable followed by the
variable placed in parenthesis
• C = PI * float (diameter);
The Assignment Operator
• The assignment operator is the equal symbol (=)
• The assignment operator changes the value of the
variable to its left after evaluating the expression
on its right
• For example:
– sum = 3 + 1000;
• The variable sum ends up with the value 1003
–
–
–
–
salary = 40000;
poundsPressure = 15 + 12;
sum = original + 300;
salary = salary + raise;
Multiple Assignments
i = j = k = 10;
// initializes all three variables to the value, 10
This statement is equivalent to:
i = 10;
j = 10;
k = 10;
Common Arithmetic Operators
+
*
/
%
for addition
for subtraction
for multiplication
for division
for modulus (like finding the remainder
of a division problem)
Compound Operators
• Example 1:
j += 1;
// is the same as j = j + 1
• Example 2:
total /= 2;
// is the same as total = total / 2;
Increments and Decrement
• The incrementing (++) and decrementing (--)
operators are useful at times if used carefully
• counter++;
• is equivalent to counter = counter + 1;
1;
and
counter +=
and
counter -= 1;
• counter--;
• is equivalent to counter = counter - 1;
• Use the incrementing and decrementing operators
with variables in statements such as these, that is
with no other operators or code except the variable
name that is being incremented or decremented.
Order of Operations
• Obey the order of operations
– Perform the following mathematical operations in this
order: Parentheses, Exponentiation, Multiplication,
Division, Addition and Subtraction
– Multiplication and division are of equal precedence, so you
must work left to right within an algebraic expression
– The modulus operator (%) has the same precedence as * and
/ but is higher in precedence than + and -.
– Addition and subtraction work left to right within an
algebraic expression as well
– Use parentheses if necessary to override the order of
operations in order to produce the desired result
Decision Making In Computers
• A circuit quite simply allows one out of two
choices to be made depending on its inputs
• When decisions are made in a computer program,
they are simply the result of a computation in
which the final result is either TRUE or FALSE
• The value zero (0) is considered to be FALSE by
C++. Any positive or negative value is considered
to be TRUE
Using Relational Operators
• Relational operators provide the tools with
which programs make decisions with true
and false evaluations
==
equal to NOTE: this is two equals symbols next to each
other, not to be confused with the assignment operator, =
>
greater than
<
less than
>=
greater than or equal to
<=
less than or equal to
!=
not equal to
Order of Logical Operations
•
Logical operators may be mixed within
evaluation statements but the following order of
preference must be respected:
1. NOT operator (!)
2. AND operator (&&)
3. OR operator (||)
• Short-circuit evaluation in C++ allows the
compiler to quickly evaluate a logical expression
in some cases without having to completely
evaluate each part of the expression
Complete order of operations
• The complete order of operations including all of
the arithmetic, relational, and logical operators
including all of the basic arithmetic, relational, &
logical operators is:
*, /, %
+, <, >, <=, >=, ==, !=
!
&&
||
Color Coding in Visual C++ Editor
• Comments are green and are ignored by the
compiler
• All ANSI keywords are coded in blue
• Other code is in plain black
– Compiler keywords like cin and cout are also
shown in black
C2065: Undeclared Identifier
1. Several things may produce this error
•
•
•
•
Misspelling a keyword
Misspelling a programmer defined name (identifier)
Misuse of case in a keyword or identifier
Failure to declare an identifier