0% found this document useful (0 votes)
12 views

CSC202

Computer programming

Uploaded by

taibatlawal0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

CSC202

Computer programming

Uploaded by

taibatlawal0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 180

Mountain Top University

Outlines

• Principles of good programming


• structured programming concepts,
• Debugging and testing,
• String processing,
• internal searching
• Sorting,
• Recursion.
• Use a programming language different from that in CSC 201.
Falana O. J.
Course Text Books

• 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

• A C++ program is a collection of one or more subprograms


(functions)
• Function
– Collection of statements
– Statements accomplish a task
• Every C++ program has a function called main

Falana O. J.
Example Program
#include <iostream>
using namespace std;
int main()
{
cout<<"Welcome to C++ Programming"<<endl;
return 0;
}

Welcome to C++ Programming

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

• Rules for identifiers


– must begin with letter or the underscore _
– followed by any combination of numerals or letters
– recommend meaningful identifiers
• Evaluate the following
ElectricCharge
23Skidoo
snarFbLat

Falana O. J.
Data Types

• Definition:
– a set of values
– combined with a set of
operations
Data Types

• Simple data types include


– Integers
– Floating point
– Enumeration
• Integer data types include
char
Numerals, symbols,
short letters
int Numbers without decimals
long
bool Values true and false only
Falana O. J.
Floating-Point Types

• Stored using scientific notation


– the sign of the number,
– the significant digits of the number
– the sign of the power of 10
– the power of 10

Falana O. J.
Data Types

• Different floating-
point types

• Note that various types will


– have different ranges of values
– require different amounts of memory

Falana O. J.
Data Types

• The string Type


– a programmer-defined type
– requires #include <string>
• A string is a sequence of characters
"Hi Mom"
"We're Number 1!"
"75607"

Falana O. J.
Arithmetic Operators and Operator Precedence

• Common operators for calculations


+ - * / %
• Precedence same as in algebraic usage
– Inside parentheses done first
– Next * / % from left to right
– Then + and - from left to right

• Note operator precedence chart,


page 1035
Falana O. J.
Expressions

• An expression includes
– constants
– variables
– function calls
– combined with operators

3 / 2 + 5.0
sin(x) + sqrt(y)

Falana O. J.
Expressions

• Expressions can include


– values all of the same type
3 + 5 * 12 – 7
– values of different (compatible) types
1.23 * 18 / 9.5
• An operation is evaluated according to the types of the operands
– if they are the same, the result is the type of the operands
– if the operands are different (int and float) then the result is float

Falana O. J.
Type Casting

• Implicit change of type can occur


– when operands are of different type
• It is possible to explicitly specify that an expression be converted
to a different type

static_cast < type > (expression)

static_cast <int> (3.5 * 6.9 / x)

Falana O. J.
Input

• Storing data in the computer's memory requires two steps


1. Allocate the memory by declaring a variable
2. Have the program fetch a value from the input device and place it
in the allocated memory location

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

• Values sent to an output device


– Usually the screen
– Can also be a file or some device
• Syntax for screen output:
cout << expression << …
• Example
cout << "The total is "<< sum << endl;

Output Sample Manipulator


command for carriage
InsertionProgram Values to be
operator return
Falana O. J.
printed
Output

• Escape sequences also used to manipulate output

cout << "The total is\t "<< sum << endl;

Falana O. J.
Preprocessor Directives

• Commands supplied to the preprocessor


– Runs before the compiler
– Modifies the text of the source code before the compiler starts
• Syntax
– start with # symbol
– #include <headerFileName>
• Example #include <iostream>

Falana O. J.
Preprocessor Directives

• Note the preprocessor


step in the sequence

Falana O. J.
Namespace

• The #include <iostream> command is where cin and cout


are declared
• They are declared within a namespace called std
• When we specify
using namespace std;
– Then we need not preface the cin and cout commands with
std::cin and std::cout

