Transcript Arrays 1

One Dimensional Arrays
•
•
•
•
•
•
Arrays
Array Declaration
Array Initialization
Accessing Array & Array elements
Const Array Size
Passing Array to Functions
1
Array Definition
• An array is a data structure that
stores a list of similar elements
using one variable name.
• Also, an Array
contiguous block
shares a common
d a ta t yp e ( i n t ,
refers to a
of data that
identifier and
c h a r , e tc ) .
• Example: array mark stores
all class marks (12 students in
the class)
int mark[12];
Name of the array is mark
mark[0]
90
mark[1]
85
mark[2]
63
mark[3]
70
mark[4]
97
mark[5]
mark[7]
40
77
73
mark[8]
83
mark[9]
60
mark[10]
87
45
mark[6]
mark[11]
Position number of the
element within array mark.
2
Array Definition
int mark[12];
• Individual array elements are
specified using the array name and
the location of the element in the
array which is called an offset or
subscript.
•
In C++, offset numbering always
starts at 0. Hence the first array
element is the element at
offest/subscript 0 (e.g. m[0])
• The name of the array stores the
memory address of the first element
of the array.
Name of the array is mark
mark[0]
90
mark[1]
85
mark[2]
63
mark[3]
70
mark[4]
97
mark[5]
mark[7]
40
77
73
mark[8]
83
mark[9]
60
mark[10]
87
45
mark[6]
mark[11]
Position number of the element within
array mark.
Notice: there is no element mark[12]
element.
3
Array Mark: Initialization
//This program initializes array mark at declaration
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int mark[12]={90,85,63,70,97,40,77,73,83,60,87,45};
//printing array mark elements
for (int i=0; i<12; i++) //you must use a loop to access and print array elements
cout<<setw(5)<<mark[i];
cout<<endl;
return 0;
}
4
Array Mark: Reading Elements from Keyboard
//This program reads array mark elements from the user
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int mark[12];
//read array mark elements from user
for (int i=0; i<12; i++) {
cout<<"Enter student "<<i+1<<" mark: ";
cin>>mark[i];
}
cout<<"\nClass Marks:\n";
//print array mark on the screen
for (int i=0; i<12; i++)
cout<<setw(5)<<mark[i];
cout<<endl;
return 0;
}
5
Fill Array with random numbers
//This program assigns random numbers to array numbers
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int SIZE=3;
int main()
{
int numbers[SIZE],
srand(time(0));
//fill array numbers with random numbers in the range 10-20
for (int i=0; i<SIZE; i++)
numbers[i]=rand()%(11) + 10;
//print array numbers
for (int i=0; i<SIZE; i++)
cout<<numbers[i]<<endl;
return 0;
}
6
C++ Syntax: Array Declaration 1
• Syntax:
data_type identifier [size];
data_type identifier [size] [= initialization list];
Note: size is an integer constant or a constant variable.
• Example:
double A[8];
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7]
?
?
?
?
?
?
?
?
A is a variable representing an array that is a block
of 8 consecutive memory locations, i.e. 8
elements: A[0]..A[7]. Note there is no A[8].
Accessing A[8] will cause an error.
7
Array Declaration 2
• When declaring arrays, specify 3 things:
1. Array Name
2. Array data type: Any data type
3. Number of elements
Syntax: type arrayName[ arraySize ];
int c[ 10 ]; // c is an array of 10 integers
float d[ 3284 ]; // d is an array of 3284 floats
• Declaring multiple arrays of same type
– Use comma separated list, like regular variables
int a, b[ 100 ], x[ 27 ];
8
Initializing Arrays 1
• Initializing array elements (initialization at declaration)
char vowels[5] = {'a', 'e', 'i', 'o', 'u'};
bool ansKey[] ={true, true, false, true, false, false};
char word[] = "Hello";
vowels
'a'
'e'
'i'
'o'
'u'
ansKey
true true false true false false
word
'H'
'e'
'l'
'l'
'o'
'\0'
9
Initializing Arrays 2
•
Initializing arrays – several ways
double g[21];
– for loop
for(int k=0;k<=20;k++)
• Set each element
g[k]= k * 0.5;
– Initializer list
• Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
int s[ 4 ] = { 8,6};
• If not enough initializers, rightmost elements will be 0
• If too many syntax error
– To set every element to same value
int n[ 5 ] = { 0 };
– If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array
10
// Initializing an array with a declaration.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// use initializer list to initialize array n
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
//display header
cout << "Element" << setw( 13 ) << "Value" << endl;
// output contents of array n in tabular format
for ( int i = 0; i < 10; i++ )
cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;
Element
0
1
2
3
4
5
6
7
8
9
Value
32
27
64
18
95
14
90
70
60
37
return 0; // indicates successful termination
} // end main
11
const Array Size
• Array size: Can be specified in two ways:
1. Using a constant integer value
– int temp[20];
2. Using a constant variable using const
- const int size = 20; //symbolic constant
-
int temp[size];
– Constants cannot be changed
– Constants must be initialized when declared
– Also called named constants or read-only variables
12
// Initialize array s to the even integers from 2 to 20.
#include <iostream>
#include <iomanip>
using namespace std;
// constant variable can be used to specify array size
const int arraySize = 10;
int main()
{
int s[ arraySize ]; // array s has 10 elements
for ( int i = 0; i < arraySize; i++ ) // set the values
s[ i ] = 2 + 2 * i;
cout << "Element" << setw( 13 ) << "Value" << endl;
// output contents of array s in tabular format
for ( int j = 0; j < arraySize; j++ )
cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;
return 0; // indicates successful termination
} // end main
13
Element
0
1
2
3
4
5
6
7
8
9
Value
2
4
6
8
10
12
14
16
18
20
14
// Compute Array Product as A * B
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int A[10 ]={1,3,4,5,6,7}, B[ 10 ]={9,8,7,5,6,4,2,3,1,11}, Product[ 10 ];
for ( int i = 0; i < 10; i++ ) // compute Product array elements
Product [i] = A[i] * B[i];
// display header
cout << "A" << setw( 5) << "B" << setw( 8) << "A * B" << endl;
cout << "----------------\n";
// output contents of arrays in tabular format
for ( int i = 0; i < 10; i++ )
cout << A[i] << setw( 5) << B[i] << setw( 6) << Product[i] << endl;
return 0;
} // end main
15
16
Functions and arrays
• An array identifier/variable, without subscripts,
references the starting address (first element) of the
array.
• Therefore, array variables are automatically passed by
reference. ie the starting address is passed, no size
information or elements. There is no need to attach the
reference & symbol.
• In C++, arrays do not know their size.
• So, functions working with arrays need to receive the
array size as a parameter using pass by value.
17
Passing Arrays to Functions
• Arrays passed-by-reference
– Be default, array variable when passed to a function it is passed
by reference.
– Functions can modify original array data (or memory locations)
– Function knows where the array is stored
ReadArray(marks, SIZE);
• Individual array elements passed-by-value
– Like regular variables
– cout<<square( myArray[3] )<<endl;
18
Passing Arrays to Functions
• Functions Prototypes
void ReadArray( int A[], int arraySize );
or
void ReadArray( int [], int ); //parameter name omitted
– Names optional in prototype, both are valid.
– Both take an integer array and a single integer
– No need for array size between brackets
• Ignored by compiler
19