CPS120 Introduction to Computer Science - PowerPoint PPT Presentation

About This Presentation
Title:

CPS120 Introduction to Computer Science

Description:

CPS120 Introduction to Computer Science Final Exam Review – PowerPoint PPT presentation

Number of Views:151
Avg rating:3.0/5.0
Slides: 106
Provided by: PaulJM8
Learn more at: http://space.wccnet.edu
Category:

less

Transcript and Presenter's Notes

Title: CPS120 Introduction to Computer Science


1
CPS120 Introduction to Computer Science
  • Final Exam Review

2
Common Flowchart Symbols
3
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

4
Truth Tables
  • Use this truth table to determine the results of
    the logical operators. In this table, 1
    represents TRUE and 0 represents FALSE.
  • Note that the ! symbol (the logical NOT operator)
    changes a TRUE to a FALSE.



1

0

1




1

1

1



1

1

1





5
Sample Switch Structure
  • switch (character_entered)
  • case A
  • cout ltlt The character entered was A.\n
  • break
  • case B
  • cout ltlt The character entered was B.\n
  • default
  • cout ltlt Illegal entry\n

6
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 compilers
    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

7
Compiling and Debugging
  • Executable code will not be created until you
    correct all of the syntax errors in your source
    code

8
Computer Mathematics
9
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

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

11
Decimal Equivalents
  • Assuming the bits are unsigned, the decimal value
    represented by the bits of a byte can be
    calculated as follows
  • Number the bits beginning on the right using
    superscripts beginning with 0 and increasing as
    you move left
  • Note 20, by definition is 1
  • Use each superscript as an exponent of a power of
    2
  • Multiply the value of each bit by its
    corresponding power of 2
  • Add the products obtained

12
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

13
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

14
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

15
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

16
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 n1 to
    2 n-1 1, an overflow results

17
Ones Complement
  • 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

18
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

19
Twos Complement Convention
  • A positive number is represented using a
    procedure similar to sign-magnitude
  • To express a negative number
  • 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

20
Twos 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
    one-bit to the left of the minuend

21
Introduction to C
22
Variable Names
  • Choose your own variable names but you must be
    careful to use valid ones
  • 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 255 characters
  • do begin the identifier with a letter

23
Declaring Initializing Variables
  • In C all variables must be declared before they
    can be used.
  • Declare a variable by indicating its type and
    name
  • int myVariable
  • C does not automatically initialize all
    variables to the value 0
  • If you do not initialize a variable, the variable
    will have an indeterminate value.
  • Initialize your variables at the same time that
    you declare them.
  • int myVariable 0

24
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

25
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

26
Common Arithmetic Operators
  • for addition
  • - for subtraction
  • for multiplication
  • / for division
  • for modulus (like finding the remainder
    of a division problem)

27
Increments and Decrement
  • The incrementing () and decrementing (--)
    operators are useful at times if used carefully
  • counter
  • is equivalent to counter counter 1
    and counter 1
  • counter--
  • is equivalent to counter counter - 1
    and 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.

28
Using Relational Operators
  • Relational operators provide the tools with
    which programs make decisions

equal to NOTE this is two equals
symbols next to each other, not to be confused
with the assignment operator, gt greater
thanlt less thangt greater than or
equal tolt less than or equal to!
not equal to
29
Order of Logical Operations
  • Logical operators may be mixed within evaluation
    statements but the following order of preference
    must be respected
  • NOT operator (!)
  • AND operator ()
  • OR operator ()

30
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
  • , /,
  • , -
  • lt, gt, lt, gt, , !
  • !

31
String Literals
  • A string literal is a sequence of characters that
    is used in a C program between double quotes
    such as in the statementcout ltlt "Hello
    world!"where "Hello world!" is the string
    literal
  • Similar to a constant
  • Ends with an invisible null terminator (ASCII 0)
  • Represented as \0

32
Character Arrays
  • Used to store strings that change as the program
    runs
  • Unlike string literal
  • An array is a group of variables of the same data
    type that appear together in memory
  • In this case each variable holds a character and
    the last variable in the string holds the null
    terminator (/0)