Falana O. J.
Program Style and Form

• Every program must contain a function


called main
int main (void)
{ … }
• The int specifies that it returns an integer
value
• The void specifies there will be no
arguments
• Also can say
void main( )
{ … }
Falana O. J.
Program Style and Form

• Variables usually declared


– inside main
– at beginning of program
• Use blanks and space to make the program easy for humans to
read
• Semicolons ; required to end a statement
• Commas used to separate things in a list

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

• Names of identifiers should help document program

double electricCharge;
// instead of ec

• Prompt keyboard entry


cout << "Enter the value for x -> ";
cin >> x;

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

• Structured Programming is often thought to be programming


without the use of the GOTO statement. Indeed, structured
programming does discourage the frequent and indiscriminate use
of GOTO
• one author has defined structured programming as follows: " a
method of designing computer system components and their
relationships to minimize complexity"

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

• A program is written to tell a computer what to do. But what do


you want it to do?
• What is the job you want it to perform for you?. The "job" is more
formally called the problem.
• Before you can tell the computer what to do, you have to "solve"
the problem yourself, in other words , you have to state every step
necessary in order to accomplish the job. This activity on your
part is called problem solving or problem analysis.

Falana O. J.
Top-down analysis

• Top down analysis is a method of problem solving. it tells you


how to start and guides you through the entire process.
• The essential idea is to subdivide a large problem into several
smaller tasks or parts.
• Top-down analysis, therefore simplifies or reduces the complexity
of the problem solving

Falana O. J.
MODULAR PROGRAMMING

• Programs generally require many instructions for the computer. Modular


programming is a method of organizing these instructions.
• Large programs are broken down into separate, smaller sections called
modules, subroutines, or subprograms.
• Each module has a specific job to do and is relatively easy to write.
Modular structure also simplifies programming by greatly reducing the
need for GOTO statement, which , when used frequently, tends to obscure
program organization and introduces error.

Falana O. J.
STRUCTURED CODING

• If programs are broken down into modules, Into what are


modules subdivided?
• Obviously, each consists of a set of instructions to the computer.
• But are these instructions organized in any special way?
• That is, are they grouped and executed in any clearly definable
patterns?

Falana O. J.
STRUCTURED CODING

• In structured programming they are organized within various


control structures.
• A control structure represents a unique pattern of execution for a
specific set of instructions. It determines the precise order in
which that set of instructions is executed.

Falana O. J.
Components of a Control Structure

• The component statements within a specific control structure are


executed either
• Sequentially
• Conditionally
• Repetitively
vStructured code cannot include GOTO statement

Falana O. J.
Advantages of Structured Programming

• Programs are more easily and more quickly written. Big


programming tasks do not remain big programming tasks. They
are broken down far enough that each subtask is easy to program
as separate unit
• Programs have greater reliability. Far fewer organizational and
logical errors occur in the initial stages of program development
and writing.

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++

• Bohm and Jacopini’s work demonstrated that all programs could be


written in terms of
• only three control structures—namely,
1. The sequence structure,
2. The selection structure and
3. The repetition structure.
• The sequence structure is built into C++. Unless directed otherwise,
the computer executes C++ statements one after the other in the order
in which they are written
Falana O. J.
CONTROL STRUCTURE IN C++ (contd…)

• sequence structure

Add grade to Total

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…)

• The if structure is called a single-selection structure, because it


selects or ignores a single action (or, as we will soon see, a single
group of actions).
• The if/else structure is called a double-selection structure, because
it selects between two different actions (or groups of actions).
• The switch structure is called a multiple-selection structure,
because it selects among many different actions (or groups of
actions).

Falana O. J.
• Iteration (Repetition):
• C++ provides three types of repetition structures—namely, while,
do/while and for

Falana O. J.
Selection Structure

• Selection Structure: The selection structure


also known as decision structure is a case in
the algorithm where one has to make a
choice of two alternatives by making a
decision depending on a given condition.

