0% found this document useful (0 votes)
112 views53 pages

C++ Programming Skills: Arrays

The document outlines various topics related to arrays in C++ programming including: 1) Declaring and initializing arrays, passing arrays to functions, and using arrays in examples like computing sums and printing histograms. 2) Techniques for sorting arrays like bubble sort and searching arrays using linear search. 3) Declaring multi-dimensional or two-dimensional arrays and arrays of characters (strings). 4) Examples of using arrays to roll dice, find minimum and maximum elements, and initialize arrays with constants.

Uploaded by

Ayesha Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views53 pages

C++ Programming Skills: Arrays

The document outlines various topics related to arrays in C++ programming including: 1) Declaring and initializing arrays, passing arrays to functions, and using arrays in examples like computing sums and printing histograms. 2) Techniques for sorting arrays like bubble sort and searching arrays using linear search. 3) Declaring multi-dimensional or two-dimensional arrays and arrays of characters (strings). 4) Examples of using arrays to roll dice, find minimum and maximum elements, and initialize arrays with constants.

Uploaded by

Ayesha Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 53

Outline

Introduction to Arrays
Declaring and Initializing Arrays
Examples Using Arrays
Sorting Arrays: Bubble Sort
Passing Arrays to Functions
Computing Mean, Median and Mode Using Arrays and Functions
Searching Arrays: Linear Search
Multiple-Subscripted Arrays: Two Dimensional Arrays
Arrays of characters (Strings)
C++ PROGRAMMING SKILLS
Part 4: Arrays
Introduction
Arrays
Structures of related data items
Static entity (same size throughout program)
Array is a consecutive group of memory locations
same name and the same type (int, char, etc.)
To refer to a particular element in an array, we specify the name of
the array and the position of the element
To refer to an element
Specify array name and position number (index)
Format: arrayname[ position number ]
First element at position 0

Arrays
N-element array c
c[ 0 ], c[ 1 ] c[ n - 1 ]
Nth element at position N-1
Array elements like other variables
Assignment, printing for an integer array c
c[ 0 ] = 3;
cout << c[ 0 ];
Can perform operations inside subscript
c[ 5 2 ] same as c[3]

Arrays
c[6]

-45

6

0

72

1543

-89

0

62

-3

1

6453

78

Name of array (Note that
all elements of this
array have the same name,
c)

c[0]

c[1]

c[2]

c[3]

c[11]

c[10]

c[9]

c[8]

c[7]

c[5]

c[4]

Position number of the
element within array c



Declaring Arrays
When declaring arrays, specify
Name
Type of array
Any data type
Number of elements
type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats
Declaring multiple arrays of same type
Use comma separated list, like regular variables
int b[ 100 ], x[ 27 ];
Initializing Arrays
Initializing arrays
For loop
Set each element
Initializer list
Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
If not enough initializers, rightmost elements 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
// Initializing an array.
#include <iostream.h>
#include <iomanip.h>

int main()
{
int n[ 10 ]; // n is an array of 10 integers

// initialize elements of array n to 0
for ( int i = 0; i < 10; i++ )
n[ i ] = 0; // set element at location i to 0

cout << "Element" << setw( 13 ) << "Value" << endl;

// output contents of array n in tabular format
for ( int j = 0; j < 10; j++ )
cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
return 0; // indicates successful termination

} // end main
Declare a 10-element array of
integers.
Initialize array to 0 using a for
loop. Note that the array has
elements n[0] to n[9].
Program Output
Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
// Initializing an array with a declaration.

#include <iostream.h>

#include <iomanip.h>


int main()
{
// use initializer list to initialize array n
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };

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;

return 0; // indicates successful termination

} // end main

Note the use of the initializer
list.
Program Output

Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
Examples Using Arrays
Array size
Can be specified with constant variable (const)
const int size = 20;
Constants cannot be changed
Constants must be initialized when declared
Also called named constants or read-only variables

// Initialize array s to the even integers from 2 to 20.

#include <iostream.h>
#include <iomanip.h>

