SlideShare a Scribd company logo
1 of 50
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Chapter 7
Arrays
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Overview
7.1 Introduction to Arrays
7.2 Arrays in Functions
7.3 Programming with Arrays
7.4 Multidimensional Arrays
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
7.1
Introduction to Arrays
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Introduction to ArraysAn array is used to process a collection of
data
of the same typeExamples: A list of names
A list of temperaturesWhy do we need
arrays?Imagine keeping track of 5 test scores, or 100, or 1000 in
memory How would you name all the variables?How would you
process each of the variables?
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Declaring an ArrayAn array, named score, containing five
variables
of type int can be declared as
int score[ 5 ];This is like declaring 5 variables of
type int:
score[0], score[1], … , score[4]The value in brackets is
calledA subscriptAn index
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
The Array VariablesThe variables making up the array are
referred to
asIndexed variablesSubscripted variablesElements of the
arrayThe number of indexed variables in an array is
the declared size, or size, of the arrayThe largest index is one
less than the sizeThe first index value is zero
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Array Variable TypesAn array can have indexed variables of
any type
All indexed variables in an array are of the
same typeThis is the base type of the array
An indexed variable can be used anywhere an
ordinary variable of the base type is used
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Using [ ] With ArraysIn an array declaration, [ ]'s enclose the
size
of the array such as this array of 5 integers:
int score [5];When referring to one of the
indexed variables,
the [ ]'s enclose a number identifying one of
the indexed variablesscore[3] is one of the indexed variablesThe
value in the [ ]'s can be any expression that evaluates to one of
the integers 0 to (size -1)
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Indexed Variable AssignmentTo assign a value to an indexed
variable, use
the assignment operator:
int n = 2;
score[n + 1] = 99;In this example, variable
score[3] is assigned 99
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Loops And Arraysfor-loops are commonly used to step through
arraysExample: for (i = 0; i < 5; i++)
{
cout << score[i] << " off by "
<< (max – score[i]) << endl;
}
could display the difference between each score and the
maximum score stored in an array
Slide 7- *
First index is 0
Display 7.1
Last index is (size – 1)
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.1
Slide 7- *
Back
Next
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Constants and ArraysUse constants to declare the size of an
arrayUsing a constant allows your code to be easily
altered for use on a smaller or larger set of dataExample:
const int NUMBER_OF_STUDENTS = 50;
int score[NUMBER_OF_STUDENTS];
…
for ( i = 0; i < NUMBER_OF_STUDENTS;
i++)
cout << score[i] << " off by "
<< (max – score[i]) << endl;Only the value of
the constant must be changed to make this code work for any
number of students
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Variables and DeclarationsMost compilers do not allow the use
of a variable
to declare the size of an array
Example: cout << "Enter number of students: ";
cin >> number;
int score[number];
This code is illegal on many compilers
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Array Declaration SyntaxTo declare an array, use the syntax:
Type_Name Array_Name[Declared_Size];Type_Name can be
any typeDeclared_Size can be a constant to make your
program more versatileOnce declared, the array consists of the
indexed
variables:
Array_Name[0] to Array_Name[Declared_Size -1]
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Computer MemoryComputer memory consists of numbered
locations called bytesA byte's number is its address
A simple variable is stored in consecutive bytesThe number of
bytes depends on the variable's type
A variable's address is the address of its first byte
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Arrays and MemoryDeclaring the array int a[6]Reserves
memory for six variables of type intThe variables are stored one
after anotherThe address of a[0] is rememberedThe addresses of
the other indexed variables is not
rememberedTo determine the address of a[3]Start at a[0]Count
past enough memory for three integers to find a[3]
Slide 7- *
Display 7.2
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.2
Slide 7- *
Back
Next
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Array Index Out of RangeA common error is using a
nonexistent indexIndex values for int a[6] are the values 0
through 5An index value not allowed by the array declaration is
out of rangeUsing an out of range index value doe not produce
an error message!
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Out of Range ProblemsIf an array is declared as: int a[6];
and an integer is declared as: int i = 7;Executing the statement
a[i] = 238; causes…The computer to calculate the address of the
illegal a[7](This address could be where some other variable is
stored) The value 238 is stored at the address calculated for
a[7]No warning is given!
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Initializing ArraysTo initialize an array when it is declaredThe
values for the indexed variables are enclosed in braces and
separated by commasExample: int children[3] = { 2, 12, 1
};
Is equivalent to:
int children[3];
children[0] = 2;
children[1] = 12;
children[2] = 1;
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Default ValuesIf too few values are listed in an initialization
statementThe listed values are used to initialize the first of the
indexed variablesThe remaining indexed variables are
initialized to a zero of the base typeExample: int a[10] = {5,
5};
initializes a[0] and a[1] to 5 and
a[2] through a[9] to 0
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Un-initialized ArraysIf no values are listed in the array
declaration,
some compilers will initialize each variable to a
zero of the base typeDO NOT DEPEND ON THIS!
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Section 7.1 ConclusionCan you
Describe the difference between a[4] and
int a[5]?
Show the output of
char symbol[3] = {'a', 'b', 'c'};
for (int index = 0; index < 3; index++)
cout << symbol[index];
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
7.2
Arrays in Functions
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Arrays in FunctionsIndexed variables can be arguments to
functionsExample: If a program contains these declarations:
int i, n, a[10];
void my_function(int n);
Variables a[0] through a[9] are of type int, making these calls
legal:
my_function( a[ 0 ] );
my_function( a[ 3 ] );
my_function( a[ i ] );
Slide 7- *
Display 7.3
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.3
Slide 7- *
Back
Next
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Arrays as Function Arguments
A formal parameter can be for an entire arraySuch a parameter
is called an array parameterIt is not a call-by-value parameterIt
is not a call-by-reference parameterArray parameters behave
much like call-by-reference parameters
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Array Parameter DeclarationAn array parameter is indicated
using empty
brackets in the parameter list such as
void fill_up(int a[ ], int size);
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Function Calls With ArraysIf function fill_up is declared in this
way:
void fill_up(int a[ ], int size);
and array score is declared this way:
int score[5], number_of_scores;
fill_up is called in this way:
fill_up(score, number_of_scores);
Slide 7- *
Display 7.4
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.4
Slide 7- *
Back
Next
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Function Call DetailsA formal parameter is identified as an
array
parameter by the [ ]'s with no index expression
void fill_up(int a[ ], int size);
An array argument does not use the [ ]'s
fill_up(score, number_of_scores);
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Array Formal ParametersAn array formal parameter is a
placeholder for
the argumentWhen an array is an argument in a function call, an
action performed on the array parameter is performed on the
array argument
The values of the indexed variables can be changed by the
function
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Array Argument DetailsWhat does the computer know about an
array?The base type The address of the first indexed
variableThe number of indexed variablesWhat does a function
know about an array
argument?The base typeThe address of the first indexed variable
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Array Parameter ConsiderationsBecause a function does not
know the size of
an array argument…The programmer should include a formal
parameter that specifies the size of the arrayThe function can
process arrays of various sizesFunction fill_up from Display 7.4
can be used to fill
an array of any size:
fill_up(score, 5);
fill_up(time, 10);
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
const ModifierArray parameters allow a function to change the
values stored in the array argumentIf a function should not
change the values of the
array argument, use the modifier constAn array parameter
modified with const is a
constant array parameterExample:
void show_the_world(const int a[ ], int size);
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Using const With ArraysIf const is used to modify an array
parameter:
const is used in both the function declaration and definition to
modify the array parameter
The compiler will issue an error if you write code that changes
the values stored in the array parameter
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Function Calls and constIf a function with a constant array
parameter
calls another function using the const array
parameter as an argument…
The called function must use a constant
array parameter as a placeholder for the array
The compiler will issue an error if a function is
called that does not have a const array parameter to accept the
array argument
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
const Parameters Example double compute_average(int a[ ], int
size);
void show_difference(const int a[ ], int size)
{
double average = compute_average(a, size);
…
}compute_average has no constant array parameterThis code
generates an error message because
compute_average could change the array parameter
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Returning An ArrayRecall that functions can return a value of
type int, double, char, …, or a class type
Functions cannot return arrays
We learn later how to return a pointer to an array
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Case Study:
Production GraphProblem Definition: We are writing a program
for the Apex Plastic
Spoon CompanyThe program will display a bar graph showing
the production of each of four plants for a weekEach plant has
separate records for each departmentInput is entered plant by
plantOutput shows one asterisk for each 1000 units, and
production is rounded to the nearest 1,000 units
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Analysis of The ProblemUse an array named production to hold
total
production of each plantProduction for plant n is stored in
production[n-1]
Program must scale production to nearest
1,000 units to display asterisks in the bar
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Production Graph Sub-TasksAnalysis leads to the following
sub-tasksinput_data: Read input for each plant
Set production [plant_number -1]
to the total production for plant
number nscale: For each plant, change
production[plant_number]
to the correct number of asterisksgraph:
Output the bar graph
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
More Analysis DetailsThe entire array will be an argument for
the
functions we write to perform the subtasksWe will also include
a formal parameter for the sizeThe size of the array is equal to
the number of plantsWe will use a constant for the number of
plants
The function declarations and main function
for the production graph program are found in
Slide 7- *
Display 7.5
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.5
Slide 7- *
Back
Next
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Algorithm Design: input_dataWe must read all departments'
data for each
plant and add them to produce a plant's totalAlgorithm for
input_data:
for plant_number is 1, 2, …, last_plant_number
do the following
Read all the data for plant number plant_number
Sum the numbers
Set production[plant_number – 1] to the total
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Coding input_dataThe algorithm can be translated to C++ as:
void input_data(int a [ ], int last_plant_number)
{
using namespace std;
for (int plant_number = 1;
plant_number <= last_plant_number;
plant_number++)
{
cout << endl
<< "Enter production for plant"
<< plant_number << endl;
get_total( a[plant_number -1] );
}
}
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Testing input_dataEach function should be tested in a program
in
which it is the only untested functionBecause input_data calls
get_total, get_total
is tested firstOnce tested, get_total can be used to test
input_data
Slide 7- *
Display 7.6 (1)
Display 7.6 (2)
Display 7.6 (3)
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.6 (1/3)
Slide 7- *
Back
Next
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.6 (2/3)
Slide 7- *
Back
Next
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.6 (3/3)
Slide 7- *
Back
Next
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Test Data for input_dataRemember that input_data should be
testedWith a plant that contains no production figures
With a plant having only one production figure
With a plant having more than one figure
With zero and non-zero production figures
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Algorithm for scalescale changes the value of the indexed
variable
to show the whole number of asterisks to printScale is called
using
scale (production, NUMBER_OF_PLANTS);
and its algorithm is
for (int index = 0; index < size; index++)
Divide the value of a[index] by 1,000 and round the result to
the nearest integer
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Coding scaleThe code for scale, below, uses a function named
round that must be defined as wellvoid scale(int a[ ], int size)
{
for (int index = 0; index < size; index++)
a[index] = round (a[index] / 1000.0);
}
Slide 7- *
Why not 1000?
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Function floorFunction round, called by scale, uses the floor
function from the cmath libraryThe floor function returns the
first whole number less than its argument:
floor (3.4) returns 3
floor (3.9) returns 3Adding 0.5 to the argument for
floor is how round performs its task
floor (3.4 + 0.5) returns 3
floor (3.9 + 0.5) returns 4
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Testing scaleTo test scaleFirst test roundScale should be tested
with arguments that Are 0Round upRound down
Slide 7- *
Display 7.7 (1)
Display 7.7 (2)
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.7 (1/2)
Slide 7- *
Back
Next
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.7
(2/2)
Slide 7- *
Back
Next
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Function graphThe design of graph is quite straightforward
and not included here
The complete program to produce the bar
graph is found in
Slide 7- *
Display 7.8 (1)
Display 7.8 (2)
Display 7.8 (3)
Display 7.8 (4)
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.8
(1/4)
Slide 7- *
Next
Back
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.8 (2/4)
Slide 7- *
Back
Next
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.8 (3/4)
Slide 7- *
Next
Back
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.8
(4/4)
Slide 7- *
Next
Back
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Section 7.2 ConclusionCan you
Write a function definition for a function called
one_more, which has a formal parameter for an array of integers
and increases the value of each array element by one. Are other
formal parameters needed?
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
7.3
Programming with Arrays
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Programming With ArraysThe size needed for an array is
changeableOften varies from one run of a program to anotherIs
often not known when the program is written
A common solution to the size problemDeclare the array size to
be the largest that could be neededDecide how to deal with
partially filled arrays
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Partially Filled ArraysWhen using arrays that are partially
filledFunctions dealing with the array may not need to know the
declared size of the array, only how many elements are stored in
the array A parameter, number_used, may be sufficient to
ensure that referenced index values are legalA function such as
fill_array in Display 7.9 needs to know the declared size of the
array
Slide 7- *
Display 7.9 (1)
Display 7.9 (2)
Display 7.9 (3)
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.9 (1/3)
Slide 7- *
Back
Next
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.9 (2/3)
Slide 7- *
Back
Next
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.9
(3/3)
Slide 7- *
Back
Next
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Constants as ArgumentsWhen function fill_array (Display 7.9)
is called,
MAX_NUMBER_SCORES is used as an
argument Can't MAX_NUMBER_SCORES be used directly
without making it an argument?Using
MAX_NUMBER_SCORES as an argument makes it clear that
fill_array requires the array's declared size This makes
fill_array easier to be used in other programs
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Searching ArraysA sequential search is one way to search
an array for a given valueLook at each element from first to last
to see if the target value is equal to any of the array
elementsThe index of the target value can be returned to
indicate where the value was found in the arrayA value of -1
can be returned if the value was not found
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
The search FunctionThe search function of Display 7.10…Uses
a while loop to compare array elements to the target valueSets a
variable of type bool to true if the target
value is found, ending the loopChecks the boolean variable
when the loop ends to see if the target value was foundReturns
the index of the target value if found,
otherwise returns -1
Slide 7- *
Display 7.10 (1)
Display 7.10 (2)
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.10 (1/2)
Slide 7- *
Next
Back
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.10 (2/2)
Slide 7- *
Back
Next
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Program Example:
Sorting an ArraySorting a list of values is very common
taskCreate an alphabetical listingCreate a list of values in
ascending orderCreate a list of values in descending orderMany
sorting algorithms existSome are very efficientSome are easier
to understand
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Program Example:
The Selection Sort AlgorithmWhen the sort is complete, the
elements of the
array are ordered such that
a[0] < a[1] < … < a [ number_used -1]This leads to an
outline of an algorithm:
for (int index = 0; index < number_used; index++)
place the indexth smallest element in a[index]
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Program Example:
Sort Algorithm DevelopmentOne array is sufficient to do our
sortingSearch for the smallest value in the arrayPlace this value
in a[0], and place the value that was in a[0] in the location
where the smallest was foundStarting at a[1], find the smallest
remaining value swap it with the value currently in a[1]Starting
at a[2], continue the process until the array is sorted
Slide 7- *
Display 7.11
Display 7.12 (1-2)
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.11
Slide 7- *
Back
Next
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.12 (1/2)
Slide 7- *
Back
Next
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.12 (2/2)
Slide 7- *
Back
Next
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Section 7.3 ConclusionCan you
Write a program that will read up to 10 letters into an array and
write the letters back to the screen in the reverse order?
abcd should be output as dcba
Use a period as a sentinel value to mark the end of input
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
7.4
Multidimensional Arrays
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Multi-Dimensional ArraysC++ allows arrays with multiple
index valueschar page [30] [100];
declares an array of characters named pagepage has two index
values:
The first ranges from 0 to 29
The second ranges from 0 to 99Each index in enclosed in
its own bracketsPage can be visualized as an array of
30 rows and 100 columns
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Index Values of pageThe indexed variables for array page are
page[0][0], page[0][1], …, page[0][99]
page[1][0], page[1][1], …, page[1][99] …
page[29][0], page[29][1], … , page[29][99]
page is actually an array of size 30page's base type is an array
of 100 characters
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Multidimensional Array ParametersRecall that the size of an
array is not needed
when declaring a formal parameter:
void display_line(const char a[ ], int size); The base type of a
multi-dimensional array must
be completely specified in the parameter
declarationvoid display_page(const char page[ ] [100],
int size_dimension_1);
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Program Example:
Grading ProgramGrade records for a class can be stored in a
two-dimensional arrayFor a class with 4 students and 3 quizzes
the array could be declared as
int grade[4][3];The first array index refers to
the number of a studentThe second array index refers to a quiz
numberSince student and quiz numbers start with one,
we subtract one to obtain the correct index
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Grading Program:
average scoresThe grading program uses one-dimensional
arrays to store…Each student's average scoreEach quiz's
average scoreThe functions that calculate these averages
use global constants for the size of the arraysThis was done
because the functions seem to be
particular to this program
Slide 7- *
Display 7.13 (1-3)
Display 7.14
Display 7.15
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.13 (1/3)
Slide 7- *
Back
Next
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.13 (2/3)
Slide 7- *
Back
Next
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.13 (3/3)
Slide 7- *
Back
Next
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.14
Slide 7- *
Back
Next
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Display 7.15
Slide 7- *
Back
Next
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Section 7.5 ConclusionCan you
Write code that will fill the array a(declared below) with
numbers typed at the keyboard? The numbers will be input
fiver per line, on four lines.
int a[4][5];
Slide 7- *
*
Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Chapter 7 - End
Slide 7- *
*
Project2_Sample_Files/project02_sample.exe
Project2_Sample_Files/test.txt
8
1
11 55 -3 0 1 5 -8 66
CO SCI 243 Programming Project # 2
100 points
Your goal is to implement an application that reads a file,
modify its content, and writes the
modification back to the same file. The file includes 3 lines of
integers. The first line indicates the
number of integers on the third line. The second line indicates
which integer on the third line has been
selected (active). And the third line lists all the integers
(maximum of 10).
Your application should have a menu that is constantly
displayed on the screen (see the menu below).
Right below the menu, the program should display list of all
integers in the file (third line). Also it
should show which integer is currently selected (active).
The user should be able to select a menu item by entering its
associated number or by pressing one of
the indicated extended keys on the keyboard.
“Insert” will insert an integer before the selected item and
makes the newly inserted item active. The
integer is typed by the user. If the list is full, insertion will not
be possible. Do not accept incorrect
values.
“Delete” deletes the active item.
“Sort” sorts the list in ascending order. The active item after the
sort is same as the active item before
the sort.
“Select Down” selects the next item in the list. If the last item
is selected, this option selects the first
item in the list.
“Select Up” selects the previous item in the list. If the first item
is selected, this option selects the last
item in the list.
“Move Down” moves the selected item one position down. If
the last item is selected, moving down
will not be possible.
“Move Up” moves the selected item one position up. If the first
item is selected, moving up will not be
possible.
“Exit” ends the application.
Make sure to use the top-down design to break your program to
many simpler tasks (at least one
function per task)
Do not use global variables.
Make sure to check the special cases. Example: list is full or list
is empty.
Your program should copy the content of the file into an array
and variables when you start the
program. The program write back the content of the array and
variables into the file when you exit the
program. When you are using the program, you should modify
the array and variables and not the file.
Make sure to test your program completely before submission.
Do not forget to add comments.
Submit your well-documented C++ program via Canvas.
Menu:
Insert "1" or "Insert" key
Delete "2" or "Delete" key
Sort "3" or "F2" key
Select Down "4" or "Down Arrow" key
Select Up "5" or "Up Arrow" key
Move Down "6" or "Page Down" key
Move up "7" or "Page Up" key
Exit "8" or "F1" key