• A selection structure takes the form:


If condition is true
Then do task A
else
Do Task-B
Falana O. J.
Selection Structure

• This structure can be illustrated in a flowchart as follows:

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

• The selection requires the following:


Ø Choose alternative actions as a result of testing a
logical condition
Ø Produce code to test a sequence of logical tests
• In making choices, IF statement is used together with
logical operators to test for true or false.
• The logical operators used are:

Ø = is equal to <= is less than or equal


Ø > is greater than <> is not equal to
Ø < is less than
Ø >= is greater than or equal

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

• A model of the software testing process

Falana O. J.
Software Testing

• Typically, a commercial software system has to go through


three stages of testing:
• Development testing, where the system is tested during
development to discover bugs and defects. System designers
and programmers are likely to be involved in the testing
process.
• Release testing, where a separate testing team tests a
complete version of the system before it is released to users. The
aim of release testing is to check that the system meets the
Falana O. J.
requirements of system stakeholders.
• User testing, where users or potential users of a system test the
system in their own environment. For software products, the ‘user’
may be an internal marketing group who decide if the software
can be marketed, released, and sold.
• Acceptance testing is one type of user testing where the customer
formally tests a system to decide if it should be accepted from the
system supplier or if further development is required.

Falana O. J.
Development testing

• Development testing includes all testing activities that are carried


out by the team developing the system.
• The tester of the software is usually the programmer who
developed that software, although this is not always the case
• During development, testing may be carried out at three levels of
granularity:
1. Unit testing, where individual program units or object classes are
tested. Unit testing should focus on testing the functionality of
objects or methods.
Falana O. J.
Development testing

2. Component testing, where several individual units are


integrated to create composite components. Component testing
should focus on testing component interfaces.
3. System testing, where some or all of the components in a
system are integrated and the system is tested as a whole.
System testing should focus on testing component interactions

Falana O. J.
Development testing: Unit testing

• Unit testing is the process of testing program components, such as


methods or object classes. Individual functions or methods are the
simplest type of component.
• Your tests should be calls to these routines with different input
parameters
• When you are testing object classes, you should design your tests
to provide coverage of all of the features of the object. This means
that you should:

Falana O. J.
Development testing: Unit testing

ütest all operations associated with the object;


üset and check the value of all attributes associated with the object;
üput the object into all possible states. This means that you should
simulate all events that cause a state change.

Falana O. J.
Development testing :Component testing

• Software components are often composite components that are


made up of several interacting objects.
• For example, in the weather station system, the reconfiguration
component includes objects that deal with each aspect of the
reconfiguration. You access the functionality of these objects
through the defined component interface

Falana O. J.
Development testing :Component testing

• The figure below illustrates the idea of component interface testing.


• Assume that components A, B, and C have been integrated to create a larger
component or subsystem.
• The test cases are not applied to the
individual components but
rather to the interface of the
composite component created by
combining these components

Falana O. J.
Development testing :Component testing

• The figure below illustrates the idea of component interface testing.


• Assume that components A, B, and C have been integrated to create a larger
component or subsystem.
• The test cases are not applied to the
individual components but
rather to the interface of the
composite component created by
combining these components

Falana O. J.
Development testing :Component testing

• There are different types of interface between program components and,


consequently, different types of interface error that can occur
• Parameter interfaces These are interfaces in which data or sometimes
function references are passed from one component to another
• Shared memory interfaces These are interfaces in which a block of memory
is shared between components. Data is placed in the memory by one
subsystem and retrieved from there by other sub-systems

Falana O. J.
Development testing: Component testing

• Procedural interfaces: These are interfaces in which one


component encapsulates a set of procedures that can be called by
other components. Objects and reusable components have this
form of interface.
• Message passing interfaces These are interfaces in which one
component requests a service from another component by passing
a message to it

Falana O. J.
Development testing: System testing

