Title: CPS120 Introduction to Computer Science
1CPS120 Introduction to Computer Science
2Common Flowchart Symbols
3Syntax 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
4Compiling and Debugging
- Executable code will not be created until you
correct all of the syntax errors in your source
code
5Introduction to C
6Variable 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
7Declaring 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
8Constants
- 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
9The 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
10Common Arithmetic Operators
- for addition
- - for subtraction
- for multiplication
- / for division
- for modulus (like finding the remainder
of a division problem)
11Increments 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.
12Using 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
13Order 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 ()
14Complete 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, , !
- !
-
-
15String 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
16Character 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)
17Using Strings In Programs
- In order to use string variables within any
Cprogram, you must use the compiler directive - include ltstring.hgt
- using namespace std
18Input 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.
19Decision Making in C
- if statement
- switch statement
- ? conditional operator statement
- goto statement
20IF-THEN
Test condition p
21IFELSE
22General Form
- if (test expression)
-
- True-block statements
-
- else
-
- False-block statements
-
- next statement
23Switch 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
24Iteration
- A program loop is a form of iteration. A computer
can be instructed to repeat instructions under
certain conditions.
25Syntax 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
26WHILE Loop
27While 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
28DO WHILE Loop
Loop statement a
29Do While Syntax
- do // body statements would be placed
herewhile (control expression) - Don't forget to include the required semicolon
after the control expression
30In 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
31An 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 -
32Scope 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
33Required 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
34Opening 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)
35Opening 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)
36Writing 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.
37Appending 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.
38Detecting 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( ) )
39Arrays 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
40Declaring 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
41Initializing 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
42Declaring 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
43Initializing 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
-
44Key Computing Concepts
45What Is a Network
- A network is a group of connected computers that
allow people to share information and equipment
46Small 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
47The Networking Revolution
- Computer networks have permanently altered the
world of computing with the client/server model
Client/Server interaction
48Types of Networks
Various network topologies
- A bus technology called Ethernet has become the
industry standard for local-area networks
49Ethernet
- 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
50Packet 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
51TCP/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
52Firewalls
- 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
53Network 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
54Domain 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
55Other Programming Concepts
56Approaches 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.
57Selection Sort
Example of a selection sort (sorted elements are
shaded)
58The 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
59Insertion Sorting
Mary Mary Gerri
Terry Gerri Kari
Gerri Kari Harry
Kari Harry Barry
Harry Barry Mary
Barry Terry Terry
60Bubble 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
61Bubble Sort
Example of a bubble sort
62Understanding 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.
63Quicksort
64Sequential 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.
65Binary 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
66Binary 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
67Object-Oriented Programming
68Object-Oriented Paradigm
- Data should be placed inside the objects and that
these objects should communicate with each other
in the form of messages
69Thinking 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
70Encapsulation
- Encapsulation is a language feature that enforces
information hiding - Both data and methods are contained within an
object
71Inheritance
- 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
72Polymorphism
- 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
73Designing 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
74OOP Advantages Reusability
- Reusability is a major benefit of object-oriented
programming
75Public 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