You are on page 1of 42

C++ Arrays

Outline
 What is an array?
 Declaring C++ arrays
 Initializing one-dimensional arrays
 Reading and Writing one-dimensional arrays
 Passing one-dimensional arrays to functions
 Manipulating one-dimensional arrays:
 Searching for something
 Rearranging stored values
 Computing and storing series of values
What Is An Array?
 An array is a collection of values that have the
same data type, e.g.
 A collection of int data values or
 A collection of bool data values
 We refer to all stored values in an array by its
name
 If we would like to access a particular value
stored in an array, we specify its index (i.e. its
position relative to the first array value)
 The first array index is always 0
 The second value is stored in index 1
 Etc.
How To Declare Arrays
 To declare an array in C++, you should specify the
following things
 The data type of the values which will be stored in the array
 The name of the array (i.e. a C++ identifier that will be used to
access and update the array values)
 The dimensionality of the array:
 One dimensional (i.e. list of values ),
 Two-dimension array (a matrix or a table), etc.
 The size of each dimension
 Examples
 int x[10]; // An integer array named x with size 10
 float GPA[30]; // An array to store the GPA for 30 students
 int studentScores[30][5]; // A two-dimensional array to store the
scores of 5 exams for 30 students
One-dimensional Arrays
 We use one-dimensional (ID) arrays to store and
access list of data values in an easy way by
giving these values a common name, e.g.
int x[4]; // all values are named x 10 x[0]
x[0] = 10; // the 1st value is 10
nd
5 x[1]
x[1] = 5; // the 2 value is 5
x[2] = 20; // the 3rd value is 20 20 x[2]

x[3] = 30; // the 4th value is 30 30 x[3]


Array Indices and
Out-of-bound Run-time Error
 All C++ one-dimensional arrays with N
entries start at index 0 and ended at index
N-1
const int N=5;
int v[N]; // this array contains 5 entries
 It is a common error to try to access the
Nth entry, e.g. v[5] or V[N], since the index
of the last array entry is N-1, not N
Initializing One-dimensional Arrays
 There are two common ways to initialize one-dimensional arrays
 Using for loop, e.g.
int x[10];
for( int index=0; index<10; index++) x [index] = index+1 ;
 Specifying list of values while declaring the 1D array, e.g.
int x[10] = {1,2,3,4,5,6,7,8,9,10};
int y[ ] = {0,0,0}; // this array contains 3 entries with 0 values
double z[100] = {0}; // this array contains 100
// entries, all of which are initialized by 0
double w[20] = {5,3,1}; // this array contains 20 entries,
// the first three entries are initialized by 5, 3, and1 respectively
// while the remaining 17 entries are automatically initialized by 0
bool pass[10] = {true, true}; // this array contains 10 entries.
// The first two entries are initialized to true, while the remaining 8
// entries are automatically initialized to false
Storing Values in 1D Arrays
 Wrong way:
Int x[10];
cin >> x; // you cannot do that unless you
// overload the >> operator!
// Wait until you take CSCI-110
 Correct way:
int x[10];
// Reading one value at a time from the user:
for (int index=0; index<10; index++)
cin >> x[index];
Displaying Values Stored
in 1D Arrays
 Wrong way:
Int x[10];
cout << x; // you cannot do that unless you
// overload the << operator!
// Wait until you take CSCI-110
 Correct way:
int x[10];
// Displaying one value per line to the user:
for (int index=0; index<10; index++)
cout << x[index] << endl;
Example: Read Values and Print
them in Reverse Order
#include <iomanip.h>
void main()
{
int x[5], index;
cout << “Please enter five integer values: “;
for( index=0; index<5; index++) cin >> x[index];
cout << “The values in reverse order are: “;
for (index=4; index>=0; index--)
cout << setw(3) << x[index];
cout << endl;
}
Passing 1D Arrays to Functions
 By default, arrays are passed to functions by
reference even though we do not even write the
reference operator (&) in front of the array name,
why?
 Since arrays store huge number of values, it is much
faster and more economical to pass arrays by
reference instead of wasting the time and memory
copying the values of the arrays into another arrays
 Example
 The following function signature accepts an array x as
a reference parameter and it also accepts the number
of entries in the array (i.e. its size)
void process (int x[], int size);
Passing 1D Arrays to Functions
 Why don’t we use the following signature to pass an
array to a function?
void process (int x[10]);
 Unfortunately, using the above signature means that this
particular function will only process a 1D array with size
=10 (no more no less!)
 Of course we would like to write a function to handle