• System testing during development involves integrating


components to create a version of the system and then testing the
integrated system.
• System testing checks that components are compatible, interact
correctly and transfer the right data at the right time across their
interfaces.

Falana O. J.
Test-driven development

• Test-driven development (TDD) is an approach to program


development in which you interleave testing and code
development
• Essentially, you develop the code incrementally, along with a test
for that increment. You don’t move on to the next increment until
the code that you have developed passes its test

Falana O. J.
Test-driven development

The fundamental TDD process


The fundamental TDD process

Falana O. J.
Test-driven development

• The steps in the process are as follows:


1. You start by identifying the increment of functionality that is
required. This should normally be small and implementable in a
few lines of code.
2. You write a test for this functionality and implement this as an
automated test. This means that the test can be executed and will
report whether or not it has passed or failed.

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

• Release testing is the process of testing a particular release of a


system that is intended for use outside of the development team.
Normally, the system release is for customers and users.
• In a complex project, however, the release could be for other
teams that are developing related systems
• The primary goal of the release testing process is to convince the
supplier of the system that it is good enough for use. If so, it can
be released as a product or delivered
• ,
Falana O. J.
User testing

• User or customer testing is a stage in the testing process in which


users or customers provide input and advice on system testing.
• This may involve formally testing a system that has been
commissioned from an external supplier, or could be an informal
process where users experiment with a new software product to
see if they like it and that it does what they need.

Falana O. J.
Types of user testing

• In practice, there are three different types of user testing:


1. Alpha testing, where users of the software work with the development
team to test the software at the developer’s site.
2. Beta testing, where a release of the software is made available to users to
allow them to experiment and to raise problems that they discover with the
system developers.
3. Acceptance testing, where customers test a system to decide whether or
not it is ready to be accepted from the system developers and deployed in
the customer environment.

Falana O. J.
Debugging

Falana O. J.
Debugging

• Debugging is the process of fixing errors and problems that have


been discovered by testing.
• Using information from the program tests, debuggers use their
knowledge of the programming language and the intended
outcome of the test to locate and repair the program error.

Falana O. J.
Debugging in general

• Basic method of all debugging:


1. Know what your program is supposed to do.
2. Detect when it doesn’t.
3. Fix it.

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

• Programmers seldom start off with an empty program.


• Reasons:
– Most basic or frequently used functions have been written
by other programmers.
– If you write every function by yourself, the source code
may be messy and hard to maintained.
– Less code, less bugs.
– You have product (or homework) deadline.
– Many existing libraries have tune the performance, and
thus are more reliable and robust.

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)

Suppose we want to write a program which


reads a double value from the user.
Then it computes and outputs the square root
of the double value.

Falana O. J.
Square Root Function sqrt()

Falana O. J.
Some functions defined in <cmath> Header

Falana O. J.
USER-DEFINED FUNCTIONS

• The great variety of functions provided by the Standard C++


Library is still not sufficient for most programming tasks.
Programmers also need to be able to define their own functions.
• Here is a simple user defined function
int cube(int x)
{ // returns cube of x:
return x*x*x;
}
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

• Whenever you create your own function, you should immediately


test it with a simple program. Such a program is called a test
driver for the function

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

• The programs we have discussed are generally structured as


functions that call one another in a disciplined, hierarchical
manner.
• A recursive function is a function that calls itself, either directly,
or indirectly (through another function).
• The function actually knows how to solve only the simplest
case(s), or so-called base case(s). If the function is called with a
base case, the function simply returns a result

Falana O. J.
The Factorial Function

• The factorial of a nonnegative integer n, written n! (and


pronounced “n factorial”), is
n · (n – 1) · (n – 2) · … · 1
• The product with 1! equal to 1, and 0! defined to be 1. For
example, 5! is the product 5 · 4 · 3 · 2 · 1,
which is equal to 120

Falana O. J.
Iteratively (non-recursively)

