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

1D Array

The document provides an overview of one-dimensional arrays in C++, including their definition, usefulness, and basic operations such as initialization, input, and output. It emphasizes the importance of arrays in programming, particularly for handling large data sets, and discusses common errors like out-of-bounds access. Additionally, it covers array parameters in functions and introduces concepts related to C-strings and searching algorithms.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

1D Array

The document provides an overview of one-dimensional arrays in C++, including their definition, usefulness, and basic operations such as initialization, input, and output. It emphasizes the importance of arrays in programming, particularly for handling large data sets, and discusses common errors like out-of-bounds access. Additionally, it covers array parameters in functions and introduces concepts related to C-strings and searching algorithms.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

SWE 2314

One-dimensional Arrays

Malik, pages 519-549 in Chapter 8.


Review from Unit 2: Data Types
• Recall that a data type is a set of values
together with a set of allowed operations
on those values.
• C++ data types fall into three categories:
– Simple data types
– Structured data types
– Pointers

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 2


Simple versus Structured Data Types
• Simple data types are the building blocks of
structured data types.
• A variable of a simple data type can store only
one value at a time.
– Examples: int, double, char, bool
• A variable of a structured data type is a
collection of other data items.
– Examples: arrays (Chapter 8), structs (Chapter
9), classes (Chapter 10)
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 3
Partial Hierarchy of Data Types

Data Types

Simple Data Structured Data


Pointers
Types Types

Integral
Floating-Point
(int, bool, Enumeration Arrays structs Classes
(double, …)
char, …)
Arrays

• An array is a collection of a fixed number of


elements (or “components”), all of the same data
type.
• For example, an array might contain:
– Five elements, each of which is an int.
– One hundred elements, each of which is a double.
– Seven thousand elements, each of which is a char.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 5


Why are Arrays Useful?

• The program on page 506 shows how (without


using arrays) to find and display the average of
five test scores, along with a list of the scores
that are less than the average.
– See next slide.
• Doing it this way is not bad for five test scores,
but what if you had 100 test scores?

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 6


Non-Array Example from p. 506
(Example 8-4 on p. 514 shows how to do it with arrays.)
Doing the Same Thing with Arrays
(Example 8-4 on p. 514.)
Making It More Flexible

 The program on the previous slide assumes


you have 5 test scores, and the number 5 is
hard-coded into the code at several places.
 Better way: Declare a constant named
ARRAY_SIZE at the program’s beginning, and
use that constant wherever you need the array
size. Then you only need to make one change
instead of several if you have more than 5 test
scores.
 See next slide…
Making It More Flexible (Improved version of
Example 8-4 on p. 514.)
Array Dimension
• In a one-dimensional array, you can think of
the elements as being arranged in a list.
• In a two-dimensional array, you can think of
the elements as being arranged in a table with
rows and columns.
• Higher-dimensional arrays are also possible,
but we’ll focus on one-dimensional arrays this
week, and two-dimensional arrays next week .

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 11


The Importance of Arrays to
Engineers

 Many engineering problems require you to


manipulate vectors and matrices, which
you’ve probably studied in a math or physics
class.
 In C++, vectors are called one-dimensional
arrays, and matrices are called two-
dimensional arrays.
 The software named MATLAB, which most
engineers are expected to learn, uses
vectors and matrices extensively. Many
concepts that you learn about arrays in C++
will carry over into MATLAB, and vice versa.
Declaring a 1-D Array
• Syntax for declaring a one-dimensional array:

where intExp is any constant expression that


evaluates to a positive integer, and dataType is the
type of the elements.
• Examples:
– int test[5];
– double myArray1[100];
– char myArray2[7000];
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 13
Accessing Array Elements
• Syntax for accessing an array element:

where indexExp is called the index.


– It’s an expression with a nonnegative integer value.
• The value of the index is the position of the
element in the array.
• [] is called the array subscripting operator.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 14


Indexes Start at 0, Not at 1
• The value of the index is the element’s position
in the array.
– The array’s first element has index 0.
– The array’s second element has index 1.
– And so on.
• Forgetting this leads to a common type of error
called an off-by-one error.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 15


