Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection of stdin and stdout TNCG18 (C++): Lec 3 1 Arrays Name of array int c[12]; Consecutive group of memory locations of the same type. To refer to an element (e.g. 3 rd ) c[2] First element at position 0 ith element at position i-1 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 TNCG18 (C++): Lec 3 2 Lec 3 Programming in C++ 1
Arrays Array elements like other variables Assignment and printing for an integer array c c[ 0 ] = 3; cout << c[ 0 ] << endl; Can perform operations inside subscript c[ 5 2 ] same as c[3] TNCG18 (C++): Lec 3 3 Declaring Arrays When declaring arrays, specify type arrayname[ arraysize ]; int c[10]; // array of 10 integers float d[3284]; // array of 3284 floats The array size can be defined as a constant const int arraysize = 10; int c[ arraysize ]; See Fig04_06.cpp Declaring multiple arrays of same type Use comma separated list, like regular variables int b[ 100 ], x[ 27 ]; TNCG18 (C++): Lec 3 4 Lec 3 Programming in C++ 2
Initializing Arrays With a loop See Fig04_03.cpp, Fig04_05.cpp Initializer list See Fig04_04.cpp Specify each element when array declared int n[ 5 ] = { 1, 2, 3, 4, 5 }; int v[ 100 ] = {0}; If too many initializers then syntax error If array size omitted, initializers determine size int n[] = { 1, 2, 3, 4, 5 }; 5 initializers, therefore 5 element array TNCG18 (C++): Lec 3 5 Defining Array Size Can be specified with constant variable const int size = 20; char v[size]; Constants cannot be changed Constants must be initialized when declared Also called read-only variables See Fig04_08.cpp Fig04_07.cpp TNCG18 (C++): Lec 3 6 Lec 3 Programming in C++ 3
Examples Histogram SeeFig04_10.cpp Throwing a dice and counting frequencies SeeFig04_11.cpp Listing student grades frequencies See Fig04_09.cpp Compute mean, median, and mode See Fig04_17.cpp TNCG18 (C++): Lec 3 7 Arrays in C++ No range checking The array does not know its size Cannot input or output an array directly, except strings Comparison and assignment not implemented TNCG18 (C++): Lec 3 8 Lec 3 Programming in C++ 4
C strings Character Arrays Arrays of characters All C strings end with null ('\0') char string1[] = { 'h', 'e', 'l', 'l', 'o', '\0 }; char string1[] = "hello"; Null character implicitly added string1 has 6 elements Subscripting string1[0] is 'h string1[2] is 'l' TNCG18 (C++): Lec 3 9 Character Arrays Input from keyboard See Fig04_12.cpp char string2[ 10 ]; cin >> string2; Reads user input in string2 Stops at first white space character Adds null character If too much text entered, data written beyond array #include <iomanip> char string3[ 5 ]; cin >> setw(5) >> string3; Reads at most 4 chars and last array position is for the null TNCG18 (C++): Lec 3 10 Lec 3 Programming in C++ 5
Printing strings Character Arrays cout << string2 << endl; Does not work for other array types Characters printed until null character found TNCG18 (C++): Lec 3 11 Passing Arrays to Functions Function prototype void modifyarray( int b[], int arraysize ); void modifyarray( int [], int); No need for array size between brackets Ignored by compiler Array parameter as const Array values cannot be modified (compiler error) void donotmodify( const int [] ); See Fig04_15.cpp TNCG18 (C++): Lec 3 12 Lec 3 Programming in C++ 6
Calling Functions with Array Arguments Call function modifyarray To pass array myarray to modifyarray int myarray[24]; modifyarray(myarray, 24); Array size is usually an argument Not required Useful to iterate over all elements TNCG18 (C++): Lec 3 13 Passing Arrays to Functions Arrays passed-by-reference Functions can modify original array data The array s name 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]); See Fig04_14.cpp TNCG18 (C++): Lec 3 14 Lec 3 Programming in C++ 7
Default Arguments Function prototype void modifyarray( int b[], int arraysize = 100); Function call int v[100]; modifyarray(v); //modifyarray(v, 100); Default value modifyarray(myarray, 24); TNCG18 (C++): Lec 3 15 Static Local Arrays If static, local variables are saved between function calls Visible only in function body Used for performance reasons Can declare local arrays to be static Initialized to zero by default static int array[3]; If not static See Fig04_13.cpp Created (and destroyed) in every function call TNCG18 (C++): Lec 3 16 Lec 3 Programming in C++ 8
Multiple-Subscripted Arrays Multiple subscripts a[ i ][ j ] int a[ 3 ][ 4 ]; 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[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Column subscript Array name Row subscript TNCG18 (C++): Lec 3 17 Multiple-Subscripted Arrays To initialize 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 TNCG18 (C++): Lec 3 18 Lec 3 Programming in C++ 9
Multiple-Subscripted Arrays Access to an element 1 0 cout << b[0][1]; 3 4 Outputs 0 Cannot access an element using commas cout << b[0, 1]; Syntax error!!! See Fig04_22.cpp See Fig04_23.cpp Function prototypes Must specify sizes of subscripts First subscript not necessary, as with singlescripted arrays void printarray( int [][2], int size ); TNCG18 (C++): Lec 3 19 StructureType in C++ struct is used to contain data of different types struct Card { int value; char suit [10]; //field, member }; Card ace = {13, Hearts }; // initialization Size (i.e. number of bytes)? sizeof(ace). TNCG18 (C++): Lec 3 20 Lec 3 Programming in C++ 10
Structure Type How do you write in C? typedef struct { int value; // char suit [10]; } Card; Card ace = {13, Hearts }; TNCG18 (C++): Lec 3 21 Operations on structs Memberwise assignment ace.value = 1; Assignment is allowed Card ace2 = ace; Yes, array fields get copied without need to copy each field at a time!!! But surprise!!!, //doesn t compile ace2.suit = ace.suit; #include<cstring> //instead use a string copy function strcpy(ace2.suit, ace2.suit); TNCG18 (C++): Lec 3 22 Lec 3 Programming in C++ 11
Operations on structs Comparison, input, and output are not available if (ace2 == ace)... //does not work cin >> ace2; //does not work Implement your own functions Overload operators ==, >> and << See Fig06_01.cpp TNCG18 (C++): Lec 3 23 Using Structures as Function Arguments Pass the structure argument by value void printcard(card c){ cout << Value: << c.value << Suit: << c.suit << endl; } Pass an array by value to a function Create a structure with the array as a member See struct1.cpp TNCG18 (C++): Lec 3 24 Lec 3 Programming in C++ 12
Using Structures as Function Arguments Pass the structure argument by reference void printcard(const Card &c){ cout << Value: << c.value << Suit: << c.suit << endl; } Pass-by-reference more efficient TNCG18 (C++): Lec 3 25 Inline Functions inline double cube(const double side) { return side * side * side; } int main() { double val; cin >> val; cout << Cube volume: << cube(val) << endl; } return 0; TNCG18 (C++): Lec 3 26 Lec 3 Programming in C++ 13
Inline Functions Function call replaced by functions code Only used for small functions Compiler is free to ignore the inline qualifier Advantage Efficiency: avoid function call overhead Disadvantages Changes in a inline function require that whole project to be recompiled Program size increases TNCG18 (C++): Lec 3 27 Reading a Sequence of Values cin >> k returns 0 when EOF is found or a value of the wrong type is given int main(){ int k, sum = 0; while (cin >> k) sum += k; cout << sum << endl; return 0; } See sum.cpp TNCG18 (C++): Lec 3 28 Lec 3 Programming in C++ 14
Reading Variables int k; cin >> k; cout << k; Prints any trash in k, if user gives a non-integer value. int k; if (cin >> k) cout << k; No problem!!! TNCG18 (C++): Lec 3 29 Redirection of input and output Redirection of input (DOS and Unix) sum < input.txt reads sequence of ints from file input.txt Redirection of output sum > output.txt writes the result to file output.txt Piping (DOS and Unix) dice sum output of dice.exe is redirected as input to sum.exe TNCG18 (C++): Lec 3 30 Lec 3 Programming in C++ 15