Computer Science II

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 152

Computer Science II

C++
Comments in C++
• Comments – information about a program and
its design included within the program.
• Two comment symbols in C++
– // end of line comment from the // to the end of that
line is a comment
– /* */ C-style comment
• May be anywhere in a program
• May contain any symbol except */
• May be several lines
• All text between /* and */ are the comment
Preprocessor Directive Example
• Preprocessor directives are used to include library
files in a program.
• Preprocessor directives can also set rules for
conditional compiling of a program or file.
• Preprocessor directives begin with # symbol
#include
String Data Type
• String – the data type used in C++ to hold a
series of characters such as words, names,
phrases, etc.
• ex. string name;
name = “Butch Bulldog”;
string address = “2825 Government St.”;
• The string type is not available in C and in
older versions of C++
Structure of the main function
int main()
{ declarative, imperative,
and control statements
return 0;
}

Declarative Statements – a statement that declares a variable or constant name

Imperative Statement – a statement that instructs the computer to do some


actions

Control Statement – a statement that alters the flow of control in a program


Important C++ Items
• All Compiler directives The main function
start with # • () are part of the name
• All programs must have a of the main function –
main function they are required
• All reserve words in C++ • The main() function
are lower case only should be of type int
• C++ identifiers are case • The main function
sensitive should end with
• All C++ statements end return 0;
with a semicolon
Constants, Variables, Data types and
Identifiers
• Identifier – a word used to name something in
a program
• Syntax
– Start with a letter
– Succeeding characters may be letter, digit, or
underscore
– May be any length
– Case sensitive
Cont.
• Data Type - a class or kind of data
• Built in types:
Type Range Bytes
Char -128 - 127 1 byte
Int -32768 - 32768 2 bytes
-2,147,483,648 - 4 bytes
2,147,483,648
Double
string
Data Types in C++
Name Range Size
float 1.4x10^-45 -> 3.4x10^38 4 bytes

double 4.9x10^-324 -> 1.8x10^308 8 bytes

Long double Varies with installation 10, 12, or


16 bytes
string C++ style class that stores a
series of up to 1024 characters
Char* C style method of storing a
series of characters –
supported only in legacy code
Declaring Variables
• Variables must be declared before they are
used.
• Best place is the beginning of the main
function.
• Syntax
Datatype variablename;
Assignment Statment
• Used to give a value to a variable
• Syntax ( variable = expression )

Declaring Constants
• Declared with const
• Syntax
const typename identifier=value;
I/O in C++
• Input and output in C++ are handled through the use
of streams.
• A stream is a series of characters in ascii format.
• Program must include library file iostream
#include <iostream>
• Isotream’s output stream goes to monitor, its input comes
from the keyboard
• cout is the name of the output stream
• cin is the name of the input stream
• Both require a direction operator as part of syntax
The cin Command
• Syntax cin >> variable;
• >> is the extraction operator
• Cin may have multiple variables
• Each variable must have an extraction
operator
Type Conversion
• Promotion - the automatic conversion of a value
from a less inclusive type to a more inclusive type.
– Ex. Double d=6; //6 converted to 6.0 then stored
– Always possible
– No negative side effects
– Conversion is implicit
• Coercion – the automatic conversion of a value from a
more inclusive type to a less inclusive type
– Not always possible
– May have unwanted side effects such as loss of accuracy
Math Shortcuts
Symbol Example Meaning
+= x+=3 x=x+3
-= x-=3 x=x-3
*= x*=3 x=x*3
/= x/=3 x=x/3
%= x%=3 x=x%3
++ x++ x=x+1
-- x-- x=x-1
Lagniappe Items
• System (“pause”)
– Function call that causes the program to stop and wait
for enter to be pressed by calling on the DOS pause
command.
• System(“cls”)
– Function all that causes the output window to be
cleared by calling on the DOS clear screen
command(cls)
• The system() function is found in the stdlib.h
library
Special Characters in C++
Sequence Meaning
\b Backspace
\t Tab character
\n New line
\’ Apostrophe
\” Quotation marks
\\ Backslash
\? Quotation marks
Math functions
• Located in the header file math.h
Math Functions
powers
• Sqrt() square root
• Log() natural logarithm
• Exp() e raised to the power of the argument –
exp is inverse of log()
• Log10() common logarithm
• Pow10()10 raised to the power of the
argument – inverse of log10()
• Pow(x,y) raises x to the power of y
Math Functions
Absolute Value
• abs() absolute value of an integer