int main()
{
// constant variable can be used to specify array size
const int arraySize = 10;

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
Note use of const keyword.
Only const variables can
specify array sizes.
The program becomes more scalable
when we set the array size using a
const variable. We can change
arraySize, and all the loops will still
work (otherwise, wed have to update
every loop in the program).
Program Output
Element Value
0 2
1 4
2 6
3 8
4 10
5 12
6 14
7 16
8 18
9 20

// Compute the sum of the elements of the array.

#include <iostream.h>

int main()
{
const int arraySize = 10;

int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int total = 0;

// sum contents of array a
for ( int i = 0; i < arraySize; i++ )
total += a[ i ];

cout << "Total of array element values is " << total << endl;

return 0; // indicates successful termination

} // end main

Total of array element values is 55

// Histogram printing program.
#include <iostream.h>
#include <iomanip.h>
int main()
{
const int arraySize = 10;
int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };

cout << "Element" << setw( 13 ) << "Value"
<< setw( 17 ) << "Histogram" << endl;

// for each element of array n, output a bar in histogram
for ( int i = 0; i < arraySize; i++ ) {
cout << setw( 7 ) << i << setw( 13 )
<< n[ i ] << setw( 9 );

for ( int j = 0; j < n[ i ]; j++ ) // print one bar
cout << '*';
cout << endl; // start next line of output

} // end outer for structure

return 0; // indicates successful termination

} // end main

Prints asterisks corresponding to
size of array element, n[i].
Element Value Histogram
0 19 *******************
1 3 ***
2 15 ***************
3 7 *******
4 11 ***********
5 9 *********
6 13 *************
7 5 *****
8 17 *****************
9 1 *

// Roll a six-sided die 6000 times.
#include <iostream.h>
#include <iomanip.h>
#include <stdlib.h>
#include <time.h>
int main()
{
const int arraySize = 7;
int frequency[ arraySize ] = { 0 };
srand( time( 0 ) ); // seed random-number generator

// roll die 6000 times
for ( int roll = 1; roll <= 6000; roll++ )
++frequency[ 1 + rand() % 6 ]; // replaces 20-line switch

cout << "Face" << setw( 13 ) << "Frequency" << endl;

// output frequency elements 1-6 in tabular format
for ( int face = 1; face < arraySize; face++ )
cout << setw( 4 ) << face
<< setw( 13 ) << frequency[ face ] << endl;

return 0; // indicates successful termination

} // end main
An array is used instead of 6 regular
variables, and the proper element can be
updated easily (without needing a
switch).

This creates a number between 1 and 6,
which determines the index of
frequency[] that should be
incremented.
Program Output

Face Frequency
1 1003
2 1004
3 999
4 980
5 1013
6 1001

// Finding the maximum and the minimum elements.
#include <iostream.h>
int main()
{
const int arraySize = 10;
int a[ arraySize ] = { 13, 2, -10, 13, 50, -6, 70, 8, 90, 10 };
int max, min;
max = min = a [ 0 ] ;
// search the contents of array a
for ( int i = 1; i < arraySize; i++ )
if ( a[ i ] > max )
max = a [ i ];
else if ( a [ i ] < min )
min = a [ i ];

cout << The minimum element value is " << min << endl;
cout << The maximum element value is " << max << endl;
return 0; // indicates successful termination
} // end main
The minimum element value is -10
The maximum element value is 90
Notice: Multiple assignment
Sorting Arrays
Sorting data
Important computing application
Virtually every organization must sort some data
Massive amounts must be sorted
Bubble sort (sinking sort)
Several passes through the array
Successive pairs of elements are compared
If increasing order (or identical), no change
If decreasing order, elements exchanged
Repeat these steps for every element

Bubble Sort
Example:
Go left to right, and exchange elements as necessary
One pass for each element
Original: 7 3 2 4 6
Pass 1: 3 2 4 6 7 (elements exchanged)
Pass 2: 2 3 4 6 7
Pass 3: 2 3 4 6 7 (no changes needed)
Pass 4: 2 3 4 6 7
Pass 5: 2 3 4 6 7
Small elements "bubble" to the top (like 2 in this example)

