Computer Science II
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;
}
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
• 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
|| or (ch==‘y’ || ch==‘Y’)
• 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
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;
• 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} };
• 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++