CSC202
CSC202
Outlines
• C++ How to Program by Paul Deitel & Harvey Deitel 7th edition
• Schaum’s Outlines, Programing with C++ 2nd Edition by John R.
Hubbard
Falana O. J.
C++ Development Environment
Falana O. J.
Falana O. J.
The Basics of a C++ Program
Falana O. J.
Example Program
#include <iostream>
using namespace std;
int main()
{
cout<<"Welcome to C++ Programming"<<endl;
return 0;
}
Falana O. J.
Program Output
The Basics of a C++ Program
• Programming language
– a set of rules, symbols, special words
• Rules
– syntax – specifies legal instructions
• Symbols
– special symbols ( + - * ! …)
• Word symbols
– reserved words
– (int, float, double, char …)
Falana O. J.
Identifiers
Falana O. J.
Data Types
• Definition:
– a set of values
– combined with a set of
operations
Data Types
Falana O. J.
Data Types
• Different floating-
point types
Falana O. J.
Data Types
Falana O. J.
Arithmetic Operators and Operator Precedence
• An expression includes
– constants
– variables
– function calls
– combined with operators
3 / 2 + 5.0
sin(x) + sqrt(y)
Falana O. J.
Expressions
Falana O. J.
Type Casting
Falana O. J.
Input
cin >> x
123
Falana O. J.
x
Allocating Memory
• Variable
– A memory location whose content may change during program
execution
• Declaration:
– Syntax:
type identifier;
– Example:
double x; Note optional
int y = 45; initialization of the
variable
Falana O. J.
Allocating Memory
• Named Constant
– A memory location whose content cannot be changed
• Declaration
– Syntax:
const type identifier = value;
– Example
const double PI = 3.14159;
Note required
initialization of the
Falana O. J. named constant
Putting Data Into Variables
• At initialization time
• Assignment statement
– Syntax:
variable = expression;
– Example
x = 1.234;
volume = sqr (base) * height;
• Input (read) statement
– Syntax:
cin >> variable ; Program
– Example Example
cin >> height;
Falana O. J.
Increment and Decrement Operators
• Pre-increment ++x;
equivalent to x = x + 1;
– Pre-decrement --x;
– Changes the value before execution of a statement y = ++x;
• Post-increment intVal++;
– Post-decrement intVal--;
– Changes the value after execution of the statement y = x++;
Falana O. J.
Output
Falana O. J.
Preprocessor Directives
Falana O. J.
Preprocessor Directives
Falana O. J.
Namespace
Falana O. J.
Program Style and Form
Falana O. J.
Program Style and Form
• Documentation
– Comments specified between
/* this is a comment */
and following // also a comment
– Always put at beginning of program
/* name,
date,
cpo,
purpose of program
*/
Falana O. J.
Program Style and Form
double electricCharge;
// instead of ec
Falana O. J.
STRUCTURED
PROGRAMING
Falana O. J.
STRUCTURED PROGRAMMING: HISTORY
AND RATIONALE
• The history of structured programming began in 1964 at an
international colloquium held in Israel.
• There Corrado Bohm and Guiseppe Jacopini presented a paper
(in Italian) that proved mathematically that only three "control
structures" were necessary to write any program.
• The work of Bohm and Jacopini made the GOTO statement
unnecessary in computer programming.
Falana O. J.
STRUCTURED PROGRAMMING: HISTORY
AND RATIONALE
• The first project to be developed using the idea of structured programming
was a system to automate the newspaper's clipping file.
• Using a list of Index terms, users could browse through abstracts of all the
paper's article and then retrieve the full-length articles of their choice from
microfiche for display on a terminal screen.
•
Falana O. J.
• These results shocked the programming community. Software
developers began to pay attention to the idea of structured
programming
Falana O. J.
Structured Programming
Falana O. J.
How does structured programming minimize
complexity?
• it does so in three ways:
• Structured programming a method of writing a computer program
that uses (1) Top-down analysis for problem solving, (2)
modularization for program structure and organization, and ( 3)
structured code for the individual modules
Falana O. J.
Top-down analysis
Falana O. J.
Top-down analysis
Falana O. J.
MODULAR PROGRAMMING
Falana O. J.
STRUCTURED CODING
Falana O. J.
STRUCTURED CODING
Falana O. J.
Components of a Control Structure
Falana O. J.
Advantages of Structured Programming
Falana O. J.
• Programs require less time to debug and test. This is true, first,
because fewer errors are made in writing programs. However ,
modularity also makes it much faster to localize and correct those
errors that do occur.
• Programs are easier to maintain. As programs and systems are
used, the need often arises to modify them, either by making
changes or adding new features.
Falana O. J.
STRUCTURED PROGRAMMING AND
PROGRAM MING LANGUAGES
• Three statements can be made about structured and computer
languages
• A programmer can apply the methods of structured programming
in any language
• Some languages have been designed in such a way that one has to
write a modular program.
• The ease with which one can write structured code depends to
some extent on the language used
Falana O. J.
CONTROL STRUCTURE IN C++
• sequence structure
Add 1 to counter
Falana O. J.
CONTROL STRUCTURE IN C++ (contd…)
• selection structures:
• The if selection structure either performs (selects) an action, if a
condition is true, or skips the action, if the condition is false
• The if/else selection structure performs an action if a condition is
true and performs a different action if the condition is false.
• The switch selection structure performs one of many different
actions, depending on the value of an expression.
Falana O. J.
CONTROL STRUCTURE IN C++ (contd…)
Falana O. J.
• Iteration (Repetition):
• C++ provides three types of repetition structures—namely, while,
do/while and for
Falana O. J.
Selection Structure
Falana O. J.
• The if selection structure performs an indicated action only when the
given condition evaluates to true; otherwise, the action is skipped. The
if/else selection structure allows the programmer to specify
• that a different action is to be performed when the condition is true
rather than when the condition is false. For example,
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”
Falana O. J.
Selection Structure
Falana O. J.
Practice Questions
Falana O. J.
TESTING AND DEBUGGING
Reference: Ian Sommerville, Software Engineering, Addison-Wesley, Sixth Edn.,
2000.
Falana O. J.
Software Testing
Falana O. J.
Software Testing
Falana O. J.
Development testing
Falana O. J.
Development testing: Unit testing
Falana O. J.
Development testing: Unit testing
Falana O. J.
Development testing :Component testing
Falana O. J.
Development testing :Component testing
Falana O. J.
Development testing :Component testing
Falana O. J.
Development testing :Component testing
Falana O. J.
Development testing: Component testing
Falana O. J.
Development testing: System testing
Falana O. J.
Test-driven development
Falana O. J.
Test-driven development
Falana O. J.
Test-driven development
Falana O. J.
Test-driven development
3. You then run the test, along with all other tests that have been
implemented. Initially, you have not implemented the functionality so
the new test will fail. This is deliberate as it shows that the test adds
something to the test set.
4. You then implement the functionality and re-run the test. This may
involve refactoring existing code to improve it and add new code to
what’s already there.
5. Once all tests run successfully, you move on to implementing the next
chunk of functionality.
Falana O. J.
Release testing
Falana O. J.
Types of user testing
Falana O. J.
Debugging
Falana O. J.
Debugging
Falana O. J.
Debugging in general
Falana O. J.
Functions
Falana O. J.
• The C++ Standard Library provides a rich collection of functions
for common mathematical calculations, string manipulations,
character manipulations, input/output, error checking and many
other useful operations.
• Functions (called methods or procedures in other programming
languages) allow you
• to modularize a program by separating its tasks into self-contained
units
Falana O. J.
Building Programs from Existing Programs
Falana O. J.
Predefined Functions and Code Reuse
• The primary goal of software engineering is to
write error-free code.
– Code reuse: reusing program fragments that have
been written and tested.
• C++ library functions provide most commonly
used functions.
– e.g., mathematical library <cmath>
• To use existing C library functions, we have to
include the header file of the corresponding
library.
– e.g., #include <cmath>
Falana O. J.
An Example: The Usage of sqrt Function (1/2)
Falana O. J.
Square Root Function sqrt()
Falana O. J.
Some functions defined in <cmath> Header
Falana O. J.
USER-DEFINED FUNCTIONS
• A user-defined function has two parts: its head and its body. The
syntax for the head of a function is
return-type name(parameter-list)
The body of a function is the block of code that follows its head.
Falana O. J.
TEST DRIVERS
Falana O. J.
FUNCTION DECLARATIONS AND
DEFINITION
• The last example illustrates one method of defining a function in
a program: the complete definition of the function is listed above
the main program. This is the simplest arrangement and is good
for test drivers.
• Another, more common arrangement is to list only the function’s
header above the main program, and then list the function’s
complete definition (head and body) below the main program.
This is illustrated in the next example
Falana O. J.
Falana O. J.
The max() Function Compiled Separately
Falana O. J.
Recursion
Falana O. J.
The Factorial Function
Falana O. J.
Iteratively (non-recursively)
Falana O. J.
The Factorial Function
Falana O. J.
The Factorial Function
Falana O. J.
Recursive power example
• An iterative solution:
int pow(int x, int y) {
int product = 1;
for (int i = 0; i < y; i++)
product = product * x;
return product;
}
100
Recursive power function
101
How recursion works
• each call sets up a new instance of all the parameters and the local
variables
• as always, when the method completes, control returns to the
method that invoked it (which might be another invocation of the
same method)
pow(4, 3) = 4 * pow(4, 2)
= 4 * 4 * pow(4, 1)
= 4 * 4 * 4 * pow(4, 0)
= 4 * 4 * 4 * 1
= 64
102
Infinite recursion
• a definition with a missing or badly written base case causes infinite recursion,
similar to an infinite loop
– avoided by making sure that the recursive call gets closer to the solution (moving
toward the base case)
int pow(int x, int y) {
return x * pow(x, y - 1); // Oops! Forgot base case
}
pow(4, 3) = 4 * pow(4, 2)
= 4 * 4 * pow(4, 1)
= 4 * 4 * 4 * pow(4, 0)
= 4 * 4 * 4 * 4 * pow(4, -1)
= 4 * 4 * 4 * 4 * 4 * pow(4, -2)
= ... crashes: Stack Overflow Error!
103
Recursive Programming
• Note that just because we can use recursion to solve a problem, doesn't
mean we should
• For instance, we usually would not use recursion to solve the sum of 1
to N problem, because the iterative version is easier to understand
• However, for some problems, recursion provides an elegant solution,
often cleaner than an iterative version
• You must carefully decide whether recursion is the correct technique
for any problem
Indirect Recursion
m1 m2 m3
m1 m2 m3
m1 m2 m3
Assignment
Falana O. J.
STRING PROCESSING
Falana O. J.
INTRODUCTION
Falana O. J.
• In C++, a C-string is an array of characters with the following
important features:
• An extra component is appended to the end of the array, and its
value is set to the NUL character '\0'.
• This means that the total number of characters in the array is
always 1 more than the string length.
Falana O. J.
Initialization of a String
Falana O. J.
Class string also provides a default constructor (which creates an
empty string) and a copy constructor. An empty string is a string that
does not contain any characters.
A string also can be initialized via the alternate constructor syntax in
the definition of a string as in
string month = "March"; // same as: string month( "March" );
Falana O. J.
Falana O. J.
Demonstrating string assignment and concatenation.
Falana O. J.
Comparing strings
• Class string provides member functions for comparing strings. class string’s comparison
capabilities.
#include <iostream>
#include <string>
using namespace std;
int main()
{ string string1( "Testing the comparison functions." );
string string2( "Hello" );
string string3( "stinger" );
string string4( string2 );
Falana O. J.
Demonstrating string comparison capabilities.
cout << "string1: " << string1 << “nstring2: " << string2 << "\nstring3: " << string3 << "\nstring4: " <<
string4 << "\n\n";
// comparing string1 and string4
if ( )
cout << "string1 == string4\n";
else // string1 != string4
{
if ( )
cout << "string1 > string4\n";
else // string1 < string4
cout << "string1 < string4\n";
} // end else
Falana O. J.
Demonstrating string comparison capabilities.
if ( result == 0 )
cout << "string1.compare( string2 ) == 0\n";
else // result != 0
{
if ( result > 0 )
cout << "string1.compare( string2 ) > 0\n";
else // result < 0
cout << "string1.compare( string2 ) < 0\n";
} // end else
Falana O. J.
Substrings
Falana O. J.
Demonstrating String member function subtr.
Falana O. J.
Swapping strings
Falana O. J.
string Characteristics
Falana O. J.
Replacing Characters in a string
• string string1( "The values in any left subtree“ \n are less than the
value in the \n parent node and the values in“ \n any right
subtree are greater \n than the value in the parent node" );
string1.erase( 62 );
string1.replace( position, 1, "." );
Falana O. J.
Inserting Characters into a string
Falana O. J.
SEARCHING AND SORTING
• ARRAY
• Arrays are data structures consisting of related data items of the
same type.
• An array is a consecutive group of memory locations that all have
the same type. To refer to a particular location or element in the
array, we specify the name of the array and the position number of
the particular element in the array.
Falana O. J.
• The figure below shows an integer array called c.
Falana O. J.
• This array contains 12 elements. A program refers to any one of
these elements by giving the name of the array followed by the
position number of the particular element in square brackets ([]).
• The position number is more formally called a subscript or index
(this number specifies the number of elements from the beginning
of the array).
• The first element in every array has subscript 0 (zero) and is
sometimes called the zeroth element. Thus, the elements of array c
are c[0] (pronounced “c sub zero”), c[1], c[2] and so on.
Falana O. J.
• A subscript must be an integer or integer expression (using any
integral type). If a program uses an expression as a subscript, then
the program evaluates the expression to determine the subscript.
For example, if we assume that variable a is equal to 5 and that
variable b is equal to 6, then the statement
c[ a + b ] += 2;
adds 2 to array element c[11].
Falana O. J.
Declaring Arrays
Falana O. J.
Declaring an Array and Using a Loop to Initialize
the Array’s Elements
Falana O. J.
Passing Arrays to Functions
int sum(int[],int);
int main()
{
int a[] = { 11,33, 55,77 };
int size = sizeof(a)/sizeof(int);
cout << "sum(a,size) = " << sum(a,size) << endl;
}
int sum(int a[],int n)
{ int sum=0;
for (int i=0; i<n; i++)
sum += a[i];
return sum;
}
Falana O. J.
THE LINEAR SEARCH ALGORITHM
• Computers are probably used more for the storage and retrieval of
information than for any other purpose.
• Data is often stored in a sequential structure such as an array.
• The simplest way to find an object in an array is start at the
beginning and inspect each element, one after the other, until the
object is found. This method is called the Linear Search algorithm
Falana O. J.
The Linear Search
int main()
{ int a[] = { 22,44, 66,88,44,66,55 };
cout << "index(44,a,7) = " << index(44,a,7) << endl;
cout << "index(50,a,7) = " << index(50,a,7) << endl;
}
int index(int x, int a[], int n)
{ for (int i=0; i<n; i++)
if (a[i] == x) return i;
return n; // x not found
}
Falana O. J.
THE BUBBLE SORT ALGORITHM
Falana O. J.
Bubble Sort
1. int a[6] = {5, 1, 6, 2, 4, 3};
2. int i, j, temp;
3. for(i=0; i<6; i++)
4. {
5. for(j=0; j<6-i-1; j++)
6. {
7. if( a[j] > a[j+1])
8. {
9. temp = a[j];
10. a[j] = a[j+1];
11. a[j+1] = temp;
12. }
13. }
14. }
void print(float[],int);
void sort(float[],int);
Void swap(float[], )
int main()
{
float a[] = {55.5, 22.5,99.9,66.6,44.4,88.8,33.3,77.7};
print(a,8);
sort(a,8);
print(a,8);
}
Falana O. J.
Bubble Sort
Falana O. J.
THE BINARY SEARCH ALGORITHM
Falana O. J.
How Binary Search Works?
Falana O. J.
How Binary Search Works?
Falana O. J.
How Binary Search Works?
Falana O. J.
How Binary Search Works?
Falana O. J.
Pseudocode of Binary Search contd
Procedure binary_search
A ← sorted array
n ← size of array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n
while x not found
if upperBound < lowerBound
EXIT: x does not exists.
set midPoint = lowerBound + ( upperBound - lowerBound ) / 2
Falana O. J.
Pseudocode of Binary Search contd…
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint
end while
end procedure
Falana O. J.
The Binary Search Algorithm
Falana O. J.
The Binary Search Algorithm contd…
Falana O. J.
Multidimensional Arrays
Falana O. J.
Reading and Printing a Two-Dimensional Array
Falana O. J.
• associates the name n, the type int, and the address of some
location in memory where the value of n is stored. Suppose that
address is 0x0064fdf0. Then we can visualize n like this:
Falana O. J.
• In C++, you can obtain the address of a variable by using the
reference operator &, also called the address operator. The
expression &n evaluates to the address of the variable n.
int main()
{ int n=44;
cout << "n = " << n << endl; // prints the value of n
cout << "&n = " << &n << endl; // prints the address of n
}
Falana O. J.
• Displaying the address of a variable this way is not very useful.
The reference operator & has other more important uses
Falana O. J.
REFERENCES
Falana O. J.
REFERENCES
Falana O. J.
POINTERS
Falana O. J.
Using a pointer variable
This program defines the int variable n and the int* variable pn:
int main()
{ int n=44;
cout << "n = " << n << ", &n = " << &n << endl;
int* pn=&n; // pn holds the address of n
cout << " pn = " << pn << endl;
cout << "&pn = " << &pn << endl;
}
Falana O. J.
• The variable n is initialized to 44. Its address is 0x0064fddc.
• The variable pn is initialized to &n which is the address of n, so
the value of pn is 0x0064fddc, as the second line of output shows.
But pn is a separate object, as the third line of output shows: it has
the distinct address 0x0064fde0
• The variable pn is called a “pointer” because its value “points” to
the location of another value. The value of a pointer is an address
Falana O. J.
Pointers
Falana O. J.
CLASSES
Falana O. J.
Introduction
Falana O. J.
Class Declaration
class Ratio
{ public:
void assign(int,i nt);
double convert();
void invert();
void print();
private:
int num,den;
};
Falana O. J.
• The declaration begins with the keyword class followed by the
name of the class and ends with the required semicolon. The name
of this class is Ratio.
• The functions assign(), convert(), invert(), and print() are called
member functions because they are members of the class.
• The variables num and den are called member data.
• Member functions are also called methods and services.
Falana O. J.
• The difference is that public members are accessible from outside
the class,
• while private members are accessible only from within the class
• Preventing access from outside the class is called “information
hiding.” It allows the programmer to compartmentalize the
software which makes it easier to understand, to debug, and to
maintain.
Falana O. J.
Main Method
int main()
{ Ratio x;
x.assign(22,7);
cout << "x = ";
x.print();
cout << " = " << x.convert() << endl;
x.invert();
cout << "1/x = "; x.print();
cout << endl;
}
Falana O. J.
Explanation
Falana O. J.
void Ratio::invert()
{ int temp = num;
num = den;
den = temp;
}
void Ratio::print()
{ cout << num << '/' << den;
}
Falana O. J.
A Self-Contained Implementation of the Ratio
Class
class Ratio
{ public:
void assign(int n,int d) { num = n; den = d; }
double convert() { return double(num)/den; }
void invert() { int temp = num; num = den; den = temp; }
void print() { cout << num << '/' << den; }
private:
int num,den;
};
Falana O. J.
CONSTRUCTORS
Falana O. J.
CONSTRUCTORS
class Ratio
{ public:
Ratio(int n,int d) { num = n; den = d; }
void print() { cout << num << '/' << den; }
private:
int num,den;
};
Falana O. J.
int main()
{ Ratio x(-1,3), y(22,7);
cout << "x = ";
x.print();
cout << " and y = ";
y.print();
}
Falana O. J.
• The constructor function has the same effect as the assign()
function had in the last example:
• it initializes the object by assigning the specified values to its
member data.
• When the declaration of x executes, the constructor is called
automatically and the integers -1 and 3 are passed to its
parameters n and d.
Falana O. J.
Using Default Parameter Values in the Ratio Class
Constructor
class Ratio
{ public:
Ratio(int n=0,int d=1) : num(n),den(d) { }
private:
int num, den;
};
int main()
{ Ratio x, y(4),z(22, 7);
}
Falana O. J.