• labs()absolute value of a long integer

• fabs() floating point absolute value


Math Functions
Type Conversions
• ceil() smallest integer greater than or equal to
the argument.

• floor() largest integer less than or equal to


the argument
Random Number Functions
• Random Numbers – a set of 1 or more integer
values in no particular order
• Sets of random number used in the simulation
of real events, in games, fractal graphics, etc.
• Pseudorandom Numbers – a set of integers in
which the next value in the set is calculated
from the current element. In C++:
Random Number Functions
• Requires #include<stdlib.h>
• Rand() – returns a peusdorandom integer
between 0 and RAND_MAX
• Srand(int) – C++ function that will seed the
random number generator with a value
provided by the statement.
String Operations
• Operation Symbol Example
• Printing << cout<<word;
• Reading >> cin>>”August”;
• Assignment = month=“August”;
• Concatenation + name=first+last
• Appending += name+=last;
• Note 1: concatenation and appending
Reading Multiword Strings
• Extracting strings from an input stream with >> is
cut off at the first white space.
• iostream provides a function that will extract a
multiple word string along with its white spaces
called getline().
• syntax: getline(cin,str);
where str is a string variable
• getline() takes all characteristics from the keyboard
up to the new line character. The new line
character is extracted and thrown away.
.ignore()
• .ignore() – is the function that will cause a
series of characters in a stream to be removed
and thrown away.
• Syntax cin.ignore(int, char);
int is an integer indicating the maximum
number of characters to be removed, and char is
a stopping character, causing the removal of
character to end if one of these is removed
String Functions
• Those functions designed to perform work
upon string variables
• Typical syntax
– stringname.functionname(argument)
– ex. len=person.length();
length()
• length() – returns the number of characters in
the invoking string.
• ex. string name = “BRHS Bulldogs’
int len = name.length()
//len gets 13
substr()
• substr() – the function that will return a string
consisting of characters from the invoking
string.
• substr() takes 2 parameters, the starting point
and the number of characters to copy.
• the return type for the substr() is string
• ex. word = “programming”;
w=word.substr(3,4); //w gets gram
find()
• find() – returns the location of the first
occurrence of the search value provided
• if search value is in the string more than once,
the position of the first occurrence is returned
• if search value is not in the string, the npos
value is returned
Insert()
• Insert() is the function that will place a given
string within the invoking string, beginning at
the location indicated.
• Requires 2 arguments: an integer position and
a string or char
• ex.1 string sc = “Baton Rouge High”;
sc.insert (11,” Magnet”);
erase()
• erase() removes characters from a string

• syntax:
• string.erase (position, number of characters to
be removed)
replace()
• replace()