More Related Content

Similar to Copyright © 2012 Pearson Addison-Wesley. All rights reserve.docx

C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
ANUSUYA S
 

Similar to Copyright © 2012 Pearson Addison-Wesley. All rights reserve.docx (20)

Object Oriented Programming - 5.1. Array
Object Oriented Programming - 5.1. ArrayObject Oriented Programming - 5.1. Array
Object Oriented Programming - 5.1. Array
 
Savitch ch 022
Savitch ch 022Savitch ch 022
Savitch ch 022
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
arrays
arraysarrays
arrays
 
C_Arrays.pptx
C_Arrays.pptxC_Arrays.pptx
C_Arrays.pptx
 
Programming in Computer Science- Pointers in C++.ppt
Programming in Computer Science- Pointers in C++.pptProgramming in Computer Science- Pointers in C++.ppt
Programming in Computer Science- Pointers in C++.ppt
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
pointers
pointerspointers
pointers
 
Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptx
 
Lecture06 computer applicationsie1_dratifshahzad
Lecture06 computer applicationsie1_dratifshahzadLecture06 computer applicationsie1_dratifshahzad
Lecture06 computer applicationsie1_dratifshahzad
 
pointers
pointerspointers
pointers
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptx
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 
savitchch02-C++Basic Computer Programming.ppt
savitchch02-C++Basic Computer Programming.pptsavitchch02-C++Basic Computer Programming.ppt
savitchch02-C++Basic Computer Programming.ppt
 