different array sizes and that is why we use the following
signature instead
void process (int x[ ], int size);
 Visual Studio in particular does not issue any warnings
or syntax error if you use the first signature and pass
different array size, but other compliers do!
Example 2: Passing 1D Array to A
Function
#include <iomanip> void main()
#include <iostream> {
#include <string> int v[7] = {1,2,3,4};
using namespace std; int w[4] = {10,20,30,40};
display ("The values of v array : ",
void display (string prompt, v, 7);
int x[ ], int n) display ("The values of w array : ",
{ w, 4);
cout << prompt ; }
for (int i=0; i<n; i++)
cout << setw(3) << x[i];
cout << endl;
}
Passing 1D Arrays As const
Reference Parameters
 It is a good idea to pass arrays as const
reference parameters if you want to
assure that the functions will never change
the values stored in the arrays, e.g.
void display (const int x[ ] , int size)
{
for (int i=0; i<size; i++)
cout << x[i] << endl;
}
Array Manipulation
I. Searching for Something…
Example: Searching for the
smallest value in an array
int smallest (const int x[ ], int n)
{
/* Assume for a moment that x[0] contains
the smallest value */
int min = x[0];
for (int i=1; i<n; i++) if (min>x[i]) min = x[i];
return min;
}
Example: Searching for The Index
of The Smallest Value in An Array
int min_index (int x[ ], int size, int start=0)
{
int index = start; Notice that:
int min = x[index]; 1. The array is not sorted!
for (int i=index+1; i<size; i++) 2. We use the parameter
if (min>x[i]) start to specify the start
{ searching index. The 0
min = x[i]; is the default value of
index = i; this parameter
} 3. Later on, we will use
return index; this function to sort an
} array
Example: Searching for A Key in
Unsorted Array Using Sequential Search
int seqSearch (int x[ ], int size, int key)
{
for (int i=0; i<size; i++)
if (key == x[i]) return i;
return -1;
This function will return the index of
}
the first value that equals to the
key if exists, otherwise, it returns -1
Example: Searching for A Key in A
Sorted Array Using Binary Search
int bSearch (int x[ ],int n,int key)
{ NB.
int left=0, right=n-1; 1. The array x must be sorted!
do 2. Each loop iteration eliminate
{ half of the current length of
int mid = (left+right)/2; the array which makes this
if (x[mid] == key) return mid; searching technique more
if (x[mid]<key) faster than the sequential
right=mid-1; search
3. We stop searching when
else
left>right and in this case we
left=mid+1; return with -1 to indicate that
} while (left<=right); we could not find the key in
return -1; the array
}
Array Manipulation
II. Compute Something…
Example: Compute The Sum of
Values Stored in An Array

int sum (const int x[ ], int n)


{
int s = 0;
for (int i=0; i<n; i++) s+=x[i];
return s;
}
Example: Compute The Mean
Value of An Array

double mean (const int x[ ], int n)


{
return (double) sum(x,n) / n;
}
Example: Compute The Standard
Deviation of An Array
double stdiv (const int x[ ], int x)
{
double ss = 0.0 , xBar = mean(x,n);
for(int i=1; i<n; i++) ss+=pow(x[i]-xBar,2);
if (n<30)
return sqrt(ss/(n-1));
else
return sqrt(ss/n);
}
Example: Compute The Range of
Numbers

int range (const int x[ ], int n)


{
return max (x, n) – min (x, n);
}
Example: Compute The Median

double median( double x[], int n)