Bubble Sort
Swapping variables
int x = 3, y = 4;
y = x;
x = y;
What happened?
Both x and y are 3!
Need a temporary variable
Solution
int x = 3, y = 4, temp = 0;
temp = x; // temp gets 3
x = y; // x gets 4
y = temp; // y gets 3
// Bubble sort an array's values into ascending order.
#include <iostream.h>
#include <iomanip.h>
int main()
{
const int arraySize = 10; // size of array a
int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int temp; // temporary location used to swap array elements
cout << "Data items in original order\n";
for ( int i = 0; i < arraySize; i++ )
cout << setw( 4 ) << a[ i ];
// bubble sort. loop to control number of passes
for ( int pass = 0; pass < arraySize - 1; pass++ )
for ( int j = 0; j < arraySize - 1; j++ )
if ( a[ j ] > a[ j + 1 ] ) {
temp = a[ j ];
a[ j ] = a[ j + 1 ];
a[ j + 1 ] = temp;
} // end if

cout << "\nData items in ascending order\n";
for ( int k = 0; k < arraySize; k++ )
cout << setw( 4 ) << a[ k ];
cout << endl;
return 0; // indicates successful termination
} // end main
Program Output

Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10 12 37 45 68 89

Passing Arrays to Functions
Specify name without brackets
To pass array myArray to myFunction
int myArray[ 24 ];
myFunction( myArray, 24 );
Array size usually passed, but not required
Useful to iterate over all elements
Passing Arrays to Functions
Arrays passed-by-reference
Functions can modify original array data
Value of name of array is address of first element
Function knows where the array is stored
Can change original memory locations
Individual array elements passed-by-value
Like regular variables
square( myArray[3] );
Passing Arrays to Functions
Functions taking arrays
Function prototype
void modifyArray( int b[], int arraySize );
void modifyArray( int [], int );
Names optional in prototype
Both take an integer array and a single integer
No need for array size between brackets
Ignored by compiler
If declare array parameter as const
Array elements cannot be modified (compiler error)
void doNotModify( const int [] );
// Passing arrays to function and modify the elements.
#include <iostream.h>
#include <iomanip.h>
void modifyArray( int [ ], int ); // appears strange
int main()
{
const int arraySize = 5; // size of array a
int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize a
cout << Effects of passing entire array by reference:\n\n;
cout << "\nThe values of the original array are:\n";
for ( int i = 0; i < arraySize; i++ )
cout << setw( 3 ) << a[ i ];
cout << endl;
modifyArray( a, arraySize ); // pass array a to modifyArray by reference
cout << "The values of the modified array are:\n";
for ( int j = 0; j < arraySize; j++ )
cout << setw( 3 ) << a[ j ];
return 0; // indicates successful termination
} // end main

void modifyArray( int b[ ], int sizeOfArray )
{
// multiply each array element by 2
for ( int k = 0; k < sizeOfArray; k++ )
b[ k ] *= 2;
} // end function modifyArray
Pass array name (a) and size to
function. Arrays are passed-by-
reference.
Although named b, the array
points to the original array a. It
can modify as data.
Effects of passing entire array by reference:

The values of the original array are:
0 1 2 3 4
The values of the modified array are:
0 2 4 6 8


// using function to input and to print arrays.
#include <iostream.h>
#include <iomanip.h>
void inputArray( int [ ], int );
void printArray( const int [ ], int );
int main()
{
const int arraySize = 5; // size of array a
int a[ arraySize ]; // declare array a un-initialized

inputArray( a, arraySize ); // pass array a to inputArray by reference
printArray( a, arraySize ); // pass array a to printArray by reference
return 0; // indicates successful termination
} // end main

void inputArray( int b[ ], int n )
{
cout << Please enter << n << integer elements\n;
for ( int k = 0; k < n; k++ )
cin >> b[ k ];
cout << endl;
} // end function inputArray
void printArray( const int b[ ], int n )
{
cout << Array elements printed using function:\n;
for ( int k = 0; k < n; k++ )
cout << setw( 3 ) << a[ k ];
cout << endl;
} // end function printArray
Please enter 5 integer elements
5 10 3 7 14

Array elements printed using function:
5 10 3 7 14


Computing Mean, Median and Mode of Arrays
Using Functions
Mean
Average (sum/number of elements)
Median
Number in middle of sorted list
1, 2, 3, 4, 5 (3 is median)
If even number of elements, take average of middle two
Mode
Number that occurs most often
1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)

// This function computes and returns the average of array elements

double mean( const int x[], int arraySize )
{
int sum = 0;

// sum the array values
for ( int i = 0; i < arraySize; i++ )
sum += x[ i ];
return static_cast< double >( sum ) / arraySize;
} // end function mean