More from vanesaburnand

InstructionsYou are a research group from BSocialMarketing, LLC.docx
InstructionsYou are a research group from BSocialMarketing, LLC.docxInstructionsYou are a research group from BSocialMarketing, LLC.docx
InstructionsYou are a research group from BSocialMarketing, LLC.docx
vanesaburnand
 
InstructionsWrite a paper about the International Monetary Syste.docx
InstructionsWrite a paper about the International Monetary Syste.docxInstructionsWrite a paper about the International Monetary Syste.docx
InstructionsWrite a paper about the International Monetary Syste.docx
vanesaburnand
 
InstructionsTITLEF14-2Beginning an 8-column work sheet for a merch.docx
InstructionsTITLEF14-2Beginning an 8-column work sheet for a merch.docxInstructionsTITLEF14-2Beginning an 8-column work sheet for a merch.docx
InstructionsTITLEF14-2Beginning an 8-column work sheet for a merch.docx
vanesaburnand
 
InstructionsThe  Public Archaeology Presentation invites you.docx
InstructionsThe  Public Archaeology Presentation invites you.docxInstructionsThe  Public Archaeology Presentation invites you.docx
InstructionsThe  Public Archaeology Presentation invites you.docx
vanesaburnand
 
InstructionsThe tools of formal analysis are the starting point .docx
InstructionsThe tools of formal analysis are the starting point .docxInstructionsThe tools of formal analysis are the starting point .docx
InstructionsThe tools of formal analysis are the starting point .docx
vanesaburnand
 
