C++ PROGRAMMING SKILLS Part 4: Arrays

Similar documents
Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

C Arrays Pearson Education, Inc. All rights reserved.

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Arrays. Week 4. Assylbek Jumagaliyev

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

C: How to Program. Week /Apr/23

Array. Arrays. Declaring Arrays. Using Arrays

Lecture 04 FUNCTIONS AND ARRAYS

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

Arrays. Systems Programming Concepts

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Multiple-Subscripted Arrays

C: How to Program. Week /Apr/16

Chapter 7 Array. Array. C++, How to Program

Programming for Engineers Arrays

BBS 514 YAPISAL PROGRAMLAMA (STRUCTURED PROGRAMMING)

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Introduction to Computer Science Midterm 3 Fall, Points

Computer Programming Lecture 14 Arrays (Part 2)

Two Dimensional Array - An array with a multiple indexs.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

Content. In this chapter, you will learn:

IS 0020 Program Design and Software Tools

Introduction to C Final Review Chapters 1-6 & 13

UNIT- 3 Introduction to C++

Review of Important Topics in CS1600. Functions Arrays C-strings

Pointers and Strings Prentice Hall, Inc. All rights reserved.

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Two Dimensional Array - An array with a multiple indexs.

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Deitel Series Page How To Program Series

Chapter 3 - Functions

BITG 1113: Array (Part 1) LECTURE 8

CSI33 Data Structures

Pointers and Strings. Adhi Harmoko S, M.Komp

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Procedural Programming

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

Chapter 5 - Functions

Chapter 6 - Pointers

Chapter 10 - Notes Applications of Arrays

Computer Science & Engineering 150A Problem Solving Using Computers

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Chapter 6 Arrays and Strings Prentice Hall, Inc. All rights reserved.

Functions. Introduction :

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 6: One Dimensional Array

CSC 211 Intermediate Programming. Arrays & Pointers

C Arrays. O b j e c t i v e s In this chapter, you ll:

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

Outline Arrays Examples of array usage Passing arrays to functions 2D arrays Strings Searching arrays Next Time. C Arrays.

Arrays and Applications

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

C++ Programming Chapter 7 Pointers

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

Objectives of This Chapter

STRUCTURED DATA TYPE ARRAYS IN C++ ONE-DIMENSIONAL ARRAY TWO-DIMENSIONAL ARRAY

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Chapter 7 : Arrays (pp )

For loops, nested loops and scopes. Jordi Cortadella Department of Computer Science

Chapter 15 - C++ As A "Better C"

How to declare an array in C?

C Pointers Pearson Education, Inc. All rights reserved.

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

Arrays. Arizona State University 1

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

Lecture (07) Arrays. By: Dr. Ahmed ElShafee. Dr. Ahmed ElShafee, ACU : Fall 2015, Programming I

Objectives. Chapter 8 Arrays and Strings. Objectives (cont d.) Introduction 12/14/2014. In this chapter, you will:

Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Outline. For loops, nested loops and scopes. Calculate x y. For loops. Scopes. Nested loops. Algorithm: repeated multiplication x x x x

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Pointers, Dynamic Data, and Reference Types

To become familiar with array manipulation, searching, and sorting.

Fundamentals of Programming Session 14

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Principles of Programming. Chapter 6: Arrays

Elements of C in C++ data types if else statement for loops. random numbers rolling a die

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

Lab Instructor : Jean Lai

Split up Syllabus (Session )

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

CSCE 110 PROGRAMMING FUNDAMENTALS. Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays

Chapter 5 - Pointers and Strings

Transcription:

C++ PROGRAMMING SKILLS Part 4: Arrays 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)

Arrays Introduction 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 Name of array (Note that all elements of this array have the same name, c) c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] -45 6 0 72 1543-89 0 62-3 1 6453 78 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 For loop Set each element Initializer list Initializing Arrays 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> Declare a 10-element array of integers. 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 Initialize array to 0 using a for loop. Note that the array has elements n[0] to n[9]. 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 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> Note use of const keyword. Only const variables can specify array sizes. int main() // constant variable can be used to specify array size const int arraysize = 10; int s[ arraysize ]; // array s has 10 elements 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, we d have to update every loop in the program). 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 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 ); Prints asterisks corresponding to size of array element, n[i]. 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

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 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. // 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; } // end main // indicates successful termination 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 ] ; Notice: Multiple assignment // 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

Sorting data Sorting Arrays 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

Example: Bubble Sort 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)

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

// 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 ]; Program Output a[ j + 1 ] = temp; } // end if Data items in original order cout << "\ndata items in ascending order\n"; 2 6 4 8 10 12 89 68 45 37 for ( int k = 0; k < arraysize; k++ ) Data items in ascending order cout << setw( 4 ) << a[ k ]; 2 4 6 8 10 12 37 45 68 89 cout << endl; return 0; // indicates successful termination } // end main

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-byreference. Although named b, the array points to the original array a. It can modify a s 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)

Computing Mean (Average) // 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 Median (Element in the Middle) // This function determines the median element s 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 ; Sort array by passing it to a function. This keeps the program modular. } // end function median

Finding the Mode (The most frequent element) // 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 The mode is the value that occurs most often (has the highest value in freq). } // end for // return the mode value return modevalue; } // end function mode

Bubble Sort Function // 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 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

Linear Search Function // 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

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 ] Column subscript Array name Row subscript

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

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 1 0 3 4 Must specify sizes of subscripts First subscript not necessary, as with single-scripted arrays void printarray( int [][ 3 ] );

// Initializing and printing multidimensional arrays. #include <iostream.h > Note the format of the prototype. 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 } }; Note the various initialization styles. The elements in array2 are assigned to the first row and cout << "Values in array1 by row are:" << endl; then the second. 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

// Function to output array with two rows and three columns void printarray( int a[][ 3 ] ) For-loops are often used to iterate through arrays. Nested for ( int r = 0; r < 2; r++ ) // for each row loops are helpful with multiplesubscripted arrays. 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

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 Above 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-loops are often used to iterate through arrays. Nested for ( int i = 0; i < 3; i++ ) // for each row loops are helpful with multiplesubscripted arrays. 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

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 Quiz1 Quiz2 Student0 Student1 95 85 89 80

// 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 Determines the average for one student. We pass the array/row containing the student s grades. Note that studentgrades[0] is itself an array. // 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

// 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

Strings Examples Using Arrays 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] 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 strings cout << "string1 is: " << string1 << "\nstring2 is: " << string2; cout << "\nstring1 with spaces between characters is:\n";

// 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 Can access the characters in a string using array notation. The loop ends when the null character is found. } // 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