33
Using Strings In Programs
  • In order to use string variables within any
    Cprogram, you must use the compiler directive
  • include ltstring.hgt
  • using namespace std

34
Input Operations
  • The operator gtgt is known as the input operator.
    It is also known as the extraction operator
  • You use the input operator in statements like,
  • cin gtgt numItems
  • which would allow the user to input a value to
    be stored in the variable numItems.

35
Complexities of Word Input
  • Some things are done automatically with gtgt
  • get does not skip over line breaks and spaces
  • If the user enters a string longer than the
    length specified in the call to the get function,
    the remaining characters are left in the input
    stream
  • Get always ignores the new line character (\n)
    and leaves it in the stream
  • Use the ignore function to flush the contents of
    the input stream
  • cin.ignore(80, \n)

36
Using setf and unsetf
  • Each stream has format options that can be
    changed
  • OPTION DESCRIPTION
  • left Left-justifies the output
  • right Right-justifies the output
  • showpoint Displays decimal point and trailing
    zeros for floats
  • uppercase Displays e in scientific as E
  • showpos Displays a leading plus sign
  • scientific Displays floating point number
    scientifically
  • fixed Displays floating-point in normal notation

37
Using Manipulators
  • You must include the ltiomanip.hgt header file at
    the top of your program in order to use the
    setprecision, setw, and other manipulators. You
    must use place the following compiler directive
    at the top of your program.include ltiomanip.hgt
  • I/O manipulators are placed directly in the
    output statement
  • cout ltlt setprecision(2) ltlt price ltlt \n

38
Decision Making in C
  1. if statement
  2. switch statement
  3. ? conditional operator statement
  4. goto statement

39
IF-THEN
Test condition p
40
IFELSE
41
General Form
  • if (test expression)
  • True-block statements
  • else
  • False-block statements
  • next statement

42
General Form
  • if (test expression)
  • True-block statements
  • else
  • False-block statements
  • next statement

43
Switch Structure
  • The switch structure is a multiple-selection
    structure that allows even more complicated
    decision statements than a two-way if/else
    structure allows.
  • Only variables with the INT or CHAR data types
    may be used in the control expressions (i.e.
    parentheses) of switch statements.
  • Single quotes must be used around CHAR variables
  • Single quotes are NOT used around the integer
    values

44
Iteration
  • A program loop is a form of iteration. A computer
    can be instructed to repeat instructions under
    certain conditions.

45
Syntax of a for Loop
  • for (initializing expression control expression
    step expression) // one or more
    statements
  • The initializing expression sets the counter
    variable for the loop to its initial value.
  • The control expression ends the loop at the
    specified moment.
  • The step expression changes the counter variable
  • Semi-colons, not commas, divide the expressions

46
WHILE Loop
47
While Loop Syntax
  • while (control expression) // one or
    more statements
  • The control expression must evaluate to TRUE in
    order for the while loop to iterate even once

48
DO WHILE Loop
Loop statement a
49
Do While Syntax
  • do // body statements would be placed
    herewhile (control expression)
  • Don't forget to include the required semicolon
    after the control expression

50
In Summary
  • Loops
  • for -- fixed number of loops
  • while -- may never be run
  • do while -- always run once
  • continue causes while, do while, and for loops
    to start over
  • break causes while, do while, for and switch
    statements to end

51
An Example of A Function
  • include ltiostream.hgt
  • void printMyMessage(int numOfTimes) //
    PROTOTYPE and NAME
  • int main( )
  • int userInput 0
  • cout ltlt "Enter a number between 1 and 10 (0 to
    Exit) "
  • cin gtgt userInput
  • if (userInput ! 0)
  • printMyMessage (userInput) // CALL
    STATEMENT WITH ACTUAL PARAMETER
  • else
  • cout ltlt "Thanks, Bye!"
  • return 0
  • // end of main
  • void printMyMessage(int numOfTimes) // FUNCTION
    HEADER W/ RETURN TYPE ACTUAL PARAMETER