InstructionsThe Homeland Security (DHS) agency is intended t.docx
InstructionsThe Homeland Security (DHS) agency is intended t.docxInstructionsThe Homeland Security (DHS) agency is intended t.docx
InstructionsThe Homeland Security (DHS) agency is intended t.docx
vanesaburnand
 

More from vanesaburnand (20)

InstructionsYou are to create YOUR OWN example of each of t.docx
InstructionsYou are to create YOUR OWN example of each of t.docxInstructionsYou are to create YOUR OWN example of each of t.docx
InstructionsYou are to create YOUR OWN example of each of t.docx
 
InstructionsYou are a research group from BSocialMarketing, LLC.docx
InstructionsYou are a research group from BSocialMarketing, LLC.docxInstructionsYou are a research group from BSocialMarketing, LLC.docx
InstructionsYou are a research group from BSocialMarketing, LLC.docx
 
InstructionsYou are attending an international journalist event.docx
InstructionsYou are attending an international journalist event.docxInstructionsYou are attending an international journalist event.docx
InstructionsYou are attending an international journalist event.docx
 
InstructionsWrite the Organizational section of your project pap.docx
InstructionsWrite the Organizational section of your project pap.docxInstructionsWrite the Organizational section of your project pap.docx
InstructionsWrite the Organizational section of your project pap.docx
 
