Introduction to Computer Science
Download
Report
Transcript Introduction to Computer Science
Introduction to Computer Science
COMP 51 – Fall 2012 – Section 2
Arrays
2
Arrays
3
Motivation for Arrays
Projects and labs to-date have worked with small
amounts of data
Ex: Write a function to find the smaller (or larger) of
two integers
Suppose we need to work with a large amount of
data?
Ex: Write a function to find the smallest (or largest)
value of a set of 1000 integers
4
Motivation for Arrays
Do you need to declare individual variables?
int num1, num2, num3, num4, …
Do you need to save data to each variable individually?
cin >> num1 >> num2 >> num3 >> num4 …
Do you need to pass a huge list of arguments to your
function?
result = min(num1, num2, num3, …);
Does your function need to have a huge number of if-
statements to compare all these variables?
5
Arrays
Fortunately, no!
High-level languages (include C++) utilize a concept
called arrays
An array is a single variable that can hold multiple
items of the same type
So, in the previous example, you can use a single
variable that holds 1000 integers
6
Array Items
Refer to each item in the array variable by a
number
Subscript or index number
The items are numbered starting with 0
Array (variable name): numbersToProcess
<item>
<item>
<item>
<item>
<item>
0
1
2
3
4
…
7
Array Syntax
How do I declare arrays?
int myArray[100];
Declares an new array
Name: myArray
Type: Integers
Maximum number of elements in array: 100
Numbered 0-99
Must declare an array before using it
Just like other variables and functions
8
Array Syntax
How do I access individual items in an array?
Example using element 16 of array “myArray”
myArray[15]
Print it out:
cout << myArray[15];
Use it in a calculation:
sum = myArray[15] + 32;
Use it in a function call:
myFunction(myArray[15]);
Why did we use [15] when we wanted the 16th
element?
9
Array Syntax
The index number can be an expression
These produce identical results
Both access element number 15 in the array
cout << myArray[15];
int n = 8;
cout << myArray[n+7];
This makes it easy to access all the items in an array
using a for or while statement
10
Example
Read in 1000 integers, and print them out in reverse
order
int values[1000];
for(int i=0; i<1000; i++)
{
cin >> values[i];
}
for(int i=999; i>=0; i--)
{
cout << values[i] << endl;
}
11
Pitfall – Arrays start at Zero, not One!
Take an array of 100 items
int myArray[100];
The first array index is ZERO
myArray[0]
The last array index is 99
myArray[99]
Array indexes run from 0 to <ArraySize> - 1
Attempting to access myArray[100] will cause problems!
12
Arrays in Memory
Address
1022
1023
Value
Think of memory as a very large
table where we can store data
1024
Each element in the table is
1025
numbered consecutively
1026
This number is called the
1027
address
1028
1029
If you’ve used a spreadsheet
1030
application, it’s similar to the
rows or columns
1031
…
13
Arrays in Memory
Address
Value
1022
15
1023
8421
var1
var2
1024
1025
1026
1027
Let’s declare some integer
1028
variables
1029
int var1 = 15;
1030
1031
…
int var2 = 8421;
14
Arrays in Memory
Address
Value
1022
15
1023
8421
1024
1025
1026
1027
1028
1029
1030
1031
…
19
Now let’s declare an
var1
var2
myArray[0]
myArray[1]
myArray[2]
myArray[3]
myArray[4]
var3
array and another
variable
int myArray[5];
int var3 = 19;
15
Arrays in Memory
Address
Value
1022
15
1023
8421
1024
1441
1025
1527
1026
1621
1027
1745
1028
1893
1029
19
1030
1031
…
Now let’s set some
var1
values
var2
myArray[3] = 1745;
myArray[0]
myArray[1] = 1527;
myArray[1]
myArray[2] = 1621;
myArray[4] = 1893;
myArray[2]
myArray[0] = 1441;
myArray[3]
myArray[4] Once the array is
defined, we can
access the items in
any order
16
Pitfall – Array Out-of-Bounds
Address
Value
1022
15
1023
8421
1024
1441
1025
1527
1026
1621
1027
1745
1028
1893
1029
19 1921
1030
1031
…
What happens if I
var1
attempt to write a
var2
value outside of the
myArray[0]
array range?
myArray[1]
myArray[2] myArray[5] = 1921;
myArray[3] I overwrite the
myArray[4]
contents of var3!
(which happened to
come next in
memory)
Bad!!
17
Pitfall – Array Out-of-Bounds
Address
Value
1022
15
1023
8421
1024
1441
1025
1527
1026
1621
1027
1745
1028
1893
1029
19
1030
1031
…
What happens if I
attempt to read a
var1
value outside of the
var2
array range?
myArray[0]
myArray[1] value=myArray[5];
myArray[2]
myArray[3] I don’t get an error
myArray[4] Instead, I get the
contents of var3!
(which happened to
come next in
Bad!!
memory)
18
Array Initialization
We can declare and initialize variables at the same time
int myVar = 15;
We can also declare and initialize arrays at the same
time
int myArray[5] = {1,2,3,4,5}; equivalent to
int myArray[5];
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;
19
Array Initialization Tips
You don’t have to specify the max size of the array when
initializing it
int myArray[] =
{10, 15, 20, 25, 30, 35, 40};
Empty brackets tells the compiler to automatically
create an array big enough to hold the initialized values
In this case, 7 elements
But you can’t later try to change the size of the array; if
it’s supposed to be bigger, you must either declare it as
such, or add “dummy” initializers
20
Setting Array Size
You could just use a literal number
int myArray[20];
But, a better way to do it is to declare a constant
variable first
const int ARRAY_SIZE=20;
int myArray[ARRAY_SIZE];
Now we can use the identifier to make the code easier
to understand (and avoid bugs)!
for(int i=0; i<ARRAY_SIZE; i++)
All-caps name is programmer convention for constants
21
Pitfall – Array Size
Array size must be known to the compiler at
compile-time
You cannot do this:
int size;
cin >> size;
int myArray[size];
There is a way to accomplish this concept that you’ll
learn later (dynamic allocation), but it requires a
different way to create the array
22
Pitfall – Copying Array
It’s reasonable to need to copy an array
const int ARRAY_SIZE = 10;
int array1[ARRAY_SIZE] = {…};
int array2[ARRAY_SIZE];
array2 = array1;
This does not work!
Compiler should produce an error here
23
Copying Array
The correct way to copy an array
const int ARRAY_SIZE = 10;
int array1[ARRAY_SIZE] = {…};
int array2[ARRAY_SIZE];
for(int i=0; i<ARRAY_SIZE; i++)
{
array2[i] = array1[i];
}
Must copy array element-by-element
24
Pitfall – Outputting Array
Likewise, you may want to output an array
const int ARRAY_SIZE = 10;
int array1[ARRAY_SIZE] = {…};
cout << array1;
This does not work!
Program will instead print out the memory address
of the first item in array1
25
Outputting Array
The correct way to output an array
const int ARRAY_SIZE = 10;
int array1[ARRAY_SIZE] = {…};
for(int i=0; i<ARRAY_SIZE; i++)
{
cout << array1[i] << endl;
}
Must also output array element-by-element
26
Arrays Elements in Function Calls
You can use individual array elements in functions calls
Example function:
calculateSomething(double var1);
Takes a double as an argument
Example array:
Pass-by-value and pass-by-reference both work
double myArray[10];
Example function calls:
calculateSomething(myArray[3]);
calculateSomething(myArray[i]);
As long as i evaluates to an int between 0 and 9
27
Whole Arrays in Function Calls
You can also use an entire array in your function call
This works using pass-by-reference
If you modify the array inside the function, the original
array (outside of the function) is actually modified
There is only one copy of the data storage element (the
array), with two labels…
Don’t need to use the & symbol
Arrays are always pass-by-reference
You cannot do pass-by-value for an entire array, only for
one element of the array
28
Whole Arrays in Function Calls
// This function will read in <size> integers
// and save them in <array>
void populateArray(int array[], int size)
{
cout << “Enter ” << size << “ integers:” << endl;
for(int i=0; i<size; i++)
{
Empty brackets so we can
cin >> array[i];
accept arrays of any size
}
}
No square bracket or
index – we want the
entire array
int main()
{
const int NUMBER_OF_GRADES = 25;
int grades[NUMBER_OF_GRADES];
populateArray(grades, NUMBER_OF_GRADES);
}
29
Arrays as Function Return Values
Functions cannot return an array
They can only return single values
One int, one double, one char, …
We’ll learn a different way to accomplish this idea
later (by using pointers…)
30
Summary of Arrays and Functions
Individual array elements (indexed variables) can be
passed as arguments to a function
Pass-by reference or pass-by-value
An entire array may be passed as arguments
Essentially pass-by-reference only
Do not need the & symbol
Array size is not known by the function
Usually need to pass it as an argument to
Nice benefit: the same function can be used for different
sized arrays!
31
Special Preview!
Strings
32
Declaring Strings
String library
Add a new type of data: Many characters in a row
Works similar to built-in data types like int, char,
and double
Include the library:
#include <string>
using namespace std;
Declare a new string variable and initialize
string mystring1 = “AMD”;
33
Strings – Basic Operators
Some of the basic operators work with strings too!
At least, the ones that make sense…
Use + to concatenate strings
Use = to assign strings
string str1=“Computer “;
string str2=“Science“;
string str3;
str3 = str1+ str2;
// Value is “Computer Science”
34
String – Basic Operators
Use == or != to compare strings
Use cout to output values
string str1=“Orange”;
string str2=“Apple“;
if(str1 != str2)
cout << str1 << “ is not equal to “ <<
str2;
Use cin to input values
string str1, str2;
cin >> str1 >> str2;
Input finishes on whitespace!
“University of the Pacific”
str1 = “University”
str2 = “of”
35
String – Member Functions
at(i) – Character at position n (count starts at 0)
Example:
string str1=“Computer”;
cout << str1.at(3); // Should print ‘p’
And many more functions!
36
Questions?
?