52
Scope of Variables
  • The scope of a variable is the area in which it
    can be legally referenced
  • Variables are either global or local in nature
  • Global variables can be used in any function
    throughout the program.
  • Local variables are ones that are declared inside
    of a function, including main. They cannot be
    used or referred to in other functions
  • It is not wise to use global variables any more
    than you have to

53
Passing Data
  • Data is passed to functions as arguments
  • When a function is "called" by the main function
    one or more arguments are passed to the function
  • On the receiving end, the function accepts these
    arguments
  • The variable names of the arguments from the
    "calling" function do not have to be the same as
    the names in the "called" function.
  • The data types of the arguments and the
    parameters should match exactly

54
Required Compiler Directives
  • Any program that uses file pointers must include
    the fstream.h header file with the compiler
    directive,include ltfstream.hgtat the top of
    the program

55
Opening Output Files
  • Opening a sequential-access file
  • ofstream outfile
  • ofstream is a C keyword indicating the type of
    pointer that you created
  • outfile is simply the programmer's chosen name
    for the file pointer (and can be any valid name)
  • Open the file "mydata.txt" that is stored on your
    PC's hard drive
  • outfile.open("mydata.txt", iosout)

56
Opening Input Files
  • Declare a file pointer as an ifstream object
    with
  • ifstream infile
  • ifstream is a keyword and infile is the name for
    the file pointer.
  • infile is simply the programmer's chosen name for
    the file pointer (and can be any valid name)
  • Open the actual file for reading with
  • infile.open("mydata.txt", iosin)

57
Writing Output
  • To write data to a sequential-access data file
    you would use a statement like
  • outfile ltlt "John Doe" ltlt endl
  • to print that name to the next line in the data
    file pointed to by the file pointer, outfile.

58
Appending Data
  • Adding data to the end of a sequential-access
    data file is called appending
  • Open the file using the iosapp stream operation
    mode as in
  • outfile.open("myfile.txt", iosapp)
  • where the app is short for append.

59
Detecting the End of a File.
  • Use the eof function to determine whether the end
    of a sequential-access file has been reached.
  • This function returns a 1 (true) if an attempt
    has been made to read past the end of the file.
  • do
  • infile gtgt x
  • if ( !infile.eof( ) )
  • cout ltlt x ltlt endl
  • while ( !infile.eof( ) )

60
Pointer Use in C.
  • A pointer is a variable or constant that holds a
    memory address
  • a) Hexadecimal numbers are used for representing
    memory locations

Address Value Name 216793 216794 216801 iptr
216801 3 i 216802
61
Intializing Pointers
  • Declare pointers before use, as with other
    variables.
  • Each variable being declared as a pointer must be
    preceded by an asterisk ().
  • Initialize pointers before use to a 0, NULL or an
    address to prevent unexpected results

62
Pointer Operators
  • is the address operator which returns the
    address of its operand
  • is the indirection operator or dereferencing
    operator and returns the value to which the
    operand (pointer) points.
  • sizeof - used to determine the size of an array
    during program compiliation

63
Structures
  • Structures group variables together in order to
    make one's programming task more efficient.
  • Any combination of variables can be combined into
    one structure.
  • This is a useful and efficient way to store data.
  • struct Student
  • string socSecNum
  • string lastName
  • string firstName
  • int pointsEarned
  • double gpa

64
Arrays A Definition
  • A list of variables accessed using a single
    identifier
  • May be of any data type
  • Can be single or multi-dimensioned
  • Vector classifications are object-oriented
    representations of arrays

65
Declaring an Array
  • To declare an array before it is used in the body
    of your program, you must use a statement like
  • int scores10
  • In this case, scores can store up to 10 different
    integer values.
  • The positions of the array are identified by
    their index positions which run from 0 to 9 (not
    1 to 10.)
  • Each one of the 10 variables in scores is called
    an element