InstructionsWrite a two-page (double spaced, Times New Roman S.docx
InstructionsWrite a two-page (double spaced, Times New Roman S.docxInstructionsWrite a two-page (double spaced, Times New Roman S.docx
InstructionsWrite a two-page (double spaced, Times New Roman S.docx
 
InstructionsWrite a thesis statement in response to the topi.docx
InstructionsWrite a thesis statement in response to the topi.docxInstructionsWrite a thesis statement in response to the topi.docx
InstructionsWrite a thesis statement in response to the topi.docx
 
InstructionsWhat You will choose a current issue of social.docx
InstructionsWhat You will choose a current issue of social.docxInstructionsWhat You will choose a current issue of social.docx
InstructionsWhat You will choose a current issue of social.docx
 
InstructionsWrite a paper about the International Monetary Syste.docx
InstructionsWrite a paper about the International Monetary Syste.docxInstructionsWrite a paper about the International Monetary Syste.docx
InstructionsWrite a paper about the International Monetary Syste.docx
 
InstructionsWrite a comprehensive medical report on a disease we.docx
InstructionsWrite a comprehensive medical report on a disease we.docxInstructionsWrite a comprehensive medical report on a disease we.docx
InstructionsWrite a comprehensive medical report on a disease we.docx
 
InstructionsWhether you believe” in evolution or not, why is it.docx
InstructionsWhether you believe” in evolution or not, why is it.docxInstructionsWhether you believe” in evolution or not, why is it.docx
InstructionsWhether you believe” in evolution or not, why is it.docx
 
InstructionsWe have been looking at different psychological .docx
InstructionsWe have been looking at different psychological .docxInstructionsWe have been looking at different psychological .docx
InstructionsWe have been looking at different psychological .docx
 
InstructionsTITLEF14-2Beginning an 8-column work sheet for a merch.docx
InstructionsTITLEF14-2Beginning an 8-column work sheet for a merch.docxInstructionsTITLEF14-2Beginning an 8-column work sheet for a merch.docx
InstructionsTITLEF14-2Beginning an 8-column work sheet for a merch.docx
 
InstructionsThis written assignment requires the student to inve.docx
InstructionsThis written assignment requires the student to inve.docxInstructionsThis written assignment requires the student to inve.docx
InstructionsThis written assignment requires the student to inve.docx
 
InstructionsThe Art Form Most Meaningful to MePick the form .docx
InstructionsThe Art Form Most Meaningful to MePick the form .docxInstructionsThe Art Form Most Meaningful to MePick the form .docx
InstructionsThe Art Form Most Meaningful to MePick the form .docx
 
InstructionsThink of a specific topic and two specific kin.docx
InstructionsThink of a specific topic and two specific kin.docxInstructionsThink of a specific topic and two specific kin.docx
InstructionsThink of a specific topic and two specific kin.docx
 
InstructionsThere are different approaches to gathering risk da.docx
InstructionsThere are different approaches to gathering risk da.docxInstructionsThere are different approaches to gathering risk da.docx
InstructionsThere are different approaches to gathering risk da.docx
 
InstructionsThe  Public Archaeology Presentation invites you.docx
InstructionsThe  Public Archaeology Presentation invites you.docxInstructionsThe  Public Archaeology Presentation invites you.docx
InstructionsThe  Public Archaeology Presentation invites you.docx
 
InstructionsThe tools of formal analysis are the starting point .docx
InstructionsThe tools of formal analysis are the starting point .docxInstructionsThe tools of formal analysis are the starting point .docx
InstructionsThe tools of formal analysis are the starting point .docx
 
InstructionsThe Homeland Security (DHS) agency is intended t.docx
InstructionsThe Homeland Security (DHS) agency is intended t.docxInstructionsThe Homeland Security (DHS) agency is intended t.docx
InstructionsThe Homeland Security (DHS) agency is intended t.docx
 
InstructionsThe student should describe how learning abou.docx
InstructionsThe student should describe how learning abou.docxInstructionsThe student should describe how learning abou.docx
InstructionsThe student should describe how learning abou.docx
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 

Recently uploaded (20)

fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

Copyright © 2012 Pearson Addison-Wesley. All rights reserve.docx

  • 1. Copyright © 2012 Pearson Addison-Wesley. All rights reserved. * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional Arrays Slide 7- *
  • 2. * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 7.1 Introduction to Arrays * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Introduction to ArraysAn array is used to process a collection of data of the same typeExamples: A list of names A list of temperaturesWhy do we need arrays?Imagine keeping track of 5 test scores, or 100, or 1000 in memory How would you name all the variables?How would you process each of the variables? Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved.
  • 3. Declaring an ArrayAn array, named score, containing five variables of type int can be declared as int score[ 5 ];This is like declaring 5 variables of type int: score[0], score[1], … , score[4]The value in brackets is calledA subscriptAn index Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. The Array VariablesThe variables making up the array are referred to asIndexed variablesSubscripted variablesElements of the arrayThe number of indexed variables in an array is the declared size, or size, of the arrayThe largest index is one less than the sizeThe first index value is zero Slide 7- * *
  • 4. Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Array Variable TypesAn array can have indexed variables of any type All indexed variables in an array are of the same typeThis is the base type of the array An indexed variable can be used anywhere an ordinary variable of the base type is used Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Using [ ] With ArraysIn an array declaration, [ ]'s enclose the size of the array such as this array of 5 integers: int score [5];When referring to one of the indexed variables, the [ ]'s enclose a number identifying one of the indexed variablesscore[3] is one of the indexed variablesThe value in the [ ]'s can be any expression that evaluates to one of the integers 0 to (size -1) Slide 7- *
  • 5. * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Indexed Variable AssignmentTo assign a value to an indexed variable, use the assignment operator: int n = 2; score[n + 1] = 99;In this example, variable score[3] is assigned 99 Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Loops And Arraysfor-loops are commonly used to step through arraysExample: for (i = 0; i < 5; i++) { cout << score[i] << " off by "
  • 6. << (max – score[i]) << endl; } could display the difference between each score and the maximum score stored in an array Slide 7- * First index is 0 Display 7.1 Last index is (size – 1) * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.1 Slide 7- * Back Next * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Constants and ArraysUse constants to declare the size of an
  • 7. arrayUsing a constant allows your code to be easily altered for use on a smaller or larger set of dataExample: const int NUMBER_OF_STUDENTS = 50; int score[NUMBER_OF_STUDENTS]; … for ( i = 0; i < NUMBER_OF_STUDENTS; i++) cout << score[i] << " off by " << (max – score[i]) << endl;Only the value of the constant must be changed to make this code work for any number of students Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Variables and DeclarationsMost compilers do not allow the use of a variable to declare the size of an array Example: cout << "Enter number of students: "; cin >> number;
  • 8. int score[number]; This code is illegal on many compilers Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Array Declaration SyntaxTo declare an array, use the syntax: Type_Name Array_Name[Declared_Size];Type_Name can be any typeDeclared_Size can be a constant to make your program more versatileOnce declared, the array consists of the indexed variables: Array_Name[0] to Array_Name[Declared_Size -1] Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Computer MemoryComputer memory consists of numbered
  • 9. locations called bytesA byte's number is its address A simple variable is stored in consecutive bytesThe number of bytes depends on the variable's type A variable's address is the address of its first byte Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Arrays and MemoryDeclaring the array int a[6]Reserves memory for six variables of type intThe variables are stored one after anotherThe address of a[0] is rememberedThe addresses of the other indexed variables is not rememberedTo determine the address of a[3]Start at a[0]Count past enough memory for three integers to find a[3] Slide 7- * Display 7.2 * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.2 Slide 7- * Back Next
  • 10. * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Array Index Out of RangeA common error is using a nonexistent indexIndex values for int a[6] are the values 0 through 5An index value not allowed by the array declaration is out of rangeUsing an out of range index value doe not produce an error message! Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Out of Range ProblemsIf an array is declared as: int a[6]; and an integer is declared as: int i = 7;Executing the statement a[i] = 238; causes…The computer to calculate the address of the illegal a[7](This address could be where some other variable is stored) The value 238 is stored at the address calculated for a[7]No warning is given! Slide 7- * *
  • 11. Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Initializing ArraysTo initialize an array when it is declaredThe values for the indexed variables are enclosed in braces and separated by commasExample: int children[3] = { 2, 12, 1 }; Is equivalent to: int children[3]; children[0] = 2; children[1] = 12; children[2] = 1; Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Default ValuesIf too few values are listed in an initialization statementThe listed values are used to initialize the first of the indexed variablesThe remaining indexed variables are initialized to a zero of the base typeExample: int a[10] = {5, 5};
  • 12. initializes a[0] and a[1] to 5 and a[2] through a[9] to 0 Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Un-initialized ArraysIf no values are listed in the array declaration, some compilers will initialize each variable to a zero of the base typeDO NOT DEPEND ON THIS! Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Section 7.1 ConclusionCan you Describe the difference between a[4] and int a[5]? Show the output of char symbol[3] = {'a', 'b', 'c'};
  • 13. for (int index = 0; index < 3; index++) cout << symbol[index]; Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 7.2 Arrays in Functions * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Arrays in FunctionsIndexed variables can be arguments to functionsExample: If a program contains these declarations: int i, n, a[10]; void my_function(int n); Variables a[0] through a[9] are of type int, making these calls legal: my_function( a[ 0 ] );
  • 14. my_function( a[ 3 ] ); my_function( a[ i ] ); Slide 7- * Display 7.3 * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.3 Slide 7- * Back Next Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Arrays as Function Arguments A formal parameter can be for an entire arraySuch a parameter is called an array parameterIt is not a call-by-value parameterIt is not a call-by-reference parameterArray parameters behave much like call-by-reference parameters Slide 7- * *
  • 15. Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Array Parameter DeclarationAn array parameter is indicated using empty brackets in the parameter list such as void fill_up(int a[ ], int size); Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Function Calls With ArraysIf function fill_up is declared in this way: void fill_up(int a[ ], int size); and array score is declared this way: int score[5], number_of_scores; fill_up is called in this way: fill_up(score, number_of_scores); Slide 7- * Display 7.4
  • 16. * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.4 Slide 7- * Back Next * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Function Call DetailsA formal parameter is identified as an array parameter by the [ ]'s with no index expression void fill_up(int a[ ], int size); An array argument does not use the [ ]'s fill_up(score, number_of_scores); Slide 7- * *
  • 17. Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Array Formal ParametersAn array formal parameter is a placeholder for the argumentWhen an array is an argument in a function call, an action performed on the array parameter is performed on the array argument The values of the indexed variables can be changed by the function Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Array Argument DetailsWhat does the computer know about an array?The base type The address of the first indexed variableThe number of indexed variablesWhat does a function know about an array argument?The base typeThe address of the first indexed variable Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights
  • 18. reserved. Array Parameter ConsiderationsBecause a function does not know the size of an array argument…The programmer should include a formal parameter that specifies the size of the arrayThe function can process arrays of various sizesFunction fill_up from Display 7.4 can be used to fill an array of any size: fill_up(score, 5); fill_up(time, 10); Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. const ModifierArray parameters allow a function to change the values stored in the array argumentIf a function should not change the values of the array argument, use the modifier constAn array parameter modified with const is a constant array parameterExample:
  • 19. void show_the_world(const int a[ ], int size); Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Using const With ArraysIf const is used to modify an array parameter: const is used in both the function declaration and definition to modify the array parameter The compiler will issue an error if you write code that changes the values stored in the array parameter Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Function Calls and constIf a function with a constant array parameter calls another function using the const array parameter as an argument… The called function must use a constant array parameter as a placeholder for the array
  • 20. The compiler will issue an error if a function is called that does not have a const array parameter to accept the array argument Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. const Parameters Example double compute_average(int a[ ], int size); void show_difference(const int a[ ], int size) { double average = compute_average(a, size); … }compute_average has no constant array parameterThis code generates an error message because compute_average could change the array parameter Slide 7- * *
  • 21. Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Returning An ArrayRecall that functions can return a value of type int, double, char, …, or a class type Functions cannot return arrays We learn later how to return a pointer to an array Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Case Study: Production GraphProblem Definition: We are writing a program for the Apex Plastic Spoon CompanyThe program will display a bar graph showing the production of each of four plants for a weekEach plant has separate records for each departmentInput is entered plant by plantOutput shows one asterisk for each 1000 units, and production is rounded to the nearest 1,000 units Slide 7- * *
  • 22. Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Analysis of The ProblemUse an array named production to hold total production of each plantProduction for plant n is stored in production[n-1] Program must scale production to nearest 1,000 units to display asterisks in the bar Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Production Graph Sub-TasksAnalysis leads to the following sub-tasksinput_data: Read input for each plant Set production [plant_number -1] to the total production for plant number nscale: For each plant, change production[plant_number] to the correct number of asterisksgraph: Output the bar graph Slide 7- *
  • 23. * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. More Analysis DetailsThe entire array will be an argument for the functions we write to perform the subtasksWe will also include a formal parameter for the sizeThe size of the array is equal to the number of plantsWe will use a constant for the number of plants The function declarations and main function for the production graph program are found in Slide 7- * Display 7.5 * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.5 Slide 7- * Back Next
  • 24. * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Algorithm Design: input_dataWe must read all departments' data for each plant and add them to produce a plant's totalAlgorithm for input_data: for plant_number is 1, 2, …, last_plant_number do the following Read all the data for plant number plant_number Sum the numbers Set production[plant_number – 1] to the total Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Coding input_dataThe algorithm can be translated to C++ as:
  • 25. void input_data(int a [ ], int last_plant_number) { using namespace std; for (int plant_number = 1; plant_number <= last_plant_number; plant_number++) { cout << endl << "Enter production for plant" << plant_number << endl; get_total( a[plant_number -1] ); } } Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved.
  • 26. Testing input_dataEach function should be tested in a program in which it is the only untested functionBecause input_data calls get_total, get_total is tested firstOnce tested, get_total can be used to test input_data Slide 7- * Display 7.6 (1) Display 7.6 (2) Display 7.6 (3) * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.6 (1/3) Slide 7- * Back Next Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.6 (2/3) Slide 7- *
  • 27. Back Next Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.6 (3/3) Slide 7- * Back Next Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Test Data for input_dataRemember that input_data should be testedWith a plant that contains no production figures With a plant having only one production figure With a plant having more than one figure With zero and non-zero production figures Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Algorithm for scalescale changes the value of the indexed variable
  • 28. to show the whole number of asterisks to printScale is called using scale (production, NUMBER_OF_PLANTS); and its algorithm is for (int index = 0; index < size; index++) Divide the value of a[index] by 1,000 and round the result to the nearest integer Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Coding scaleThe code for scale, below, uses a function named round that must be defined as wellvoid scale(int a[ ], int size) { for (int index = 0; index < size; index++) a[index] = round (a[index] / 1000.0); } Slide 7- * Why not 1000?
  • 29. * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Function floorFunction round, called by scale, uses the floor function from the cmath libraryThe floor function returns the first whole number less than its argument: floor (3.4) returns 3 floor (3.9) returns 3Adding 0.5 to the argument for floor is how round performs its task floor (3.4 + 0.5) returns 3 floor (3.9 + 0.5) returns 4 Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Testing scaleTo test scaleFirst test roundScale should be tested with arguments that Are 0Round upRound down Slide 7- * Display 7.7 (1)
  • 30. Display 7.7 (2) * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.7 (1/2) Slide 7- * Back Next Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.7 (2/2) Slide 7- * Back Next Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Function graphThe design of graph is quite straightforward and not included here
  • 31. The complete program to produce the bar graph is found in Slide 7- * Display 7.8 (1) Display 7.8 (2) Display 7.8 (3) Display 7.8 (4) * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.8 (1/4) Slide 7- * Next Back Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.8 (2/4) Slide 7- * Back Next
  • 32. Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.8 (3/4) Slide 7- * Next Back Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.8 (4/4) Slide 7- * Next Back Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Section 7.2 ConclusionCan you Write a function definition for a function called one_more, which has a formal parameter for an array of integers and increases the value of each array element by one. Are other formal parameters needed? Slide 7- * *
  • 33. Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 7.3 Programming with Arrays * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Programming With ArraysThe size needed for an array is changeableOften varies from one run of a program to anotherIs often not known when the program is written A common solution to the size problemDeclare the array size to be the largest that could be neededDecide how to deal with partially filled arrays Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Partially Filled ArraysWhen using arrays that are partially filledFunctions dealing with the array may not need to know the declared size of the array, only how many elements are stored in the array A parameter, number_used, may be sufficient to
  • 34. ensure that referenced index values are legalA function such as fill_array in Display 7.9 needs to know the declared size of the array Slide 7- * Display 7.9 (1) Display 7.9 (2) Display 7.9 (3) * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.9 (1/3) Slide 7- * Back Next * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.9 (2/3) Slide 7- * Back
  • 35. Next * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.9 (3/3) Slide 7- * Back Next * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Constants as ArgumentsWhen function fill_array (Display 7.9) is called, MAX_NUMBER_SCORES is used as an argument Can't MAX_NUMBER_SCORES be used directly without making it an argument?Using MAX_NUMBER_SCORES as an argument makes it clear that fill_array requires the array's declared size This makes fill_array easier to be used in other programs Slide 7- *
  • 36. * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Searching ArraysA sequential search is one way to search an array for a given valueLook at each element from first to last to see if the target value is equal to any of the array elementsThe index of the target value can be returned to indicate where the value was found in the arrayA value of -1 can be returned if the value was not found Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. The search FunctionThe search function of Display 7.10…Uses a while loop to compare array elements to the target valueSets a variable of type bool to true if the target value is found, ending the loopChecks the boolean variable when the loop ends to see if the target value was foundReturns the index of the target value if found, otherwise returns -1 Slide 7- *
  • 37. Display 7.10 (1) Display 7.10 (2) * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.10 (1/2) Slide 7- * Next Back * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.10 (2/2) Slide 7- * Back Next *
  • 38. Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Program Example: Sorting an ArraySorting a list of values is very common taskCreate an alphabetical listingCreate a list of values in ascending orderCreate a list of values in descending orderMany sorting algorithms existSome are very efficientSome are easier to understand Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Program Example: The Selection Sort AlgorithmWhen the sort is complete, the elements of the array are ordered such that a[0] < a[1] < … < a [ number_used -1]This leads to an outline of an algorithm: for (int index = 0; index < number_used; index++) place the indexth smallest element in a[index]
  • 39. Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Program Example: Sort Algorithm DevelopmentOne array is sufficient to do our sortingSearch for the smallest value in the arrayPlace this value in a[0], and place the value that was in a[0] in the location where the smallest was foundStarting at a[1], find the smallest remaining value swap it with the value currently in a[1]Starting at a[2], continue the process until the array is sorted Slide 7- * Display 7.11 Display 7.12 (1-2) * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.11 Slide 7- * Back Next
  • 40. * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.12 (1/2) Slide 7- * Back Next * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.12 (2/2) Slide 7- * Back Next * Copyright © 2012 Pearson Addison-Wesley. All rights reserved.
  • 41. Section 7.3 ConclusionCan you Write a program that will read up to 10 letters into an array and write the letters back to the screen in the reverse order? abcd should be output as dcba Use a period as a sentinel value to mark the end of input Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 7.4 Multidimensional Arrays * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Multi-Dimensional ArraysC++ allows arrays with multiple index valueschar page [30] [100]; declares an array of characters named pagepage has two index values:
  • 42. The first ranges from 0 to 29 The second ranges from 0 to 99Each index in enclosed in its own bracketsPage can be visualized as an array of 30 rows and 100 columns Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Index Values of pageThe indexed variables for array page are page[0][0], page[0][1], …, page[0][99] page[1][0], page[1][1], …, page[1][99] … page[29][0], page[29][1], … , page[29][99] page is actually an array of size 30page's base type is an array of 100 characters Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved.
  • 43. Multidimensional Array ParametersRecall that the size of an array is not needed when declaring a formal parameter: void display_line(const char a[ ], int size); The base type of a multi-dimensional array must be completely specified in the parameter declarationvoid display_page(const char page[ ] [100], int size_dimension_1); Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Program Example: Grading ProgramGrade records for a class can be stored in a two-dimensional arrayFor a class with 4 students and 3 quizzes the array could be declared as int grade[4][3];The first array index refers to the number of a studentThe second array index refers to a quiz numberSince student and quiz numbers start with one, we subtract one to obtain the correct index
  • 44. Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Grading Program: average scoresThe grading program uses one-dimensional arrays to store…Each student's average scoreEach quiz's average scoreThe functions that calculate these averages use global constants for the size of the arraysThis was done because the functions seem to be particular to this program Slide 7- * Display 7.13 (1-3) Display 7.14 Display 7.15 * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.13 (1/3)
  • 45. Slide 7- * Back Next Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.13 (2/3) Slide 7- * Back Next Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.13 (3/3) Slide 7- * Back Next Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.14 Slide 7- * Back Next
  • 46. * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Display 7.15 Slide 7- * Back Next Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Section 7.5 ConclusionCan you Write code that will fill the array a(declared below) with numbers typed at the keyboard? The numbers will be input fiver per line, on four lines. int a[4][5]; Slide 7- * * Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 - End Slide 7- *
  • 47. * Project2_Sample_Files/project02_sample.exe Project2_Sample_Files/test.txt 8 1 11 55 -3 0 1 5 -8 66 CO SCI 243 Programming Project # 2 100 points Your goal is to implement an application that reads a file, modify its content, and writes the modification back to the same file. The file includes 3 lines of integers. The first line indicates the number of integers on the third line. The second line indicates which integer on the third line has been selected (active). And the third line lists all the integers (maximum of 10).
  • 48. Your application should have a menu that is constantly displayed on the screen (see the menu below). Right below the menu, the program should display list of all integers in the file (third line). Also it should show which integer is currently selected (active). The user should be able to select a menu item by entering its associated number or by pressing one of the indicated extended keys on the keyboard. “Insert” will insert an integer before the selected item and makes the newly inserted item active. The integer is typed by the user. If the list is full, insertion will not be possible. Do not accept incorrect values. “Delete” deletes the active item. “Sort” sorts the list in ascending order. The active item after the sort is same as the active item before the sort. “Select Down” selects the next item in the list. If the last item is selected, this option selects the first item in the list. “Select Up” selects the previous item in the list. If the first item is selected, this option selects the last
  • 49. item in the list. “Move Down” moves the selected item one position down. If the last item is selected, moving down will not be possible. “Move Up” moves the selected item one position up. If the first item is selected, moving up will not be possible. “Exit” ends the application. Make sure to use the top-down design to break your program to many simpler tasks (at least one function per task) Do not use global variables. Make sure to check the special cases. Example: list is full or list is empty. Your program should copy the content of the file into an array and variables when you start the program. The program write back the content of the array and variables into the file when you exit the program. When you are using the program, you should modify the array and variables and not the file. Make sure to test your program completely before submission.
  • 50. Do not forget to add comments. Submit your well-documented C++ program via Canvas. Menu: Insert "1" or "Insert" key Delete "2" or "Delete" key Sort "3" or "F2" key Select Down "4" or "Down Arrow" key Select Up "5" or "Up Arrow" key Move Down "6" or "Page Down" key Move up "7" or "Page Up" key Exit "8" or "F1" key