We cast to a double to get
decimal points for the average
(instead of an integer).
Computing Mean (Average)
// This function determines the median elements value

double median( int x[], int size )
{
// sort array and determine median element's value
bubbleSort( x, size ); // sort array

// If the size is odd the median is x [size / 2 ]
// If the size is even the median is the average
// of the two middle elements x[(size - 1)/2] and x[size/2]
if (size % 2 != 0) // odd size
return x [ size / 2];
else
return ( x [ (size 1) / 2] + x [ size / 2] ) / 2.0 ;

} // end function median


Computing Median
(Element in the Middle)
Sort array by passing it to a
function. This keeps the program
modular.
// This function returns the most frequent element in an array
// The elements values range between 1 and 9
int mode(int x[], int size )
{
int largestFreq = 0; // represents largest frequency
int modeValue = 0; // represents most frequent element
int freq[ 10 ] = { 0 }; // declare and initialize frequencies to 0
// summarize frequencies
for ( int j = 0; j < size; j++ )
++freq[ x[ j ] ];
for ( int i = 1; i <= 9; i++ ) {
// keep track of mode value and largest frequency value
if ( freq[ i ] > largestFreq ) {
largestFreq = freq[ i ];
modeValue = i;
} // end if

} // end for
// return the mode value
return modeValue;
} // end function mode
Finding the Mode
(The most frequent element)
The mode is the value that
occurs most often (has the
highest value in freq).
// This function sorts an array with bubble sort algorithm

void bubbleSort( int a[], int size )
{
int temp; // temporary variable used to swap elements

// loop to control number of passes
for ( int pass = 1; pass < size; pass++ )

// loop to control number of comparisons per pass
for ( int j = 0; j < size 1 ; j++ )

// swap elements if out of order
if ( a[ j ] > a[ j + 1 ] ) {
temp = a[ j ];
a[ j ] = a[ j + 1 ];
a[ j + 1 ] = temp;

} // end if

} // end function bubbleSort
Bubble Sort Function
To reduce the number of comparisons,
the for-loop continuation-condition can
be written as:
j < size pass
e.g., if size=5:
Pass 1 4 comparisons
Pass 2 3 comparisons
Pass 3 2 comparisons
Pass 4 1 comparison
Searching Arrays: Linear Search
Search array for a key value
Linear search
Compare each element of array with key value
Start at one end, go to other
Useful for small and unsorted arrays
Inefficient, if search key not present, examines every element

// The function compares key to every element of array until location
// is found or until end of array is reached; return subscript of
// element key or -1 if key not found

int linearSearch( const int array[], int key, int sizeOfArray )
{
for ( int j = 0; j < sizeOfArray; j++ )

if ( array[ j ] == key ) // if found,
return j; // return location of key

return -1; // key not found

} // end function linearSearch
Linear Search Function
Multiple-Subscripted Arrays
Multiple subscripts
a[ i ][ j ]
Tables with rows and columns
Specify row, then column
Array of arrays
a[0] is an array of 4 elements
a[0][0] is the first element of that array

Row 0

Row 1

Row 2

Column 0

Column 1

Column 2

Column 3

a[ 0 ][ 0 ]

a[ 1 ][ 0 ]

a[ 2 ][ 0 ]

a[ 0 ][ 1 ]

a[ 1 ][ 1 ]

a[ 2 ][ 1 ]

a[ 0 ][ 2 ]

a[ 1 ][ 2 ]

a[ 2 ][ 2 ]

a[ 0 ][ 3 ]

a[ 1 ][ 3 ]

a[ 2 ][ 3 ]

Row subscript

Array name

Column subscript

Two-dimensional Array: Initialization
To initialize
Default of 0
Initializers grouped by row in braces
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };



int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

1 2
3 4
1 0
3 4
Row 0 Row 1
Two-dimensional Array: Referencing
Referenced like normal
cout << b[ 0 ][ 1 ];
Outputs 0
Cannot reference using commas
cout << b[ 0, 1 ];
Syntax error
Function prototypes
Must specify sizes of subscripts
First subscript not necessary, as with single-scripted arrays
void printArray( int [][ 3 ] );
1 0
3 4
// Initializing and printing multidimensional arrays.
#include <iostream.h >