• The factorial of an integer, number, greater than or equal to 0, can


be calculated iteratively (non-recursively) by using a for
statement as follows:
factorial = 1;
for ( int counter = number; counter >= 1; counter-- )
factorial *= counter

Falana O. J.
The Factorial Function

• A recursive definition of the factorial function is arrived at by


observing the following
• algebraic relationship:
• n! = n · (n – 1)!

Falana O. J.
The Factorial Function

Falana O. J.
Recursive power example

• Write method pow that takes integers x and y as parameters and


returns xy.
xy = x * x * x * ... * x (y times, in total)

• 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

• Another way to define the power function:


pow(x, 0) = 1
pow(x, y) = x * pow(x, y-1), y > 0

int pow(int x, int y) {


if (y == 0)
return 1;
else
return x * pow(x, y - 1);
}

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

• A method invoking itself is considered to be direct recursion


• A method could invoke another method, which invokes another, etc.,
until eventually the original method is invoked again
• For example, method m1 could invoke m2, which invokes m3, which
in turn invokes m1 again
• This is called indirect recursion, and requires all the same care as
direct recursion
• It is often more difficult to trace and debug
Indirect Recursion

m1 m2 m3

m1 m2 m3

m1 m2 m3
Assignment

Falana O. J.
STRING PROCESSING

Falana O. J.
INTRODUCTION

• A C-string (also called a character string) is a sequence of


contiguous characters in memory terminated by the NUL
character '\0'.
• C-strings are accessed by variables of type char* (pointer to char).
For example, if s has type char*, then
cout << s << endl;
• will print all the characters stored in memory beginning at the
address s and ending with the first occurrence of the NUL
character.
Falana O. J.
• The C header file <cstring> provides a wealth of special functions
for manipulating C-strings. For example, the call
• strlen(s) will return the number of characters in the C-string s, not
counting its terminating NUL character. These functions all
declare their C-string parameters as pointers to char.

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

• A string object can be initialized with a constructor argument such


as
string text( "Hello" ); // creates a string from a const char *
• which creates a string containing the characters in "Hello", or with
two constructor arguments as in
string name( 8, 'x' ); // string of 8 'x' characters
which creates a string containing eight 'x' characters.

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.

// comparing string1 and string2


int result = ;

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

• Class string provides member function substr for retrieving a


substring from a string.
• The result is a new string object that is copied from the source
string. The Figure below demonstrates substr.
• The program declares and initializes a string at line 9. Line 13
uses member function substr to retrieve a substring from string1.
The first argument specifies the beginning subscript of the desired
substring; the second argument specifies the substring’s length

Falana O. J.
Demonstrating String member function subtr.

Falana O. J.
Swapping strings

• Class string provides member function swap for swapping strings.

Falana O. J.
string Characteristics

• Class string provides member functions for gathering information


about a string’s size, length, capacity, maximum length and other
characteristics.
// display string statistics
void printStatistics( const string & stringRef )
{
cout << "capacity: " << stringRef.capacity() << "\nmax size: "
<< stringRef.max_size() << "\nsize: " << stringRef.size()
<< "\nlength: " << stringRef.length()
<< "\nempty: " << stringRef.empty();
} // end printStatistics
Falana O. J.
Finding Substrings and Characters in a string

• Class string provides const member functions for finding


substrings and characters in a string
• string1.find( "is" )
• string1.find_first_of( "misop" );
• string1.find_last_of( "misop" );

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

• Class string provides member functions for inserting characters


into a string.
• string1.insert( 10, string2 );
• GFDHGF

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

type arrayName[ arraySize ];


• The compiler reserves the appropriate amount of memory. (Recall
that a declaration which reserves memory is more properly known
as a definition in C++.)

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

• There are many algorithms for sorting an array. Although not as