Accessing Array Elements (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 16


Accessing Array Elements (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 17


Array Initialization During Declaration
• Arrays can be initialized during declaration.
– Values are placed between curly braces.
– If no array size is given inside the square brackets,
the array’s size is determined by the number of
initial values in the braces.
• Example: Here we declare and initialize an array of
type double with four elements:
double sales[] = {12.25, 32.50, 16.90, 45.68};

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 18


Partial Initialization of Arrays During
Declaration
• If you specify an array size in square brackets
but only give initial values for some of the
elements, the remaining elements are
initialized to 0.
• Example:
int list[10] = {8, 5, 12};
– Declares an array of 10 elements and initializes
list[0] to 8, list[1] to 5, list[2] to 12.
– All other elements are initialized to 0.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 19
Processing One-Dimensional Arrays
• Some basic operations on a 1-D array:
– Initializing the array
– Inputting data into the array from the keyboard
– Displaying data stored in the array
– Copying the array into another array
– Finding the largest and/or smallest element in the array
• Each operation requires you to step through the
array’s elements one by one.
– This is easily accomplished using a loop.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 20
No Aggregate Operations on Arrays
• An aggregate operation is an operation (such as
assignment, input, output, etc.) that treats the
entire array as a single unit.
– C++ does not allow aggregate operations on arrays.
• Example:

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 21


Example: Initializing a One-
Dimensional Array
• Given the declaration:
int list[100]; //array of size 100
• Use a for loop to initialize all array elements
to some value (13 in this case):
We execute this
for (int i = 0; i < 100; i++) statement 100 times,
list[i] = 13; but each time i has a
different value, so each
time we access a
different array element.
• The following aggregate operation is illegal:
list = 13; //Error!!!
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 22
Example: Inputting Values into a One-
Dimensional Array from the Keyboard
• Given the declaration:
int list[100]; //array of size 100
• Use a for loop to input all values from the
keyboard:
for (int i = 0; i < 100; i++)
cin >> list[i];

• The following aggregate operation is illegal:


cin >> list; //Error!!!
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 23
Example: Displaying Values Stored in
a One-Dimensional Array
• Given the declaration:
int list[100] = {0}; //array of size 100
• Use a for loop to display all values:
for (int i = 0; i < 100; i++)
cout << list[i] << endl;

• The following aggregate operation is illegal:


cout << list << endl; //Error!!!

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 24


Example: Copying a One-Dimensional
Array into Another Array
• Given the declaration:
int myList[100] = {0}; //array of size 100
int yourList[100]; //array of size 100
• Use a for loop to copy all values:
for (int i = 0; i < 100; i++)
yourList[i] = myList[i];

• The following aggregate operation is illegal:


yourList = mylist; //Error!!!

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 25


Array Index Out of Bounds
• An array’s index is in bounds if the index is >=0
and <= the array’s size minus 1.
– Otherwise, the index is out of bounds.
• C++ does not guard against indices that are
out of bounds. You (the programmer) must
insure that you never use out-of-bounds
indices. Otherwise your program may fail.
• The next three slides show three examples
that fail in different ways.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 26
Array Index Out of Bounds: Example 1

 The compiler will not catch this error. It’s a logic


error that will produce garbage results when you
run the program.
Array Index Out of Bounds: Example 2

 The compiler will not catch this error. It’s a run-


time error that will crash your program when you
run it.
Array Index Out of Bounds: Example 3

 The compiler will catch this error and refuse to run the
program.
Arrays as Parameters to Functions
• When used as function parameters, arrays are
always passed by reference (never by value).
• But you do not use the symbol & when
declaring an array as a formal parameter.
• Example:

• As shown here, we usually omit the array’s


size in the parameter list.
– If you provide the size, the compiler ignores it.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 30
Example: Array as a Parameter to a
Function
A Potential Problem with Passing
Parameters by Reference
• Whenever a parameter is passed by reference, the
called function can change the value of the calling
function’s variable. What if you don’t want this?
• With parameters of simple data types (int,
double, etc.), you have the option of passing the
parameter by value instead of by reference, thus
preventing the called function from changing the
calling function’s value.
• But with arrays, you don’t have this option.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 32


Solution to Potential Problem:
Constant Formal Parameters
• Solution: To prevent a called function from
changing the value of the calling function’s
variable when passing by reference, use
const in the formal parameter list.
• Example:

• Within the function example, any attempt to


change the values in y will result in an error.
See next slide.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 33
Example: A Constant Parameter
A Function Cannot Return an Array
• C++ does not allow
functions to return a
value of type array.
The code shown here
won’t run.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 35


Base Address of an Array and Array in
Computer Memory
• An array’s base address is the address
(memory location) of the array’s first element.
• Example:
– If list is a one-dimensional array, its base address
is the address of list[0].
• When an array is passed as a parameter, the
base address of the actual array is passed to
the formal parameter.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 36


An Array’s Size Cannot Be a Variable
• In most example programs above we have used an integer inside
the [] when we declared an array.
• Example: int testScores[20];
• You can use an integer constant instead.
• Example:
const int NUMBER_OF_STUDENTS = 20;
int testScores1[NUMBER_OF_STUDENTS];
• But you cannot use an integer variable.
• Example:
int numberOfStudents = 20;
int testScores2[numberOfStudents]; //ERROR!

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 37


An Array’s Size Cannot Be a Variable
(cont’d.)
• This is a serious limitation because it prevents you from letting the
user choose the size of an array.
• Example:
int numberOfStudents;
cout << "How many students?" << endl;
cin >> numberOfStudents;
int testScores2[numberOfStudents]; //ERROR!
• C++ provides a way to get around this limitation, but it requires you
to use pointers, which we won’t look at until later in the course.
• If you’re interested, look ahead to the section in Chapter 12
called “Dynamic Arrays”.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 38


Parallel Arrays
• We say two (or more) arrays are parallel if
their corresponding elements hold related
information. Example:
int studentId[50];
char courseGrade[50];
• C++ does not “know” that these two
arrays have anything to do with each
other. They are parallel only in the
programmer’s mind.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 39
Review: Two Kinds of Strings in C+
+
 In C++, the term “string” can mean:
 The string data type, which is new to C+
+. (It did not exist in C.)
 To use it, you must include the <string>
header file.
 We’ve been using this data type since Week 2.

 Discussed in Chapter 7.

A null-terminated character array. This was


the only kind of string in C.
 The book refers to these as “C-strings.”
 Much less convenient than C++’s string data

type.
 Discussed in Chapter 8, but we won’t use it. 40
A Brief Look at C-Strings
• A character array is an array whose elements
are of type char.
• A C-string is a special type of character array:
it is a null-terminated character array, which
means that it ends with the null character.
– The null character is the character whose ASCII
code is 0. To type it in a program, you type '\0'.
Example:
char name[10] = “John”;

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 41


Searching and Sorting Arrays
 Two classic computer-science
problems that have been studied
exhaustively over the past six
decades are:
 How to search an array to see whether it
contains a given value.
 How to sort the elements in an array (for

example, from smallest to largest in an


integer array).
 The next slides show two primitive solutions to
these problems. Chapter 16 (which we won’t
study) goes into much more detail. 42
One Method for Searching an Array:
Sequential Search
• To search an array for a given item using a
sequential search (or linear search):
– Start from the first array element.
– Compare each element in the array with the value
being searched for.
– Continue until the item is found or you’ve reached
the end of the array.

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 43


One Method for Sorting an Array:
Selection Sort
• To sort an array using a selection sort:
rearrange the list by selecting an element and
moving it to its proper position.
• Steps:
– Find the smallest element in the unsorted portion
of the list.
– Move it to the top of the unsorted portion by
swapping it with the element currently there.
– Start again with the rest of the list.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition 44
Selection Sort: Example

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 45

You might also like