{
sort (x, n); //assume sort( ) is already defined
if (n % 2 == 1)
return x[n/2+1];
else
return (x[n/2]+x[n/2+1)/2;
}
Example: Multiplying An Array with
A Constant Value

void multiply( int x[ ], int n, const int value)


{
for (int i=0; i<n; i++) x[i] *= value;
}
Example: Dot Product of Two
Arrays

int dotProduct( int x[ ], int y[ ], int n)


{
int sum = 0;
for (int i=0; i<n; i++)
sum += x[i] * y[i];
return sum;
}
Example: Adding/Subtracting Two
arrays
void add (const int x[], const int y[], int z[], nt n)
{
for (int i=0; i<n; i++) z[i] = x[i] + y[i];
}

void subtract (const int x[], const int y[], int z[], int n)
{
for (int i=0; i<n; i++) z[i] = x[i] - y[i];
}
Example: Set Intersection
void intersection (const int set1[], int size1,
const int set2[], int size2, int s[], int &size)
{
size=0;
for(int i=0; i<size1; i++)
if (seqSearch(set2, size2, set1[i])>-1)
set[size++] = set1[i];
}
Example: Set Difference
void difference (const int set1[], int size1,
const int set2[], int size2, int s[], int &size)
{
size=0;
for(int i=0; i<size1; i++)
if (seqSearch(set2, size2, set1[i]) == -1)
set[size++] = set1[i];
}
Example: Set Union
void union (const int set1[], int size1,
const int set2[], int size2, int s[], int &size)
{
size = size1;
for(int i=0; i<size; i++) set[i]=set1[i];
for(int i=0; i<size2; i++)
if (seqSearch(set, size, set2[i]) == -1)
set[size++] = set2[i];
}
Example: Converting An Integer
Decimal Number to Binary Number
#include <iomanip.h> {
void main() while (n>0)
{
short int binary[64]={0}; {
int index, bits=0; binary[bits] = n % 2;
unsigned int n; n /= 2;
bits++;
cout << "Please enter an integer value: ";
}
cin >> n;
Guess what happens when you enter -1!
cout << "The binary number is "; for (index=bits-1;index>=0;index--)
if (n==0) cout << binary[index];
cout << 0 << endl; cout << endl;
else
}
}
Example #2: Converting an integer
decimal number to binary number
#include <iomanip.h> {
void main() while (n>0)
{
short int binary[64]={0}; {
int index, bits=0; binary[bits] = n % 2;
unsigned int n; n /= 2;
bits++;
cout << "Please enter an integer value: ";
}
cin >> n;
Guess what happens when you enter -1!
cout << "The binary number is "; for (index=bits-1;index>=0;index--)
if (n==0) cout << binary[index];
cout << 0 << endl; cout << endl;
else
}
}
Example 4: Search for The Largest
Value in 1D Array
#include <iostream.h>

int largest (const int x[ ], int size)


{
// Assume for a moment that the largest
// value is stored in x[0]
int max = x[0];
for (int i=1; i<size; i++) if (max < x[i]) max = x[i];
return max;
}
Example 4 (Cont.)
void main()
{
int array[10] = {4,1,6,3,-5,2,9,5,7,8};
cout << “The largest stored value is “
<< largest (array,10)
<< endl;
}
Exercise #1
Write a function to search for the smallest
value stored in a ID array. Your function
signature should be like this
int smallest (const int x[ ], int size);
// purpose – find the smallest value
// input – an array x and its size
// output – the smallest value
Write a C++ program to test your function
Example 5: Searching for The Index of
the Largest Value in 1D Array
#include <iomanip>
#include <string>
#include <iostream>
using namespace std;

int indexOfMaxValue(const int x[ ], int size)


{
// Assume for a moment that the largest value is stored in x[0]
int max = x[0];
int index = 0;
for (int i=1; i<size; i++)
if (max < x[i])
{
max = x[i];
index = i;
}
return index;
}
Exercise#2
 Write a function to search for the index of the
smallest value stored in 1D array. Your function
signature should be like this

Int indexOfMinValue (const int x [ ], int size);


// purpose – get the index of the smallest value stored in
the array x
// input – the array x and its size
// output – the index of the smallest value

Write a C++ program to test your function


Example 6: Insertion Sort
void insertionSort(int x [], int n)
{
for(int i=0; i<n; i++)
swap(x[indexOfMaxValue(x,n-i)], x[n-i-1]);
}
Get the index of the largest value stored in the range of
[0,n-i] and swap this value in that index with x[n-i-1]
void printArray(string p, int x[ ], int size)
{
cout << p;
for (int i=0; i<size; i++) cout << setw(3) << x[i];
cout << endl;
}
Example 6 (Cont.)
void main()
{
int array[10] = {4,1,3,2,7,6,10,9,5,8};
printArray("Unsorted array:",array, 10);
insertionSort(array, 10);
printArray("Sorted array: ",array, 10);
}
Array Manipulation
II. Compute…
 The sum of the values stored in an array
 The mean and the standard deviation for the array
values
 The range of the values stored in an array
 Multiplying array values by a constant
 Dot-product of two arrays
 The intersection of two arrays (acting as sets)
 The union of two arrays (acting as sets)
 The difference between two arrays acting as sets
 Binary representation for a given integer number
 Generate Fibonacci series
 Generate geometric series
Array Manipulation
III. Rearranging values of an array

 Sorting an array (in ascending or


descending order) using bubble sort

 Remove duplicate values from an array

 Reversing the content of an array

You might also like