efficient as most others, the
• Bubble Sort is one of the simplest sorting algorithms. It proceeds
through a sequence of iterations, each time moving the next
largest item into its correct position.
• On each iteration, it compares each pair of consecutive elements,
moving the larger element up.

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. }

Mountain Top University


Bubble Sort

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

void sort(float a[],int n)


{ // bubble sort:
for (int i=1; i<n; i++)
// bubble up max{a[0..n-i]}:
for (int j=0; j<n-i; j++)
if (a[j] > a[j+1]) swap(a[j],a[j+1]);
// INVARIANT: a[n-1-i..n-1] is sorted
}
Void swap(float a[j], a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}

Falana O. J.
THE BINARY SEARCH ALGORITHM

• Binary search is a fast search algorithm with run-time complexity of Ο(log


n). This search algorithm works on the principle of divide and conquer. For
this algorithm to work properly, the data collection should be in the sorted
form.
• How Binary Search Works?
• For a binary search to work, it is mandatory for the target array to be sorted.
We shall learn the process of binary search with a pictorial example. The
following is our sorted array and let us assume that we need to search the
location of value 31 using binary search.

Falana O. J.
How Binary Search Works?

• First, we shall determine half of the array by using this formula −


mid = low + (high - low) / 2
• Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the
mid of the array

Falana O. J.
How Binary Search Works?

• Now we compare the value stored at location 4, with the value


being searched, i.e. 31. We find that the value at location 4 is 27,
which is not a match. As the value is greater than 27 and we have
a sorted array, so we also know that the target value must be in the
upper portion of the array.
• We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2

Falana O. J.
How Binary Search Works?

• Our new mid is 7 now. We compare the value stored at location 7


with our target value 31

Falana O. J.
How Binary Search Works?

• We compare the value stored at location 5 with our target value.


We find that it is a match.

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

int index(int, int[], int);


int main()
{ int a[] = { 22,33, 44,55,66,77,88 };
cout << "index(44, a, 7) = " << index(44, a, 7) << endl;
cout << "index(60, a, 7) = " << index(60, a, 7) << endl;
}
int index(int x, int a[], int n)
{ // PRECONDITION: a[0] <= a[1] <= ... <= a[n-1];
// binary search:
int low =0, high = n-1, midpoint;

Falana O. J.
The Binary Search Algorithm contd…

while (low <= high)


{ midpoint = (low + high)/2; // the average of low and high
if (a[midpoint] == x) return midpoint;
if (a[midpoint] < x)
low = midpoint+1; // continue search in a[midpoint+1..high]
else high = midpoint -1; // continue search in a[low..midpoint-1]
}
return n; // x was not found in a[0..n-1]
}
Falana O. J.
Determining whether an Array is Sorted

This program tests a boolean function that determines whether a


given array is nondecreasing.
bool isNondecreasing(int a[],int n);
int main()
{ int a[] = { 22,44, 66,88,44,66,55 };
cout << "isNondecreasing(a,4) = " << isNondecreasing(a,4) <<
endl;
cout << "isNondecreasing(a,7) = " << isNondecreasing(a,7) <<
endl;
}
bool isNondecreasing(int a[],int n)
{ // returns true iff a[0] <= a[1] <= ... <= a[n-1]:
for (int i=1; i<n; i++)
if (a[i]<a[i-1]) return false;
return true;
}
• If the function finds any adjacent pair (a[i-1],a[i]) of elements that decrease
(i.e., a[i]<a[i-1]), then it returns false. If that doesn’t happen, then it returns
true, meaning that the array is nondecreasing
Falana O. J.
Multidimensional Arrays

• Arrays with two dimensions (i.e., subscripts) often represent tables of


values consisting of information arranged in rows and columns.
• To identify a particular table element, we must specify two subscripts.
By convention, the first identifies the element’s row and the second
identifies the element’s column.
• Arrays that require two subscripts to identify a particular element are
called two-dimensional arrays or 2-D arrays. Arrays with two or
more dimensions are known as multidimensional arrays and can
have more than two dimensions.