void printArray( int [][ 3 ] );

int main()
{
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };

cout << "Values in array1 by row are:" << endl;
printArray( array1 );

cout << "Values in array2 by row are:" << endl;
printArray( array2 );

cout << "Values in array3 by row are:" << endl;
printArray( array3 );

return 0; // indicates successful termination
} // end main
Note the various initialization
styles. The elements in array2
are assigned to the first row and
then the second.
Note the format of the prototype.
// Function to output array with two rows and three columns
void printArray( int a[][ 3 ] )
{
for ( int r = 0; r < 2; r++ ) { // for each row

for ( int c = 0; c < 3; c++ ) // output column values
cout << a[ r ][ c ] << ' ';

cout << endl; // start new line of output

} // end outer for structure

} // end function printArray
Values in array1 by row are:
1 2 3
4 5 6
Values in array2 by row are:
1 2 3
4 5 0
Values in array3 by row are:
1 2 0
4 0 0

For-loops are often used to
iterate through arrays. Nested
loops are helpful with multiple-
subscripted arrays.
Two-dimensional Array: Example
Program showing
initialization
Compute the sum of array elements on the first diagonal
Compute the sum of array elements on the second diagonal
Compute the sum of array elements above the first diagonal
Compute the sum of array elements bellow the first diagonal



First diagonal Second diagonal
#include <iostream.h >
void printArray( int [][ 3 ] );
int main()
{
int array[ 3 ][ 3 ] = { { 1, 2, 3 },
{ 4, 5, 6 } ,
{ 7, 8, 9 } };
cout << "Values in the array are:" << endl;
printArray( array );
// sum the values on the first diagonal
int sumDiag1 = 0;
for ( int i = 0; i < 3; i++ )
sumDiag1 += array[ i ][ i ] ;
cout << Sum of Values on first diagonal:" << sumDiag1 << endl;
cout << endl;
// sum the values on the second diagonal
int sumDiag2 = 0;
for ( int i = 0; i < 3; i++ )
sumDiag2 += array[ i ][ 3 i - 1 ] ;
cout << Sum of Values on second diagonal:" << sumDiag2 << endl;
cout << endl;

// sum the values above the first diagonal
int sumAbove = 0;
for ( int i = 0; i < 3; i++ )
for ( int j = 0; j < 3; j++ )
if ( i < j )
sumAbove += array[ i ][ i ] ;
cout << Sum of Values above diagonal:" << sumAbove << endl;
cout << endl;

// sum the values bellow the first diagonal
int sumBellow = 0;
for ( int i = 0; i < 3; i++ )
for ( int j = 0; j < 3; j++ )
if ( i > j )
sumBellow += array[ i ][ i ] ;
cout << Sum of Values bellow diagonal:" << sumBellow << endl;
cout << endl;

return 0; // indicates successful termination
} // end main
// function to output array with three rows and three columns
void printArray( int a[][ 3 ] )
{
for ( int i = 0; i < 3; i++ ) { // for each row

for ( int j = 0; j < 3; j++ ) // output column values
cout << a[ i ][ j ] << ' ';

cout << endl; // start new line of output

} // end outer for structure

} // end function printArray
For-loops are often used to
iterate through arrays. Nested
loops are helpful with multiple-
subscripted arrays.
Values in the array are:
1 2 3
4 5 6
7 8 9

Sum of Values on first diagonal:15

Sum of Values on second diagonal:15

Sum of Values above diagonal:10

Sum of Values bellow diagonal:19
Two-dimensional Array: Example
Tracking Students Grades
Program showing initialization
Keep track of students grades
Uses two-dimensional array (table)
Rows are students
Columns are grades



95 85
89 80
Quiz1 Quiz2
Student0
Student1
// Tracking Students grades example.
#include <iostream.h>
#include <iomanip>

const int students = 3; // number of students
const int exams = 4; // number of exams