• syntax:
sc.replace (12,7,”Junior”)
(position, # of characters to be removed, new)
Format Specifiers
Specifier Meaning
%s String
%d An integer in base 10
%o An integer in base 8
%x or %X An integer in base 16 x uses a-f, X uses A-F
%f Decimal numbers in floating point notations – 6 digits after the
decimal
%e Decimal numbers in exponent(scientific) notation
%g Decimal numbers in either floating point or exponent notation
– no trailing 0’s
%c A character
%% Insert a % sign
Creating Formatted Strings
• C and C++ create formatted style strings using the
function sprintf()
• sprintf() is found in <stdio.h>
• Syntax:
sprintf() (C_string, template string, list of values);
• ex.
char line [80];
int a=10, b=12
sprintf(line, “x=%d
printf()
• printf ("Width trick: %*d \n", 5, 10);
Format Specifier
• All begin with %
• All end with a letter defining the type of data
to be inserted
Function
• A function is a nearly independent segment of
code that is performed when called by the
program; a subprogram.
• Used For
– Making programs modular
– Support top down design
– Support bottom up testing
– Information hiding
– Reuse of code
Calling Functions
• Functions are called by using their names as a
command on the right hand side of an
assignment
ex. r=cube(x)
Void Functions
• A void functions is a functions that does not
return a value.
• Data type of void is used
• Void functions cannot contain a return
statement.
Programming With Functions
• Always look for ways to reuse the code – think
general use.
• Any routine that needs to be performed in more
than one place within a program should be
coded as a function.
• Any process that is a nearly independent task
within the solution should be written as a
function.
• Any clearly identifiable step in the sol
Documenting Functions
• Each function is to have a comment heading in which
the action and signature of the function is explained.
• This heading should have:
– the action of the function
– the parameters of the function
– the return type of the function
• Along with the heading the body of the function
should contain comments for section headings or
non-descriptive variables used in the function.
• http://www.sqlite.org/lang_corefunc.html
http://www.cplusplus.com/forum/general/4011/
Scope of Identifiers
• All identifiers in C++ have block scope.
– Block – a series of statements between { }
– Only accessible within block
– Local identifiers
• Global Identifiers – any identifier known
throughout a program.
– Declared outside of all blocks
– Accessible in all functions
– Don’t use global variables, can cause side effects
Activation Records and the Run-Time Stack

• Activation Record – A copy of a function’s


parameters, variables and position counter
placed into the Run-Time stack when the
function is called.

• Run-Time Stack - A segment of memory where


active functions are placed. Execution occurs in
the function that is “on the top” of the stack.
Additional Terms
1. Functional abstraction – process of considering
what a function does, not how it does it
2. Information hiding – condition in which the user
of a module does not know the implementation
details for the module
3. Preconditions – state of the machine that must
exist in order for a module to execute correctly
4. Postconditions – state of the machine that exists
when a module has terminated
More additional terms
5. Interface – a shared boundary between two
systems.
6. Overloading – the process
Function Overloading
• Function overloading – two or more functions
with the same name, but different parameter
list
• Overloading is used to allow several functions
that perform the same basic operation to
share a common name.
Library
• Library – A collection of identifier declarations
and function definitions stored in secondary
memory.
– A Library may be written in a single file or in two
separate files
1. A file containing the functions completely coded. The
file name will have an extension of .h
2. A header file with .h extension containing the function
prototypes, and an implementation file with a .cpp
extension containing the code for the functions.
Compiler Directives
• Library file will contain computer directives
• #include used to include any libraries upon which the
current library depends
• #define used to create an identifier name representing
a block of code.
• #ifndef conditional item that causes the compiler to
compile or skip a block of code based upon the given
name.
• #endif directive used to mark the end of an #ifndef
block
Flow Control
• Flow of Control in a program refers to the order in
which statements are executed.
• Types of control flow:
– Sequential
– Functional (procedural)
– Selection
– Iteration
• C++ supports all 4
• Control Statements – commands that alter the flow of
control in a program.
If () statement
• if() is the statement used to execute or skip a
statement or block.
• Syntax
if(boolean expression)
Action of if()
boolean expression is evaluated

true – statement or block is performed

false – statement or block is skipped


Block
• Block – a series of one or more statements
enclosed within braces
Ex. {
a=b*c;
d=b+c;
r=a/d;
cout << r << endl;
}
Boolean Expression
• A boolean expression is an expression that has a
value of true or false
• Also called a logical expression
• Boolean expressions may consist of:
– a single bool (or int) variable
– a call to a function of type bool
– a comparison of two values using a relationship symbol
– two boolean expressions joined by a boolean operator
– the not operator followed by a boolean expression
Relationship Symbols
• Used to create boolean • == is equal to
expressions • > is greater than
• Can be used to compare • < is less than
an int, double, char, or • != is not equal to
string to same type
• >= is greater than or
item.
equal to
• Can be used to compare
• <= is less than or equal
compatible types. ex.
to
int to double
Boolean Operators
Symbol Meaning Example

&& and (a==0 && b ==0)

|| or (ch==‘y’ || ch==‘Y’)

! not (!done) // done is bool


If () else statements
• Command that will execute one of two
statements or blocks. The selection of the
statement performed is based on a boolean
expression.
• Syntax
If (boolean expression)
statement or block;
else
statement or block;
Nested if () else
• nested if ()else is placing an if () else as the
statement in an else
• syntax
if( )
statement;
else if ( )
statement;
else
statement;
Short Circuit Evaluation
• Short circuit evaluation is the process of
evaluating a boolean expression only up to the
point that the result is obvious.
• false && anything is false
• C++ uses short circuit evaluation
Switch Statement
• Switch is the multiple • Syntax
way branching switch (variable)
statement in C++. {
• Switch works by using Case value: statements;
the value of an integer Case value: statements;
or char variable (or Case value: statements;
expression) to define }
the entry point into a
block.
Action of switch()
Useful items with switch()
• default – a value that can be placed in any
switch statement that represents any non-list
value. Usually placed last and doesn’t use the
word case. Ex. default : pts +=0;
• Break – C++ immediate exit of the current
block. Syntax break;
C++ Loop Statements
• A Loop is a control statement that can make a
statement or block of code be performed more than
one time.
• C++ offers 3 loop commands
while()
do while ()
for ()
• All loops in C++ are controlled by a boolean expression
and continue as long as the expression is true.
The while () loop
• The while () loop is the pretest, indefinite
iteration loop in C++

• Syntax
while (boolean expression)
statement or block;
The do while () Loop
• The do … while() is the post-test indefinite
iteration loop in C++.

• Syntax:
do
statement or block;
while (boolean expression);
Controlling Loops
• while and do-while are known as event-controlled loops.
They continue until some event occurs..
• Common control methods
– counter – a programming technique that increases the value of a
variable by a fixed amount on each repetition of the loop.
– sentinel value - a programming technique that has the user enter a
special, false value of data to exit a loop.
– ending option – a programming technique in which a loop is
controlled by the user’s response to a question
– flag control – a programming technique in which the value of a
boolean variable controls the loop. The value of the boolean
variable is set inside the loop.
The for () Loop
• for (starting place; stopping place; counting interval)
{
BLOCK OR STATEMENT
}
The Struct

Storing data of different types


Simple data type
• A simple data type is a data type in which the
variable stores only 1 value at a time.
Structured Data Type
• A structured data type is a data type in which
the variables store more than one value at a
time.
• Also called composite data type
Struct
• The struct is the C++ structured data type that
can hold several values of different data types.
• Values within a struct are called members or
fields.
• Each member has its own variable name
within the struct definition.
Defining a struct
struct structTypeName
{
typeName fieldname1;
typeName fieldname2;

}
1. The structTypeName becomes a data type name that is used
to declare struct variables in your program.
2. The struct definition is placed before the function prototypes.
3. The semicolon after the close braces is required.
Structs and Functions
• Functions may have a struct as its return type
• A struct may be passed as value parameters to
functions
• A struct may be passed as a reference
parameter to a function.
• If a struct contains many members it is often
passed as a constant reference parameter to
save memory space.
Declaring and Initializing Structs
• Structs, like other variables can be intialized
when they are declared in a function
• C++ provides two methods of initializing structs
– C styled initialization using { } in main()
– Constructor functions in struct definition
• C Style method syntax:
structname variable = { value1, value2,……}
http://www.fredosaurus.com/notes-cpp/index.ht
ml
Nested Structs
• Structs may contain a field which itself is a struct;
called a nested struct.
• Nested structs are used when a field of a struct is
itself made of separate data items.
• The program must define the inner struct before
defining the outer struct
• When accessing the fields of a nested struct, the
program must use the name of both struct fields.
File Streams in C++

Processing Data stored in secondary


memory
Streams
• A stream is a source of data that is transmitted as a
sequence of ASCII characters
• A given stream may be used for input of information, or
output of information but not both. Input streams and
output streams have different data types.
• Treating files as streams allow them to be abstract and
portable.
– Abstract – actual source of data does not change how data is
read from that source
– Portable – manner in which the stream is used is the same
under all operating system
Declaring Streams
• Syntax datatype varname;

• Ex. ofstream outf:


ifstream data;
fstream data;
File Stream Types
• ofstream – output file stream – a stream class
used to write output to a file or other external
device.
• ifstream – input file stream – a stream class
used to read values from a data file or other
external device.
• to use either of these a program must include
the header file fstream or fstream.h
• fstream - for input from or output to a file
File Stream Commands
• .open() – gives a program access to a
filestream.
– syntax streamname.open(“filename.ext”);

• .close() – cuts off access to a folder


In order for a program to write data to a file
the program must:
1. include the header file 1. #include <fstream>
2. declare an ofstream 2. ofstream outf;
variable
3. open the stream 3. outf.open(“data.txt”);
4. insert values into the 4. x=12345;
file using the insertion outf << x << endl;
operator <<
5. close the file when 5. outf.close();
finished with it.
Writing a File Notes
• Should the file listed in the open command not exist, C++
will have Windows create the file as an empty file.
• Should the file listed in the open command exist, C++ will
open the file with the file pointer at the beginning of the
file. The new output will overwrite the existing output.
• It is possible to have the new data added to the end of
the existing file rather than replacing it.
• When the file is closed, Windows writes an end of file
character at the current location of the file pointer.
Writing a File Notes
• Item written to the file must be separated by
whitespace characters. The program must
explicitly insert these characters.
• I/O manipulators such as setw() and
setprecision() may be used with ofstreams to
format output to the file.
• All “printable” data types may be written to a
file.
appending & echo printing
• out.open (“BRHS.txt”, ios::app);
• appends a file with info already in it.

• echo printing – printing the data read from a


file along with the results of the data
processing
Reading Data from a File
1. include header file 1. #include <fstream>
2. declare an ifstream 2. ifstream inf;
variable
3. open the stream 3. inf.open(“data.txt);
4. extract values from the 4. inf >> x;
file >>
5. close the file when 5. inf.close();
finished with it.
Reading from a File - Notes
• The file named in the open statement must
exist otherwise reading will not occur
• Extracting values from a file stream follows
the same rules as extracting from cin.
– leading white spaces are skipped when extracting.
– extraction cuts off the first trailing white space
Some Useful Items
• .fail() – a boolean function that returns true if the last file
operation did not work, false if it worked successfully.
– syntax: streamname.fail()
– primarily used to avoid trying to process non-existant file.
• abort() – function that will cause the current program to
immediately terminate.
– found in stdlib.h
– syntax: abort();
• cerr – an output stream, defined by iostream.h, used to
output error messages.
Filestreams and Functions
• Both ifstreams and ofstreams may be passed
to functions as arguments
• Files MUST be passed as reference
parameters. They cannot be passed as value
or constant reference
• A filestream reference can be returned as the
value of a function
Processing Character by Character
• Character data may be extracted from a file
using >>
• When reading characters with >> white space
characters are skipped
• C++ provides the get() command that can be
used when whitespace need to be read and
processed.
• Syntax: streamname.get( char)
Alternative Declaration Syntax
• Declaration Statement – C++ has a declaration
version that allows the file to be declared and
opened at the same time.
• The file name may be provided as a c-style
string variable.
– ex: char* fname = “H:names.txt”;
ifstream inf (fname);
- or string name = “H:data.txt”;
inf.open(name.c_str())
Other Fairly Useful File Commands
• peek() – peek returns the next character in the
input stream without removing it from the
stream.
• flush() – flush will cause all of the data in an
ofstream’s buffer to be transferred to the sidl
without waiting for the buffer to fill.
• put() – put will place a single character into an
output stream
Default Parameters
Default Parameters
• Default Parameters are a method of providing
an initial value for parameters that are not
provided in the calling statement.
Notes on Default Parameters
1. The name of the parameter does not have to be
listed in the prototype
2. A function can provide default values for more
than 1 parameter
3. Default parameters must appear last in the
parameter list
4. Do not overuse. Apply only when 1 or more
values may not be available and you need to
initialize them for the function
Inline Functions
Inline Functions
• An inline function is a function in which the
compiler replaces the function call in the object
code with the object code for the function itself
• Inline functions indicated with the keyword inline
before the declaration.
• Inline functions can save execution time by
cutting down on the overhead of function calls
• Inline functions can lead to excessively long
object code if the function is long
Function Overloading
Function Overloading
• Overloading – having two or more functions
with the same name in a program.
– Overloaded
Why use Function Overloading
• Overloading is used to allow several functions
that perform the same basic operation to
share the same name.
• Overloading eliminates confusion over which
version of a function to use for a particular
type of data by naming them all with the same
name.
• C did not allow overloading, C++ does
Recursion
Recursion
• Recursion – the process of a function invoking(calling)
itself.
• Recursion provides a powerful programming tool for
solving some problems.
• Recursion has 2 absolute requirements
1. At some point, the solution to the problem being solved
must be definable without recursion – called the base case.
2. Each call to function must bring the function closer to the
base case.
• Recursion can always be replaced by an iterative
process
Why Recursion Works
• Recursion works because of how C++ manages
the run-time stack.
• Each call to a function creates a new stack frame,
complete with its own set of local variables.
• Each level of a recursive function (stack frame) is
independent of other levels in operation.
• Each level is completed in reverse order from
which they were created.
Definition
• tail recursion – tail recursion is when the
recursive call is the last statement with the
function.
• tail recursive is easily and simply replaced with
an iterative routine
• recursive processes that do not use tail
recursion will require some sort of memory
structure to support the iterative solution to the
problem.
C-Styled Arrays
Array
• An array is an ordered collection of variables
with the same name and data type in which
individual variables are accessed by name and
position number.
• Declaring arrays
datatype arrayname [number_of_elements];
ex. int vector [25];
Array Specifics
• Arrays are 0-Based. Indices begin with 0 for all C-styled
arrays.
• Each variable in the array, called an element, must be of
the base type of the array.
• Array elements accessed by array name and its position
number, the position number is called the index or
subscript
• Indices must be int values.
• Indices may be constant, variable or expression.
• C-Styled arrays are NOT
Arrays and Functions
• Arrays may be passed to functions
• Do not give the dimension of the array parameter in the
prototype or the heading line.
• Use only the array name in the calling statement
• Arrays are automatically passed be reference
• Functions cannot return an array as it type
void fill (int ar[]);

int main()
{
int ar[10];
fill(ar);
}
Declaring Array with Constants
• Constants often used to set size of arrays so
that the program can be easily changed later.
Sub-Array Processing
• Often the number of values to be placed in an
array is not known at design time or changes from
one data set to another.
• In a program, the array size is fixed and cannot be
changed, nor can it be declared with a variable.
• Solution to the problem: Make the array
sufficiently large enough to hold typical data set
and have program use only part of the array.
Sorting
• Sorting – The process of placing data into some
predefined order
– Ascending order – smallest to largest
– Descending order – largest to smallest
– Alphabetical order – A to Z – ascending order for strings
• Sorting Methods
1. Selection Sort 2. Bubble Sort
3. Insertion Sort 4. Merge Sort
5. Quick Sort
Another Insertion Sort Approach
• The insertion sort approach can be used to
sort an array already filled with numbers.
• Algorithm:
For elements [1] through [howmany -1]
p = elementIndex
while ar[p] < ar[p-1] and p !=0
swap (ar[p], ar[p-1])
p--
1. void insertionSort(int arr[], int howmany)
2. {
3. for(int i=0, i<howmany; i++)
4. {
5. int p=i;
6. while (p!=0 && arr[p] < arr[p-1])
7. {
8. int temp = arr[p-1];
9. arr[p] = arr[p-1];
10. arr[p-1] = temp;
11. p--;
12. }
13. }
14.}
Bubble Sort
• The Bubble Sort works by comparing and
correcting the relative order of adjacent
elements in the array.
• Process
– As long as the array is not sorted for each array
location through the 2nd to last if the value of the
current location is larger than the value at the next
location swap value of the current location with
the value of the next location
1. void bubble(int arr[], int howmany)
2. {
3. bool swapped = true;
4. for( int pass = 1; pass < howmany; pass++)
5. {
6. swapped = false;
7. for( int k = 0; k<howmany-pass; k++)
8. {
9. if( arr[k] > arr[k+1])
10. {
11. int temp = arr[k];
12. arr[k] = arr[k+1];
13. arr[k+1] = temp;
14. }
15. }
16. }
17. }
Selection Sort
• Selection sort works by finding the correct
value for each location of the array beginning
with the first.
• Process
– For each location starting with the first the
smallest value remaining swap value with the
current location’s value
• Advantage – only one exchange of values per
element in the array
Insertion Sort
1. void insertionSort(int ar[], int &howmany, ifstream &inf)
2. {
3. int value, place;
4. inf >> value;
5. while(!inf.eof())
6. {
7. place = 0;
8. while(place < howmany && value > ar[place])
9. place++;
10. for( int k=howmany-1; k>=place; k--)
11. ar[k+1]=ar[k];
12. ar[place]=value;
13. howmany++;
14. inf>>value;
15. }
16.}
The Merge
• The Merge works by placing values from two
sorted arrays into a single sorted array.
Algorithm:
set list pointers to element 0 of each list and the combination list while both data
list have value in them
i
• void MergeSort(apvector <int> &arrayA, apvector <int> &arrayB, apvector <int> &arrayC)
{
     int indexA = 0;     // initialize variables for the subscripts
     int indexB = 0;
     int indexC = 0;

     while((indexA < arrayA.length( )) && (indexB < arrayB.length( ))


     {
          if (arrayA[indexA] < arrayB[indexB])
          {
                 arrayC[indexC] = arrayA[indexA];
                 indexA++;    //increase the subscript
          }
         else
         {
                 arrayC[indexC] = arrayB[indexB];
                 indexB++;      //increase the subscript
         }
        indexC++;      //move to the next position in the new array
     }
     // Move remaining elements to end of new array when one merging array is empty
     while (indexA < arrayA.length( ))
     {
           arrayC[indexC] = arrayA[indexA];
           indexA++;
           indexC++;
     }
     while (indexB < arrayB.length( ))
     {
           arrayC[indexC] = arrayB[indexB];
           indexB++;
           indexC++;
     }
     return;
}
• http://mathbits.com/mathbits/compsci/comp
sci.htm
The Merge Sort
void mergesort (int nums [], int low, int high)
{
if (low < high)
{
int middle = (low + high)/2;
mergesort (nums, low, middle);
mergesort (nums, middle+1, high);
merge (nums, low, middle, high);
}
Merge Sort
• The merge sort is a divide and conquer sort that
is based upon the fact that it is more efficient to
sort two short list and combine them into one
list rather that sorting the data as a single list.
• This process uses a process called a sorted
merge
• A merge can combine two lists of size N/2 into a
list of size N with N operations
void merge (int nums[], int low, int middle, int high)
{
int temp[20];
int lp = low;
int hp = middle+1;
int tp = low;
while (lp <= middle && hp <== high)
{
if (nums[lp] < nums[hp])
{
temp[tp] = nums[lp];
tp++;
lp++;
}
else
{
temp[tp] = nums[hp];
tp++;
Sequential Search
• Sequential search is the search method that tests each
value of the array in their order within the array.
• Works on both a sorted or unsorted array.
• The array may contain duplicate values.
• This search may be used to find and process multiple
occurrences of the search value.
• Algorithm
– Get the search value
– For every location in the array
• If the element of the array equals the search value, process the array
element
Binary Search
• Binary Search is a searching method that works
by cutting the portion of the array where the
value lies in half with each comparison
• Algorithm is a similar to the strategy used in the
number guessing game called High-Low.
• Very fast and efficient searching method
especially for a long list
• Requires that the array be sorted prior to
searching.
Binary Search Algorithm
Get the search value
Set low to 0
Set high to last position containing data in the array
Do
find the middle position
if the value at the middle position is larger than the search
value, move high to the middle
else if the value at the middle is smaller than the search value,
move low to the middle
until the value at the middle position is equal to the search
value process the middle position in the array.
C++
/*
* searches for a value in sorted array
*   arr is an array to search in
*   value is searched value
*   left is an index of left boundary
*   right is an index of right boundary
* returns position of searched value, if it presents in the array
* or -1, if it is absent
*/
int binarySearch(int arr[], int value, int left, int right) {
      while (left <= right) {
            int middle = (left + right) / 2;
            if (arr[middle] == value)
                  return middle;
            else if (arr[middle] > value)
                  right = middle - 1;
            else
                  left = middle + 1;
      }
      return -1;
}
Two Dimensional Arrays
• A two dimensional array is an array in which
each element is referred to by 2 subscript
values. Ex T[3][6]

• Declaring:
– Syntax datatype name[row][column]
– Ex. int T[3][6];
Two Dimensional Arrays
• Both rows and columns are 0 based
• Accessing – the elements of the array are
accessed by giving the name of the array
followed by both subscripts. The row subscript
is given first.
• Two dimensional arrays are not range check.
• In code, be sure not to go beyond range of
array.
Initializing Two Dimensional Arrays
• //1 provide value for every location
int two [3][4] = { {1,2,3,4}, {2,4,6,8}, {3,6,9,12} };

• //2 provide some values for each row


int mat [ ][4] = { {1,2,3}, {2,4}, {6} };

• //3 providing them sequentially


int tbl [3][4] = {1,2,3,4,5,6,7,8,9,10};
Two Dimensional Arrays
• Array Operations
– 2-d arrays may be passed to a function as
parameters.
– 2-d arrays used as parameters to a function are
automatically reference parameters
– 2-d arrays may not be returned as the value of a
function
– 2d arrays may not be compared
– 2d arrays
Passing 2D arrays to functions
• Two dimensional arrays may be passed to
functions as parameters
• They are automatically passed as reference
parameters
• When writing the parameter the number of
columns must be given – the number of rows
is optional
CLASSES
Class Definitions
• Class – a C++ data type • Class – an abstract data
that contains several data type consisting of a set of
members of different values called attributes
types and member and a set of operations
functions for processing called behaviors
the data members.
• Object – an abstract item
• Object – a variable (an that has a unique set of
instance) of a class data attributes and behaviors
type
Abstract view of a Class
• Attributes
– A list of the values that describe the object

• Behaviors
– A list of the operations that are performed on or
with the attributes
Abstract view of a Class
EXAMPLE
• Class – a desk lap
• Attributes
– Lamp status

• Behavior
– Turn on
– Turn off
Class Definitions Syntax
Class typename
{
public:
//prototypes and declarations of items
//accessible from outside the class
private:
//prototypes and declarations of items
//accessible only by class members
};
Writing Classes in Programs
• When defining a class in the same file as the
program that uses the class, the class is
defined before the function prototypes
• The member functions can be coded within
the class, but normally are not
• Normally the member functions are
prototyped in the class definition and coded
after main()
Using Overloaded Constructors
• Overloaded constructors are used to declare
and initialize class objects in one statement.
• Syntax: classname varname(param. list)
Free Functions
• A free function is a non-member function
provided with a class that performs some task
with class object.
• Free functions are prototyped in the .h file,
outside of the class definition.
• Free functions are implemented in the .cpp
file
• When implementing
Destructor
• Destructor is a special function used to remove an object
from memory when it goes out of scope.
• Object goes out of scope at:
– End of block
– End of a function
– End of a program
– C++ provides a default destructor is one not placed in the class.
• Declaration
~classname();
Used for getting rid of objects when they go out of scope
this
• A keyword that refers to the current object – it
is a way to let a function refer to the object
that invokes it.

• Syntax:
this -> a
*this
Pointers in C++

Indirection, Referencing and Dynamic


Allocation of Variables
Memory Addresses
• Memory Address – a non-negative integer that
‘names’ a byte in memory
• Addresses begin with 0
• Addresses are sequential by 1
• The memory address is how the computer
system finds an item in memory.
• A variable’s address is the memory address of the
first byte of memory used to store the variable’s
value
Reference Variables
• Reference – a variable that stores the memory
address of another variable
• A Reference variable is indicated by the use of
an & before the variable name.
– Int &ref
Pointer Variables
• Pointer – a variable that stores the memory
address of another variable
• A pointer variable is indicated by the use of an
asterisk(*) before the variable name.

• Pointer only store the address of a specific


type of variable.

You might also like