Falana O. J.
Multidimensional Arrays

• The illustrates a two-dimensional array, a. The array contains


three rows and four columns, so it’s said to be a 3-by-4 array. In
general, an array with m rows and n columns is called an m-by-n
array.

Falana O. J.
Reading and Printing a Two-Dimensional Array

void read(int a[][5]);


void print(cont int a[][5]);
int main()
{
int a[3][5];
read(a);
print(a);
}
Falana O. J.
Function for reading Two-Dimensional Array

void read(int a[][5])


{
cout << "Enter 15 integers,5 per row:”;
for (int i=0; i<3; i++)
{
cout << "Row " << i << ": ";
for (int j=0; j<5; j++)
cin >> a[i][j];
}
}
Falana O. J.
Function for printing Two-Dimensional Array

void print(const int a[][5])


{
for (int i=0; i<3; i++)
{
for (int j=0; j<5; j++)
cout << " " << a[i][j];
cout << endl;
}
}
Falana O. J.
Pointers and References

• THE REFERENCE OPERATOR


• Computer memory can be imagined as a very large array of bytes. For
example, a computer with 256 MB of RAM (256 megabytes of
random-access memory) actually contains an array of 268,435,456
(228) bytes. As an array, these bytes are indexed from 0 to
268,435,455.
• The index of each byte is its memory address. So a 256 MB computer
has memory addresses ranging from 0 to 268,435,455, which is
0x00000000 to 0x0fffffff in hexadecimal
Falana O. J.
• The diagram below represents that array of bytes, each with its
hexadecimal address.
• A variable declaration associates three fundamental
attributes to the variable: its name, its type,
and its memory address. For example,
The Declaration
int n;

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:

• The variable itself is represented by the box. The variable’s name


n is on the left of the box, the variable’s address 0x0064fdf0 is
above the box, and the variable’s type int is below the box.

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

• A reference is an alias or synonym for another variable. It is


declared by the syntax
type& ref-name = var-name;
• where type is the variable’s type, ref-name is the name of the
reference, and var-name is the name of the variable. For example,
in the declaration int& rn = n; // r is a synonym for n
• rn is declared to be a reference to the variable n, which must
already have been declared.

Falana O. J.
REFERENCES

This declares rn as a reference to n:


int main()
{ int n=44;
int& rn=n; // r is a synonym for n
cout << "n = " << n << ", rn = " << rn << endl;
--n;
cout << "n = " << n << ", rn = " << rn << endl;
rn *= 2;
cout << "n = " << n << ", rn = " << rn << endl;
}

Falana O. J.
POINTERS

• The reference operator & returns the memory address of the


variable to which it is applied.
• We can also store the address in another variable. The type of the
variable that stores an address is called a pointer. Pointer variables
have the derived type “pointer to T”, where T is the type of the
object to which the pointer points.

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

• A class is like an array: it is a derived type whose elements have


other types. But unlike an array, the elements of a class may have
different types.
• Any region of storage may generally be regarded as an “object”,
the word is usually used to describe variables whose type is a
class.
• There is much more to object-oriented programming than simply
including classes in your programs

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

• Here x is declared to be an object of the Ratio class.


• It has its own internal data members num and den, and
• it has the ability to call the four class member functions assign(),
convert(), invert(), and print().
• Note that a member function like invert() is called by prefixing its
name with the name of its owner: x.invert().
• Indeed, a member function can only be called this way. We say
that the object x “owns” the call
Falana O. J.
Declaration of member functions

void Ratio::assign(int numerator,int denominator)


{ num = numerator;
den = denominator;
}
double Ratio::convert()
{ return double(num)/den;
}

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

• A constructor is a member function that is invoked automatically


when an object is declared.
• A constructor function must have the same name as the class itself,
and it is declared without return type.
• The following example illustrates how we can replace the
assign() function with a constructor.

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.

You might also like