// function prototypes
int minimum( int [][ exams ], int, int );
int maximum( int [][ exams ], int, int );
double average( int [], int );
void printArray( int [][ exams ], int, int );
int main()
{
// initialize student grades for three students (rows)
int studentGrades[ students ][ exams ] = { { 77, 68, 86, 73 },
{ 96, 87, 89, 78 },
{ 70, 90, 86, 81 } };
// output array studentGrades
cout << "The array is:\n";
printArray( studentGrades, students, exams );

// determine smallest and largest grade values
cout << "\n\nLowest grade: " << minimum( studentGrades, students, exams )
<< "\nHighest grade: " << maximum( studentGrades, students, exams ) << '\n';
// calculate average grade for each student
for ( int person = 0; person < students; person++ )
cout << "The average grade for student " << person
<< " is "
<< average( studentGrades[ person ], exams )
<< endl;

return 0; // indicates successful termination

} // end main

// The following function finds minimum grade
int minimum( int grades[][ exams ], int pupils, int tests )
{
int lowGrade = 100; // initialize to highest possible grade

for ( int i = 0; i < pupils; i++ )

for ( int j = 0; j < tests; j++ )

if ( grades[ i ][ j ] < lowGrade )
lowGrade = grades[ i ][ j ];

return lowGrade;
} // end function minimum

Determines the average for one
student. We pass the array/row
containing the students grades.
Note that studentGrades[0] is
itself an array.

// The following function finds maximum grade of all grades

int maximum( int grades[][ exams ], int pupils, int tests )
{
int highGrade = 0; // initialize to lowest possible grade

for ( int i = 0; i < pupils; i++ )

for ( int j = 0; j < tests; j++ )

if ( grades[ i ][ j ] > highGrade )
highGrade = grades[ i ][ j ];

return highGrade;

} // end function maximum



// The following function determines average grade for particular student

double average( int setOfGrades[], int tests )
{
int sum = 0;

// total all grades for one student
for ( int i = 0; i < tests; i++ )
sum += setOfGrades[ i ];

return static_cast< double >( sum ) / tests; // average

} // end function maximum

// The following function prints the two-dimensional array of students grades

void printArray( int grades[][ exams ], int pupils, int tests )
{
// set left justification and output column heads
cout << left << " [0] [1] [2] [3]";

// output grades in tabular format
for ( int i = 0; i < pupils; i++ ) {

// output label for row
cout << "\nstudentGrades[" << i << "] ";

// output one grades for one student
for ( int j = 0; j < tests; j++ )
cout << setw( 5 ) << grades[ i ][ j ];

} // end outer for

} // end function printArray

The array is:
[0] [1] [2] [3]
studentGrades[0] 77 68 86 73
studentGrades[1] 96 87 89 78
studentGrades[2] 70 90 86 81

Lowest grade: 68
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75

Examples Using Arrays
Strings
Arrays of characters
All strings end with null character denoted by ('\0')
Examples
char string1[] = "hello";
Null character implicitly added
string1 has 6 elements
char string1[] = { 'h', 'e', 'l', 'l', 'o', '\0 };
Subscripting is the same
String1[ 0 ] is 'h'
string1[ 2 ] is 'l'
Examples Using Arrays
Input from keyboard
char string2[ 10 ];
cin >> string2;
Puts user input in string
Stops at first whitespace character
Adds null character
If too much text entered, data written beyond array
We want to avoid this (section 5.12 explains how)
Printing strings
cout << string2 << endl;
Does not work for other array types
Characters printed until null found


// Treating character arrays as strings.
#include <iostream.h>

int main()
{
char string1[ 20 ], // reserves 20 characters
char string2[] = "string literal"; // reserves 15 characters

// read string from user into array string2
cout << "Enter the string \"hello there\": ";
cin >> string1; // reads "hello" [space terminates input]

// output strings
cout << "string1 is: " << string1
<< "\nstring2 is: " << string2;

cout << "\nstring1 with spaces between characters is:\n";


Two different ways to declare
strings. string2 is initialized,
and its size determined
automatically .
Examples of reading strings
from the keyboard and printing
them out.
// output characters until null character is reached
for ( int i = 0; string1[ i ] != '\0'; i++ )
cout << string1[ i ] << ' ';

cin >> string1; // reads "there"
cout << "\nstring1 is: " << string1 << endl;

return 0; // indicates successful termination

} // end main

Enter the string "hello there": hello there
string1 is: hello
string2 is: string literal
string1 with spaces between characters is:
h e l l o
string1 is: there

Can access the characters in a
string using array notation. The
loop ends when the null
character is found.

You might also like