66
Initializing an Array
  • If you wish to initialize each element of an
    array to a specific value, you can use the
    statement,int scores 65, 76, 45, 83, 99
  • You don't even have to specify a size of the
    array in this case since the initialization
    statementwould cause the compiler to declare an
    array of size 5 since there are five values in
    the set of curly braces

67
Declaring a Multi-dimensional Array
  • To declare an array of integers called
    studentGrades to be a 2-dimensional array with 3
    rows and 4 columns, you would use the
    statementint studentGrades3 4where the
    first integer value is used to specify the number
    of rows in the array and the second value
    specifies the number of columns
  • Think of remote control

68
Initializing a Multi-dimensional Array
  • You can initialize the 2-dimensional array when
    you declare it by using commas and braces
    appropriately
  • int studentGrades3 4
  • 1, 2, 3, 4,
  • 5, 6, 7, 8,
  • 9, 10, 11, 12

69
Other Programming Concepts
70
Approaches to Sorting
  • There are two basic approaches to sorting data
  • The incremental approach
  • The divide and conquer approach.
  • Using the incremental approach, one sorts the
    whole list at once
  • The divide and conquer approach splits the list
    up into parts and sorts each part separately.

71
Selection Sort
Example of a selection sort (sorted elements are
shaded)
72
The Insertion Sort
  • The insertion sort is incremental in nature.
  • This is similar to the way a person usually
    organizes a hand of playing cards.
  • The insertion sort is relatively quick for small
    lists that are close to being sorted

73
Insertion Sorting
Mary Mary Gerri
Terry Gerri Kari
Gerri Kari Harry
Kari Harry Barry
Harry Barry Mary
Barry Terry Terry
74
Bubble Sort
  • Starting with the last list element, we compare
    successive pairs of elements, swapping whenever
    the bottom element of the pair is smaller than
    the one above it

75
Bubble Sort
Example of a bubble sort
76
Understanding the Quick Sort
  • The quicksort is a divide and conquer algorithm
    and is more efficient than incremental sorts. It
    can be difficult to code though since it uses
    recursion or stacks.
  • The original list is partitioned into two lists.
  • One of the lists contains elements that are
    greater than the first original element.
  • The second list contains elements that are less
    than or equal to the first original element.

77
Quicksort
78
Sequential Searching
  • Although there are more efficient ways to search
    for data, sequential searching is a good choice
    of methods when amount of data to be searched is
    small.
  • You simply check each element of an array
    position by position until you find the one that
    you are looking for.
  • In any search, the item upon which the search is
    based is called the key and the field being
    searched is called the key field.

79
Binary Search
  • A binary search looks for an item in a list using
    a divide-and-conquer strategy
  • Binary search algorithm assumes that the items in
    the list being searched are sorted
  • The algorithm begins at the middle of the list in
    a binary search
  • If the item for which we are searching is less
    than the item in the middle, we know that the
    item wont be in the second half of the list
  • Once again we examine the middle element (which
    is really the item 25 of the way into the list)
  • The process continues with each comparison
    cutting in half the portion of the list where the
    item might be

80
Binary Search
  • 0 Ant
  • 1 Cat
  • 2 Chicken
  • 3 Cow
  • 4 Deer
  • 5 Dog
  • 6 Fish
  • 7 Goat
  • 8 Horse
  • 9 Monkey
  • 10 Snake

Trace of the binary search
81
Key Computing Concepts
82
What Is a Network
  • A network is a group of connected computers that
    allow people to share information and equipment

83
Small Networks
  • 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

84
The Networking Revolution
  • Computer networks have permanently altered the
    world of computing with the client/server model

Client/Server interaction
85
Types of Networks
Various network topologies
  • A bus technology called Ethernet has become the
    industry standard for local-area networks

86
Ethernet
  • A bus technology called Ethernet has become the
    industry standard for local-area networks
  • Most popular and least expensive solution
  • Each computer waits for a pause before sending
    information
  • Collisions between information often occur
  • Computers wait a moment, then resend

87
Packet Switching
  • To improve the efficiency of transferring
    information over a shared communication line,
    messages are divided into fixed-sized, numbered
    packets
  • Network devices called routers are used to direct
    packets between networks

Messages sent by packet switching
88
TCP/IP
  • TCP stands for Transmission Control Protocol
  • TCP software breaks messages into packets, hands
    them off to the IP software for delivery, and
    then orders and reassembles the packets at their
    destination
  • IP stands for Internet Protocol
  • IP software deals with the routing of packets
    through the maze of interconnected networks to
    their final destination

89
Firewalls
  • A firewall is a machine and its software that
    serve as a special gateway to a network,
    protecting it from inappropriate access
  • Filters the network traffic that comes in,
    checking the validity of the messages as much as
    possible and perhaps denying some messages
    altogether
  • Enforces an organizations access control policy

90
Network Addresses
  • An IP address can be split into
  • network address, which specifies a specific
    network
  • host number, which specifies a particular machine
    in that network

An IP address is stored in four bytes
91
Domain Name System
  • A hostname consists of the computer name followed
    by the domain name
  • orchard.wccnet.org is the domain name
  • A domain name is separated into two or more
    sections that specify the organization, and
    possibly a subset of an organization, of which
    the computer is a part
  • Two organizations can have a computer named the
    same thing because the domain name makes it clear
    which one is being referred to

92
Internet Fundamentals
  • Dates from DARPA in the 1960s
  • Consists of thousands of connected networks
    around the world
  • Each organization on the Internet is responsible
    for maintaining its own equipment
  • These organizations allow you to pass-through
    their nets
  • Designed to provide multiple routing to bypass
    disabled computers

93
The World Wide Web
  • The Web is an infrastructure of distributed
    information combined with software that uses
    networks as a vehicle to exchange that
    information
  • A Web page is a document that contains or
    references various kinds of data, such as text,
    images, graphics, and programs
  • Web pages also contain links to other Web pages
    so that the user can move around as desired

94
Web Browser
Figure 16.2 A browser retrieving a Web page
95
Create Publish Web Pages
  • HyperText Mark-up Language is a computer code
    used to create Web pages
  • There are many programs available, called visual
    editors which can help you create Web pages
    without having to learn HTML
  • Publishing your pages loaded to an addressable
    server

96
Interactive Web Pages
  • When HTML was first developed, there was no way
    to interact with the information and pictures
    presented in a Web page
  • As users have clamored for a more dynamic web,
    new technologies were developed to accommodate
    these requests
  • Many of the new ideas were offshoots of the newly
    developed Java programming language

97
XML
  • XML is a metalanguage
  • A metalanguage is a language for talking about,
    or defining, other languages

98
Object-Oriented Paradigm
  • Data should be placed inside the objects and that
    these objects should communicate with each other
    in the form of messages

99
Thinking Object-Oriented
  • Think in an object-oriented way
  • E.g. an answering machine encapsulates the
    functions of an answering machine with the data
    (messages).
  • The buttons are the equivalent of sending
    messages to the machine

100
Encapsulation
  • Encapsulation is a language feature that enforces
    information hiding
  • Both data and methods are contained within an
    object

101
Inheritance
  • Inheritance fosters reuse by allowing an
    application to take an already-tested class and
    derive a class from it that inherits the
    properties the application needs

102
Polymorphism
  • Polymorphism the ability of a language to have
    duplicate method names in an inheritance
    hierarchy and to apply the method that is
    appropriate for the object to which the method is
    applied

103
Designing A Class
  • A class is a language construct that is a pattern
    for an object and provides a mechanism for
    encapsulating the properties and actions of the
    object class
  • We instantiate the class
  • Private and public are called access modifiers

104
OOP Advantages Reusability
  • Reusability is a major benefit of object-oriented
    programming

105
Public vs. Private
  • Private Cannot be accessed outside the object
  • Public Can have access to all the variables and
    functions
  • public
  • // constructors
  • circle() // default
    constructor
  • circle(const circle ) // copy constructor
  • // member functions
  • void SetRadius(float)
  • double Area()
  • private
  • // data
  • float radius
Write a Comment
User Comments (0)
About PowerShow.com