Chapter 6 Pointers and Arrays
|
|
- Emma Baldwin
- 5 years ago
- Views:
Transcription
1 Chapter 6 Pointers and Arrays This chapter addresses the following two issues: 1. How to access a variable (memory location) using its address. 2. How to process a collection of data as a list or a table. If you want to use the address of a variable (memory location) to access it, you must first define a variable called pointer variable to hold that address. A list of data is processed in the C++ language by using a one-dimensional array, and a table of data is processed by using a two-dimensional array. Pointer variables, one-dimensional arrays and two-dimensional arrays are discussed in the following sections. 6.1 Pointer Variables and the Address Of Operator A pointer variable is a variable that you define to hold the address of another variable (memory location). You define a pointer variable as follows: Note: Where: <data-type> * <pointer-variable> ; <pointer-variable> <data-type> is an identifier, and is the data type of the variables whose addresses may be held in the pointer variable. C++ distinguishes a pointer variable to hold the address of an integer variable from a pointer variable to hold the address of a character or a floating point variable. Example 6.1 Declaration of Pointer Variables char * cpt; /* cpt is a pointer variable to hold the address of a character (char) variable */ int * ipt; /* ipt is a pointer variable to hold the address of an integer (int) variable */ double * dpt; /* dpt is a pointer variable to hold the address of a double precision floating point (double) variable */ 2017 Gilbert Ndjatou Page 231
2 You may also define pointer variables with other variables in the same declaration statement as follows: int num = 10, * ipt1, result; int *ipt1, num = 10, *ipt2, result; You access the address of a variable by using the address of operator &. For example, if num is a variable, you obtain its address by using the expression: &num. You store the address of a variable into a pointer variable by using the assignment operator as in the following example. Example 6.2 Storing an Address into a Pointer Variable Given the following definitions of variables with their memory representations: Address Memory Locations Address int *iptr; 103 iptr 135 ivar int ivar = 10, *iptrl; double dvar = 7.5, *dptr; 206 iptr1 231 dvar char cvar = Z, *cptr; 275 dptr 283 cvar Z 298 cptr The following assignment statements are valid and have the specified effects on the memory locations: Address Memory Locations Address iptr = &ivar; 103 iptr 135 A 135 ivar dptr = &dvar; cptr = &cvar; 206 iptr1 135 A 231 dvar iptr1 = iptr; 275 dptr 231 A 283 cvar Z 298 cptr 283 A A pointer variable that holds the address of another variable is used to access that variable (memory location) by using the indirection or deference operator (*). For example if pointer variable pt holds the address of a variable (memory location), the expression: *pt says to go to the memory location with address in pointer variable pt Gilbert Ndjatou Page 232
3 Note: You can use the address in a pointer variable to do the following two things: to access the current value of the variable at that address, and to store a value into the variable at that address. Example 6.3 Using a pointer variable to access the current value of a variable Given the following definitions of variables and the assignment statements, Address Memory Locations Address iptr = &ivar; 103 iptr 135 A 135 ivar dptr = &dvar; cptr = &cvar; 206 iptr1 135 A 231 dvar iptr1 = iptr; 275 dptr 231 A 283 cvar Z 298 cptr 283 A Each of the following statements will produce the specified output: Statements Output a) cout << endl << *iptr + 5 = \t << (*iptr + 5); *iptr + 5 = 15 b) cout << endl << *cptr = \t << *cptr; *cptr = Z c) cout << endl << *dptr * 3 = \t << (*dptr * 3); *dptr * 3 = 22.5 The expression (*iptr + 5) is read: get the value in the variable at the address in pointer variable iptr, and add 5 to it. The expression *cptr is read: get the value in the variable at the address in pointer variable cptr. The expression (*dptr * 3) is read: get the value in the variable at the address in pointer variable dptr and multiply it by Gilbert Ndjatou Page 233
4 Example 6.4 Using a pointer variable to store a value into a variable Given the following definitions of variables and the assignment statements, Address Memory Locations Address iptr = &ivar; 103 iptr 135 A 135 ivar dptr = &dvar; cptr = &cvar; 206 iptr1 135 A 231 dvar iptr1 = iptr; 275 dptr 231 A 283 cvar Z 298 cptr 283 A The following program segment will produce the specified output: * cptr = X ; * dptr = dvar + 3; * iptr = * iptr + 8; cout << \ncvar =\t << cvar << \nivar =\t << ivar; cout << endl << dvar =\t << dvar; Output cvar = X ivar = 18 dvar = 10.5 The assignment statement * cptr = X ; says to store character X into the variable at the address in pointer variable cptr; the assignment statement * dptr = dvar + 3; says to add the current value of variable dvar to 3 and to store the result into the variable at the address in pointer variable dptr; The assignment statement * iptr = * iptr + 8; says to get the current value in the variable at the address in pointer variable iptr, add 8 to it, and to store the result into the same variable Gilbert Ndjatou Page 234
5 Exercise 6.1 * Show the output of each of the following code segments: a. int num1 = 7, *numptr1, *numptr2, num2 = 10; numptr1 = &num1; numptr2 = &num2; cout << "\n num1 = << num1 << \n*numptr1 = " << *numptr1; cout << "\n num2 = << num2 << \n*numptr2 = " << *numptr2; cout << \n*numptr1 + 8=\t << (*numptr1 + 8); b. int num1 = 7, *numptr1, *numptr2, num2 = 10; numptr1 = &num1; numptr2 = &num2; num1 += 5; *numptr2 += 15; cout << "\n num1 = << num1 << \n*numptr1 = " << *numptr1; cout << "\n num2 = << num2 << \n*numptr2 = " << *numptr2; c. int num1 = 7, *numptr1, *numptr2, num2 = 10, num3; numptr1 = &num1; numptr2 = &num2; num3 = *numptr1 + 2; *numptr2 = *numptr1; cout << "\n num1 = << num1 << \n*numptr1 = " << *numptr1; cout << "\n num2 = << num2 << \n*numptr2 = " << *numptr2; cout << "\n num3 = << num3; d. int num1 = 7, *numptr1, *numptr2, num2 = 10; numptr1 = &num1; numptr2 = &num2; numptr2 = numptr1; cout << "\n num1 = << num1 << \n*numptr1 = " << *numptr1; cout << "\n num2 = << num2 << \n*numptr2 = " << *numptr2; Exercise 6.2 Show the output of each of the following code segments: a. int num1 = 20, *numptr1, *numptr2, num2 = 0; numptr1 = &num1; numptr2 = &num2; cout << "\n num1 = << num1 << \n*numptr1 = " << *numptr1; cout << "\n num2 = << num2 << \n*numptr2 = " << *numptr2; cout << \n*numptr1 + 8=\t << (*numptr1 + 8); 2017 Gilbert Ndjatou Page 235
6 b. int num1 = 20, *numptr1, *numptr2, num2 = 0; numptr1 = &num1; numptr2 = &num2; num1 += 5; *numptr2 += 10; cout << "\n num1 = << num1 << \n*numptr1 = " << *numptr1; cout << "\n num2 = << num2 << \n*numptr2 = " << *numptr2; c. int num1 = 20, *numptr1, *numptr2, num2 = 0, num3; numptr1 = &num1; numptr2 = &num2; num3 = *numptr1-15; *numptr2 = *numptr1; cout << "\n num1 = << num1 << \n*numptr1 = " << *numptr1; cout << "\n num2 = << num2 << \n*numptr2 = " << *numptr2; cout << "\n num3 = << num3; d. int num1 = 20, *numptr1, *numptr2, num2 = 0; numptr1 = &num1; numptr2 = &num2; numptr2 = numptr1; cout << "\n num1 = << num1 << \n*numptr1 = " << *numptr1; cout << "\n num2 = << num2 << \n*numptr2 = " << *numptr2; When Do You Need a Pointer Variable? You need a pointer variable when there is a need to access a variable without knowing its name: As we will see in one of the next chapters, you can create an unnamed variable in C++ and the only way you can access one such variable is to use its address. In C++, you can also let a function access a local variable of the calling function in one of the following ways: By passing the local variable to the function (by using a reference parameter). By passing the address of the local variable to the function. Passing an Address to a Function You pass the address of a variable to a function by using a value parameter referred to as a pointer parameter as follows: 2017 Gilbert Ndjatou Page 236
7 Pointer Parameter Character pointer Integer pointer Single precision floating point pointer Double precision floating point pointer Address of: character variables integer variables single precision floating point variables double precision floating point variables The following example illustrates the use of pointer parameters: Example 6.5 Passing an Address to a Function Assume given the following definitions of functions tester and main: After the call statement: void tester ( int num, int * pt) * pt = * pt + num; int main() int tvalue = 5; tester ( 7, & tvalue); cout << endl << tvalue = \t << tvalue; return 0; tester ( 7, & tvalue); The body of function tester is executed as if it was written as follows: num = 7; pt = &tvalue; * pt = * pt + num; So the output of the program is: Output tvalue = 12 Note that you accomplish the same thing with reference and pointer parameters: you allow a function to access a local variable of the calling function. The difference is that: With a reference parameter, you pass the variable itself, Whereas with a pointer parameter, you pass its address Gilbert Ndjatou Page 237
8 Exercise 6.3 * a. Show the body of the function tester in the way it is executed after the function call. b. Then execute the program and show its output. void tester ( int num, int * pt) * pt = * pt - num; int main() int tvalue = 20; tester ( 4, & tvalue); cout << endl << tvalue = \t << tvalue; return 0; Exercise 6.4 a. Show the body of the function tester in the way it is executed after the function call. b. Then execute the program and show its output. void tester(int num, int *p1, int *p2) num = num + 5; *p1 = *p1 + 5; *p2 = num ; int main() int i = 10, j, k, *ptr; j = 15; ptr = &j; tester(i, ptr, &k); cout << \ni =\t << i << \nj =\t << j << \nk =\t << k; return(0); 2017 Gilbert Ndjatou Page 238
9 6.2 One-Dimensional Arrays The solutions of some problems are possible only if the data to be processed are stored in the main memory, and are processed as a list. Consider the problem of reading the test scores of 20 students, computing their average, and finding out how many students have a test score above the average. After the average test score is computed, each test score must be compared to it in order to find out how many students have a test score above the average. We must therefore be able to hold all 20 test scores inside the main memory, so that we can compare each one to the average after it has been computed. One way to hold 20 test scores in memory is to use 20 double precision variables. But this approach is not practical because this class could as well have 50 or even 100 students. Another way is to use a one-dimensional array that we will discuss in the following section. Defining and Referencing One-Dimensional Arrays A one-dimensional array is used to create a list of variables with the same data type. You define a one-dimensional array by using the following declaration statement: <data-type> <array-name> [ size ]; <array-name> <data-type> size is the name of the array or the list, is the data type of the variables in the list, and is the number of variables in the list. The following are examples of one-dimensional array definitions: char letter[5]; /*list of 5 variables to hold character values */ int idlist[5]; /* list of 5 variables to hold integer values */ double scores[10]; /*list of 10 variables to hold double precision floating point values */ An individual variable of a one-dimensional array is referred to as an element of the array. An element of the array has a name that consists of the name of the array and an index enclosed between square brackets, and is called an indexed variable. The indexed variables of an array named A and of size n are: A[0], A[1], A[2],..., and A[n-1] Gilbert Ndjatou Page 239
10 The indexed variables for the arrays defined above are given as follows: letter[0], letter[1], letter[2], letter[3], and letter[4]. idlist[0], idlist[1], idlist[2], idlist[3], and idlist[4]. scores[0], scores[1], scores[2], scores[3],..., and scores[9]. Exercise 6.5 * Write the declaration statements to define the following arrays: a. Array scorelist of 20 double precision floating point elements. b. Array line to hold 80 characters c. Array valuelist to hold 50 integer values. Indexed Variables and Memory Locations Contiguous memory locations are allocated for the indexed variables of an array and The name of an array is a pointer constant that holds the address of the first element of the array. Figure 6.5 illustrates the representation of an array in memory. Example 6.6 Indexed Variables and Memory Locations The indexed variables of the following two arrays are represented in memory as follows: char letters[5]; int idlist[5]; Memory letters 2000 A Addresses: letters[0] letters[1] letters[2] letters[3] letters[4] idlist 2300 A Addresses: idlist[0] idlist[1] idlist[2] idlist[3] idlist[4] 2017 Gilbert Ndjatou Page 240
11 Note that a character variable occupies a byte of memory location whereas an integer value occupies a four-byte memory location in an Intel Pentium computer. Exercise 6.6* Write the declaration statement to define each of the following arrays and also show their memory representations (make up memory addresses if they are needed). a. Array letters of 8 characters. b. Array numberlist of 5 integer values. Initializing the Elements of a One-Dimensional Array You can initialize the elements of a one-dimensional array only when it is defined. You initialize a one-dimensional array by following its definition with the assignment operator, which is followed by the list of initial values enclosed between the left and the right braces. The first value in the list is assigned to the first element of the array, the second value to the second element,..., etc. If there are not enough values for all the elements of the array, the rest of the elements are initialized to 0 (for numeric values) and the null character (for characters). Example 6.7 Initializing Arrays 1. int values[5] = 10, 20, 30, 40, 50 ; assigns the values as follows: values[0] values[1] values[2] values[3] values[4] 2. int values[5] = 10, 20, 30 ; assigns the values as follows: values[0] values[1] values[2] values[3] values[4] 2017 Gilbert Ndjatou Page 241
12 3. char letters[5] = A, B ; assigns the values as follows: A B \0 \0 \0 letters[0] letters[1] letters[2] letters[3] letters[4] 4. int values[ ] = 10, 20, 30, 40; assigns the values as follows: values[0] values[1] values[2] values[3] You do not have to specify the size of an array in the declaration statement when it is initialized: The number of elements will be exactly the same as the number of initial values provided in the list of values. An array of characters may also be initialized with a string constant when it is defined in one of the following ways: char <array-name> [size] = <string-constant>; or char <array-name> [size] = <string-constant> ; The characters of the string constant are stored into the elements of the array, including a Null character at the end. Example 6.8 Initializing Arrays with String Constants 1. char name[6] = John ; assigns the values as follows: J o h n \0 \0 name[0] name[1] name[2] name[3] name[4] name[5] 2. char car[ ] = ford ; assigns the values as follows: f o r d \0 car[0] car[1] car[2] car[3] car[4] 2017 Gilbert Ndjatou Page 242
13 Exercise Write a declaration statement to define each of the following arrays: a. Array numberlist of 15 integer elements initialized with the values: 12, 4, 8, 40, -5, 10. b. Array name initialized with the string constant: John Doe. 2. Show the memory representation of each of the following arrays (you should make up memory addresses if they are needed): a. char alist[8] = A, B, C, D, E ; b. int numlist[8] = 15, -10, 25, 30; c. int newlist[ ] = 10, 20, 30, 40, 50, 60; d. char name1[10] = BE HAPPY ; e. char name2[ ] = HAPPY ; Using Indexed Variables In a C/C++ program, an indexed variable is used in the same way that a simple variable with the same data type can be used. The index of an indexed variable does not have to be a constant value: It can be any arithmetic expression (called index expression) that evaluates to an index of the array. Example 6.9 Using Indexed Variables Given the following definitions of variable tscore and array scores: double tscore, scores[10]; 1. The indexed variables of the array scores could be used as follows: scores[2] = 90.5; scores[0] = scores[2] - 6; tscore = scores[2] + 3; scores[1] = tscores - 10; cin >> scores[5]; cout << scores[2] + 1; scores[5]++; 2017 Gilbert Ndjatou Page 243
14 2. With the following definitions of the variables i and j, int i = 2, j = 4; Index expressions may be used to specify the elements of the array scores as follows: Using Index Expressions is processed as scores[i] = 85.5; scores[2] = 85.5; scores[i + 4] = 96.4; scores[6] = 96.4; scores[2 * j - 1] = scores[i +3]; scores[7] = scores[5]; scores[i ++] = 75.0; scores[2] = 75.0; scores[-- j] = 87.5; scores[3] = 87.5; An index expression used to access the elements of an array must evaluate to a value in the range 0 to size - 1, where size is the number of elements in the array. Exercise 6.8* Given the following definitions of array list and variables i and j : int list[ 5] = 5, 10, 15, 20, 25, i = 5, j = 2; a. What is wrong with the statement: cin >> list[i]; b. Show the memory representation of array list. c. Show the memory representation of array list after the execution of the following statements: 1. list[j - 2] = 7; 2. list[j]++; 3. list[- - j] = list[4] + 5; 4. i = 3; 5. j = 3; 6. list[i ++] = list[j + 1] + 10; 7. list[i] = 50; 2017 Gilbert Ndjatou Page 244
15 Processing One-Dimensional Arrays The indexed variables of a one-dimensional array are in general processed as a list of variables: Identical operations are performed on these variables by using a counter-controlled iteration in which these operations are specified in the body-of-the-loop, and the index variable is used as the loop counter. In general, this processing would be specified in C/C++ using a for structure as follows: for(index = 0 ; index < size ; index ++ ) <process element( index)> In the following examples, we will use the array of 10 integer elements named list and the named constant SIZE defined as follows: #define SIZE 10 /* number of elements in the array */ int list [10]; 1. Reading values into an Array for (int i = 0; i < SIZE; i++) cout << \n value for element # \t << i + 1 << \t ; cin >> list[i]; 2. Printing the Values of the Elements of an Array for (int i = 0; i < SIZE; i++) cout << endl << list[i]; 3. Computing the Total Value of the Elements of an Array int totalvalue = 0; for (int i = 0; i < SIZE; i++) totalvalue += list[i]; cout << endl << the total value is:\t << totalvalue; 2017 Gilbert Ndjatou Page 245
16 Exercise 6.9* Given the following definition of array list1: int list1[5] = 10, 20, 30, 40, 50; Show the output of each of the following program segments: a. for(int j = 0 ; j < 5 ; j ++ ) b. for (int j = 4 ; j >= 0 ; j - - ) cout << endl << (list1[j] + j ); cout << endl << list1[j]; Exercise 6.10 Given the following definition of array list2: double list2[10]; a. write a program segment to read values into array list2. b. write a program segment to compute the average of the elements of array list2 and print it. Looking for the Maximum Value in an Array In order to look for the maximum value in an array, we use a variable named maxvalue as follows: We first set variable maxvalue to the first element of the array. We then compare the value is the variable maxvalue with each successive element in the array: if this element of the array is greater, then it replaces the current value of variable maxvalue; otherwise, we do nothing. At the end, variable maxvalue will have the maximum value in the array. The C/C++ code segment is provided as follows: int maxvalue; // to hold the maximum value for (maxvalue = list[0], int i = 1; i < SIZE; i ++) if (maxvalue < list[i]) maxvalue = list[i]; cout << \n the maximum value in the array is:\t << maxvalue; Exercise 6.11* Given array list defined as double list[10]; Write a program segment to look for the minimum value in array list and print it Gilbert Ndjatou Page 246
17 Parallel Arrays Given arrays list1 and list2 defined as follows: int list1[ 10 ] = 3, 8, - 1, 7, 9, 11, 6, 2, 12, -3, list2[ 10 ]; The code segment to add 5 to each element of array list1 and to store the result into the corresponding element of array list2 follows: for ( int i = 0 ; i < 10 ; i+ + ) list2[ i ] = list1[ i ] + 5; Exercise 6.12* Arrays list1, list2, and list3 are defined as follows: int list1[ 5 ] = 23, -12, 45, 9, 11, list2[ 5 ] = 21, -4, 63, 21, -8, list3[ 5 ]; a. write a program segment to subtract each entry of array list2 from the corresponding entry of array list1 and to store the result in the corresponding entry of array list3. b. write a program segment to multiply each entry of array list1 by 5, and to store the result in the corresponding entry of array list3. Exercise Given the following definition of array letters: char letters[10]; a. write a program segment to read 10 characters into array letters. b. write a program segment to print the characters in array letters in reverse order. That means, if the input is: A B C D E F G H I J, the output should be: J I H G F E D C B A. 2. An array of integer values called numlist[20] holds 20 values. a. write a program segment to add 5 to each positive or 0 value in the list, and to subtract 3 from each negative value. b. write a program segment to add 10 to each even value in the list. 3. An array named letterlist holds 20 letters of the alphabet (not necessary all distinct). Write a code segment to replace every occurrence of the letter P in that list with the letter B. That means, PAPA... becomes BABA Gilbert Ndjatou Page 247
18 Passing an Array to a Function The parameter that corresponds to an array argument is specified in a function header as follows: <data-type> <Parameter-name>[ ] The following are examples of functions with array(s) as parameters: /* function readvalues() */ /* read values into an array of integer */ void readvalue(int list[ ], int size) for(int j = 0; j < size; j++) cout << \nenter a value:\t ; cin >> list[ j ]; /* function computeaverage() */ /* compute the average of the elements of an array and return it */ double computeaverage(double scores[ ], int size) double total = 0; /* compute the total of all elements */ for(int j = 0; j < size; j++) total += scores[j]; /* compute and return the average */ return ( total / size ); /* function addlist */ /* add a value to each element of an array and build a new one */ void addlist(int list1[ ], int list2[ ], int num, int size) for(int j = 0; j < size; j++) list2[j] = list1[j] + num; 2017 Gilbert Ndjatou Page 248
19 You pass an array to a function by just passing the address of the first element of that array to it: that means the name of the array. In addition to passing the address of the first element of the array, you must also pass to the function the size of the array so that it knows how many elements are in the array. When a function is called, its body is executed as if the array parameter is replaced by the array argument. Example Given the following definitions of arrays and variables: int idlist[20], numlist1[5] = 10, 20, 30, 40, 50,, numlist2[5]; double testscore[5] = 92.0, 78.5, 86.0, 98.5, 76.0, average; With the call statement: readvalues(idlist, 20); The body of the function readvalues is executed as if it was written as follows: size = 20; for(int j = 0; j < size; j++) cout << \nenter a value:\t ; cin >> idlist[ j ]; With the call statement: average = computeaverage(testscore, 5); The body of the function computeaverage is executed as if it was written as follows: size = 5; double total = 0; /* compute the total of all elements */ for(int j = 0; j < size; j++) total += testscores[j]; /* compute and return the average */ return ( total / size ); 2017 Gilbert Ndjatou Page 249
20 With the call statement: addlist(numlist1, numlist2, 50, 5); The body of the function addlist is executed as if it was written as follows: num = 50; size = 5; for(int j = 0; j < size; j++) numlist2[j] = numlist1[j] + num; Exercise 6.14* 1. Given the following definition of function tester( ): void tester ( int list[ ], int size ) for ( int j = 0 ; j < size ; j + + ) list [ j ] + + ; a. Show the body of function tester in the way it is executed after the following function call: int numlist [ 5 ] = 10, 20, 30, 40, 50 ; tester ( numlist, 5 ); for ( int j = 0 ; j < 5 ; j + + ) cout << endl << numlist[ j ]; c. Execute the code segment above and show its output. Exercise 6.15* a. Write a function with function header int computesum(int list[ ], int size) that receives as argument an array of integer values and its size, and computes and returns the sum of the elements of the array. b. Write the statement(s) to compute and print the sum of the elements of the array numlist[10] = 3, 5, 8, 2, 4, 12, 32, 45, 2, 35; (by calling function computesum) and print it. Exercise a. Write a function with function header void addconst1(int list[ ], int num, int size) to add num to each element of array list. b. Write the statement(s) to add 50 to each element of array numlist (by calling function addconst1( ) ) defined as follows: int numlist[10] = 2, 4, 5, 10, 35, 4, 21, 50, 3, 45; 2017 Gilbert Ndjatou Page 250
21 2. a. Write a function with function header void addconst2(int list1[ ], int list2[ ], int num, int size) to add num to each element of array list1 and to store the result into the corresponding entry of array list2. b. Write the statement(s) to add 50 to each element of array numlist and to store the result in the corresponding entry of array resultlist (by calling function addconst2( )). Array numlist and resultlist are defined as follows: int resultlist[10], numlist[10] = 2, 4, 5, 10, 35, 4, 21, 50, 3, 45; Partially Filled Arrays When you design a program that processes information represented using arrays, the exact number of items to be processed may nt be known in advance. Also, most programs are designed in such a way that the size of the data to be processed may vary from one execution of the program to another. Programmers usually deal with this problem by defining the array(s) with the largest size that the program could possibly need, and then keep track in the program of the last index used in the array(s) as in the following example. Program segment to read one or more values into array list ( -99 is entered as the last dummy value) int lastndx; // to hold the last index used in the array int avalue, // to hold the value read from the keyboard j; cin >> avalue; // read the first value for ( j = 0 ; j < SIZE && avalue!= -99 ; j++) list[j] = avalue; cin >> avalue; // read the nest value lastndx = j - 1; The loop condition here is j < SIZE && avalue!= -99 : We have to make sure that we do not input more values than there are elements in the array, and We must also make sure that the dummy value -99 is not entered into the array. When the loop iterations stop, the current value of the index is one position past the last element used in the array Gilbert Ndjatou Page 251
22 Program segment to print the element used in the array for (int j = 0; j <= lastndx; j++) cout << endl << list[j]; The loop condition here is j <= lastndx instead of j < SIZE : The elements used in the array are list[0], list[1],..., list[lastndx]. Exercise Given array valuelist defined as follows: double valuelist[ 10 ]; a. Write a program segment to read one or more values (up to the maximum of 10 values) into array valuelist. The dummy value -99 is entered to mark the end of the input. Note that you must keep track of the last indexed variable used in the array. b. Write a program segment to print the values read into array valuelist in question 1.a. 2. a. Write the function with function header int readvalues( int list [ ], int size ) that reads one or more values (up to the maximum of size values) into the array that it receives as argument. The dummy value -99 is entered to mark the end of the input. This function returns the index of the last indexed variable used in the array to the caller. b. Write the statements to read one or more values into array numlist (using function readvalues( )) defined as follows: int numlist[ 20 ]; c. Write the statements to print the values read into array numlist in question 2.b Gilbert Ndjatou Page 252
23 6.4 Two-Dimensional Arrays A two-dimensional array allows you to organize and access information inside the computer main memory as a table. It is defined as follows: <data-type> <array-name> [ row ][column]; <array-name> <data-type> row column is the name of the array or the table, is the data type of the elements (variables) in the table, is the number of rows in the table, and the number of columns. Example 1 Scores received by 10 students in 6 lab. assignments in a computer science class are represented using a table as follows: Lab. Assignment # Column Row Student # This table is represented in C/C++ by the two-dimensional array, scoretable[10][6] defined as follows: int scoretable[10][6]; The score of student number 2 on lab. assignment number 5 is 8, and is represented by the array element soretable[1][4]. The score of student number 6 on lab. assignment number 4 is 9, and is represented by the array element scoretable[5][3] Gilbert Ndjatou Page 253
24 Example 2 A page of a computer document that is formatted to hold a maximum of 50 lines of text with a maximum of 80 characters per line can be represented in C/C++ by the two-dimensional array, page[50][80] defined as follows: char page[50][80]; The first character of the first line is represented by the array element page[0][0]. The 25 th character of the 43 rd line is represented by the array element page[42][24]. Indexed variables of a two-dimensional array are used in the same way as indexed variables of a one-dimensional array with the same data type. Example 3 1. Statement to store character H in the 8 th position of the 16 th line: page[15][7] = H ; 2. Statement to adds 2 to the 4 th lab. assignment score of the 8 th student: scoretable[7][3] += 2; 3. Statement to prints the character in the 47 th position of the 20 th line, and the 6 th lab. assignment score of the 9 th student: cout << endl << the character is:\t << page[19][46] << endl << and the score is:\t << classscores[8][5]; 4. Two index expressions (one for the rows and another one for the columns) are used to access the elements of a two-dimensional array as in the following examples: int i = 5, j = 2; classscores[i][j] refers to the same array element as classscores[5][2], and classscores[i - 1][j + 3] refers to the same array element as classscores[4][5]. Exercise 6.18* Write the declaration statements to define each of the following two-dimensional arrays: a. array to hold 6 test scores (integer values) in a class of 20 students. b. array to hold the total sales (double precision values) made by 25 salesmen in 10 cities. c. array to represent a page of a computer document that is formatted to hold a maximum of 45 lines of text with a maximum of 65 characters per line Gilbert Ndjatou Page 254
25 Initializing the Elements of a Two-Dimensional Array A two-dimensional array may be initialized only when it is defined by following its declaration with the equal sign which is followed by the list of the values. Initial values are listed row by row and braces may be used to separate the initial values for one row from those of the other rows. Example The statement: int M[4][5] = 10, 5, -3 17, 83, 9, 0, 0, 8, -7, 32, 20, 1, 0, 14, 0, 0, 8, 7, 6; initializes the elements of array M as follows: M[0][0] = 10 M[0][1] = 5 M[0][2] = -3 M[0][3] = 17 M[0][4] = 83 M[1][0] = 9 M[1][1] = 0 M[1][2] = 0 M[1][3] = 8 M[1][4] = -7 M[2][0] = 32 M[2][1] = 20 M[2][2] = 1 M[2][3] = 0 M[2][4] = 14 M[3][0] = 0 M[3][1] = 0 M[3][2] = 8 M[3][3] = 7 M[3][4] = 6 The above initializations could also be achieved with the following statement in which the braces are omitted: int M[4][5] = 10, 5, -3, 17, 83, 9, 0, 0, 8, -7, 32, 20, 1, 0, 14, 0, 0, 8, 7, 6; However, the statement: int M[4][5] = 10, 5, -3, 9, 2, 7, 32, 20, 1, 0, 0, 8; only initializes the first three columns of each row with the values specified. The last two columns of each row are set to 0 as follows: M[0][0] = 10 M[0][1] = 5 M[0][2] = -3 M[0][3] = 0 M[0][4] = 0 M[1][0] = 9 M[1][1] = 2 M[1][2] = 7 M[1][3] = 0 M[1][4] = 0 M[2][0] = 32 M[2][1] = 20 M[2][2] = 1 M[2][3] = 0 M[2][4] = 0 M[3][0] = 0 M[3][1] = 0 M[3][2] = 8 M[3][3] = 0 M[3][4] = Gilbert Ndjatou Page 255
26 Processing Two-Dimensional Arrays A two-dimensional array is either processed row by row or column by column using nested iterations. In the following examples, we will use the array of integer values consisting of 15 rows and 10 columns named table defined as follows: int table [15][10]; 1. Reading values into array table (It is assumed that the values are entered row by row). for (int row = 0 ; row < 15 ; row ++) cout << \n enter all the values for row # \t << (row + 1) << \t ; for (int column = 0 ; column < 10 ; column ++) cin >> table[ row ] [ column ]; 2. Printing the Elements of array table a. the values are printed one row per line: for (int row = 0; row < 15; row ++) cout << \n values for row # \t << (row + 1); for (int column = 0 ; column < 10 ; column ++) cout << \t << table[ row ][ column ]; b. the values are printed one column per line: for (int column = 0 ; column < 10 ; column ++) cout << \n values for column # \t << (column + 1); for (int row = 0 ; row < 15 ; row ++) cout << \t << table[ row ][ column ]; 2017 Gilbert Ndjatou Page 256
27 Exercise 6.19* 1. Given the following definitions of arrays table1, table2, and table3: int table1[3][5] = 1, 3, 5, 7, 9, 0, 2, 4, 6, 8, 1, 2, 3, 4, 5, table2[3][5], table3[10][10]; a. what is the output of the following program segment? for ( int r = 0 ; r < 3 ; r ++ ) cout << endl; for (int c = 0 ; c < 5 ; c ++) cout << \t << table1[r][c] + 2; b. write a code segment to print the elements of array table1 row by row. c. write a code segment to print the elements of array table1 column by column. d. write a code segment to add 5 to each element of array table1 and to store the result in the corresponding element of array table2. e. write a code segment to built array table3 such that the value for element table[i][j] is i + j. Exercise Define an array to hold 6 test scores (integer values) in a class of 20 students and do the following: a. Write a code segment to read students test scores into that array. b. Write a code segment to compute the average test score for each test and print it. c. Write a code segment to compute the average test score for each student and print it. 2. Define an array to hold the total sales (double precision values) made by 25 salesmen in 10 cities and do the following: a. Write a code segment to read the total sales in the 10 cities for each salesman into the array. b. Write a code segment to compute the sum of the total sales in each city and print it. c. Write a code segment to compute the sum of the total sales for each salesman and print it. Passing a Two-Dimensional Array to a Function The parameter that corresponds to a two-dimensional array argument is specified in a function header as follows: <data-type> <Parameter-name>[ ] [number-of-columns] The following are examples of functions that have parameters that correspond to two-dimensional arrays arguments: 2017 Gilbert Ndjatou Page 257
28 Examples of Functions with two-dimensional Arrays as Parameters /* function readvalues( ) */ /* read values into a two-dimensional array with 6 columns. The values are entered row by row. */ void readvalues (int table[ ][6], int numrow) for (int row = 0 ; row < numrow ; row ++) cout << \n enter all the values for row # \t << (row + 1) << \t ; for (int column = 0 ; column < 6 ; column ++) cin >> table[row][column]; /* function addvalue( ) */ /* add a constant value to each element of a two-dimensional array with 5 column*/ void addvalue(int matrix[ ][5], int num, int numrow) for (int row = 0 ; row < numrow ; row ++) for (int column = 0 ; column < 5 ; column ++) matrix[row][column] += num; /* function computeaverage( ) */ /* compute the average of each row of a two-dimensional array with 6 columns, and print it. */ void computeaverage(int table[ ][6], int numrow) for (int row = 0 ; row < numrow ; row ++) /* compute the sum of the values in this row */ int total; for ( total = 0, int column = 0 ; column < 6 ; column ++) total += table[row][column]; /* compute and print the average */ cout << \n the average for row # << (row + 1) << \tis: ; cout << ( total / 6); 2017 Gilbert Ndjatou Page 258
29 Note that you must specify the number of columns in a two-dimensional array with the parameter. You may also specify the number of rows; but it is not required, and it is not used by the compiler: the number of rows must be passed as an argument. You pass a two-dimensional array to a function by passing the address of the first element of that array (that means the name of the array) to the function. In addition to the address of the first element, you must also pass to the function the number of rows in the array so that it knows how many rows are in the array. When a function is called, its body is executed as if the array parameter is replaced by the array argument. Examples of Calls to Functions with two-dimensional Arrays as Parameters Given the following definitions of arrays classscores and mathtable: int classscores[10][6]; int mathtable[4][5] = 12, 7, 10, 4, 24, 5, 21, 5, 9, 4, 23, -5, 7, 30, 34, 14, 12, 11, 4, 8; With the call statement: readvalues ( classscores, 10 ); The body of the function readvalue is executed as if it was written as follows: numrow = 10; for (int row = 0 ; row < numrow ; row ++) cout << \n enter all the values for row # \t << (row + 1) << \t ; for (int column = 0 ; column < 6 ; column ++) cin >> classscores[row][column]; With the call statement: computeaverage (classscores, 10); The body of the function computeaverage is executed as if it was written as follows: numrow = 10; for (int row = 0 ; row < numrow ; row ++) /* compute the sum of the values in this row */ int total; for ( total = 0, int column = 0 ; column < 6 ; column ++) total += classscores[row][column]; 2017 Gilbert Ndjatou Page 259
30 /* compute and print the average */ cout << \n the average for row # << (row + 1) << \tis: ; cout << ( total / 6); With the call statement: addvalue ( mathtable, 50, 4); The body of the function addvalue is executed as if it was written as follows: numrow = 4; for (int row = 0 ; row < numrow ; row ++) for (int column = 0 ; column < 5 ; column ++) mattable[ row ][ column ] += num; Exercise 6.21* a. Write the function with function header void addten(int table[][5], int row) that receives a twodimensional array with 5 columns and its number of rows, and adds 10 to each element of that array. b. Given the following definition of array table1: int table1[3][5] = 1, 3, 5, 7, 9, 0, 2, 4, 6, 8, 1, 2, 3, 4, 5; Write a statement to add 10 to each element of array table1 by calling function addten. Exercise 6.22 a. Write the function with function header int computetotal(int table[][5], int row) that receives a twodimensional array with 5 columns and its number of rows, and computes the sum of all the elements of that array and returns it. b. Given the following definition of array table1: int table1[3][5] = 1, 3, 5, 7, 9, 0, 2, 4, 6, 8, 1, 2, 3, 4, 5; Write the statements to compute the sum of all the elements of array table1 (by calling function computetotal) and print it. Exercise 6.23 a. Write the function with function header void computerowsum(int table[][5], int list[], int row) that receives a two-dimensional array with 5 columns, a one- dimensional array, and the number of rows in the two-dimensional array which is also the number of elements in the one-dimensional array. This function computes the sum of the elements in each row of the two-dimensional array and stores the result in the corresponding element of the one-dimensional array Gilbert Ndjatou Page 260
31 b. Given the following definition of arrays table1 and result: int table1[3][5] = 1, 3, 5, 7, 9, 0, 2, 4, 6, 8, 1, 2, 3, 4, 5; int result[3]; Write a statement to compute the sum of each row of array table1 and to store the result in the corresponding element of array result by calling function computerowsum( ) Gilbert Ndjatou Page 261
32 6.5 Sorting and Searching Sorting a list of values is the process of rearranging those values so that they are listed either in ascending order (from the smallest to the largest), or in descending order (from the largest to the smallest). One algorithm to sort a list of values, called bubble sort is described as follows: Bubble Sort Sort in ascending order (using bubble sort) the list of values: First pass through the list: i = 0 Compare 7 to 4: 7 is greater than 4, so interchange them new list is: i = 1 Compare 7 to 8: 7 is less than 8, so do nothing list is: i = 2 Compare 8 to 5: 8 is greater than 5, so interchange them new list is: i = 3 Compare 8 to 3: 8 is greater than 3, so interchange them new list is: Second pass through the list: i = 0 Compare 4 to 7: 4 is less than 7, so do nothing list is: i = 1 Compare 7 to 5: 7 is greater than 5, so interchange them new list is: i = 2 Compare 7 to 3: 7 is greater than 3, so interchange them new list is: i = 3 Compare 7 to 8: 7 is less than 8, so do nothing list is: Third pass through the list: i = 0 Compare 4 to 5: 4 is less than 5, so do nothing list is: i = 1 Compare 5 to 3: 5 is greater than 3, so interchange them new list is: i = 2 Compare 5 to 7: 5 is less than 7, so do nothing list is: i = 3 Compare 7 to 8: 7 is less than 8, so do nothing list is: Fourth pass through the list: i = 0 Compare 4 to 3: 4 is greater than 3, so interchange them new list is: i = 1 Compare 4 to 5: 4 is less than 5, so do nothing list is: i = 2 Compare 5 to 7: 5 is less than 7, so do nothing list is: i = 3 Compare 7 to 8: 7 is less than 8, so do nothing list is: Gilbert Ndjatou Page 262
33 The algorithm to perform one pass through the list is called one pass bubble sort. It is specified in terms of a list (array ) of n elements as follows: 1. Initialize the list index i to 0 (first element of the list). 2. As long as the list index i is less than n - 2 do the following: 2.1 if list [ i ] is greater than list [ i + 1], interchange them. 2.2 increment list index i by 1 (move to the next element in the list). Note that if we are sorting in descending order, then the test: list [ i ] is greater than list [ i + 1] will be replaced with the test: list [ i ] is less than list [ i + 1] After one pass through the list, the largest element is moved to the last position in the list; after the second pass, the second largest element is moved to the next to last position; and... after n 1 passes, the smallest element is moved to the first place. The bubble sort algorithm to sort a list of n values (in ascending order) is then given as follows: Bubble Sort Algorithm 1. Set passcount to As long as passcount is less than or equal to n - 1, do the following: 2.1 Initialize the list index i to As long as the list index i is less than n - 1 do the following: if list[i] is greater than list[i + 1] do the following: interchange them increment the list index i by increment passcount by Gilbert Ndjatou Page 263
34 It is implemented in C/C++ as follows: /* perform SIZE -1 passes through the list */ /* SIZE is the name of the number of elements in the array */ for (int passcount = 1; passcount < SIZE ; passcount ++) for (int i = 0; i < SIZE - 1; i ++) /* perform one pass */ if (list[i] > list[ i +1]) /*they are not in order */ /* interchange them */ int temp; temp = list[i]; list[i] = list[ i + 1]; list[i + 1] = temp; Exercise 6.24* 1. What is the effect of the following program segment? #define MAX 50 int list[max]; for (int i = 0 ; i < MAX - 1 ; ++i ) if ( list[i] < list[i + 1] ) int temp; temp = list[i]; list[i] = list[i + 1]; list[i + 1] = temp; 2. List[20] is an array of 20 integer values. Write a program segment to sort the elements of this array in descending order using the bubble sort algorithm Gilbert Ndjatou Page 264
35 Exercise An array of integer values called idlist[20]is used to hold the Ids of 20 students, and a double precision floating point array called scorelist[20] is used to hold their test scores. a. Write a program segment to sort students scores in ascending order using the bubble sort algorithm. b. Write a program segment to sort their Ids in descending order using the bubble sort algorithm 2. The bubble sort algorithm provided in the text performs n - 1passes through the list even when the original list is already sorted. To prevent it from performing another pass through a list that is already sorted, one could use a variable named anotherpass that is set to 0 (no other pass is needed) before performing a pass through the list, and if no swapping of values occurs in the list (that means that the list is sorted), the value of variable anotherpass stays 0, and the process stops; if however a swapping occurs (the list is not sorted), the value of variable anotherpass is changed to 1 (another pass is needed). The algorithm is specified as follows: 1. Set variable anotherpass to 1 and variable passcount to As long as variable anotherpass is 1 and passcount is less than n, do the following: 2.1 Set variable anotherpass to Initialize the list index i to As long as the list index i is less than n - 1 do the following: if list[i] is greater than list[i + 1] do the following: interchange them set variable anotherpass to increment the list index i by increment variable passcount by 1. a. Write the program segment that corresponds to this algorithm. b. When we use the bubble sort algorithm to sort a list (in ascending order), after the first pass through the list, the largest value is in the last position, and after the second pass, the second largest value is in the second to the last position,..., etc. However, in the algorithm provided above and in the text, each pass through the list compares all pairs of elements, including those that we know are already in order. Modify these two algorithms such that unnecessary comparisons are not performed in a pass through the list. For example, in the second pass, the next to the last element and the last element should not be compared Gilbert Ndjatou Page 265
36 Searching a List Searching a list of values is the process of going through the list to find out if a given value is one of these values. One primary reason for searching a list is to find a given item to be modified or replaced. Two issues are important in a searching process: The first is whether all occurrences of the given value or only one occurrence need to be found; The second is whether the list is sorted or not. These issues can greatly influence the choice of the algorithm to use in the searching process. Two searching algorithms are discussed in this section: The first is called linear (or sequential ) search and is mostly used when the list is not sorted; The second is called binary search and can be used only when the list is sorted. Both algorithms only look for one occurrence of the given value in the list. In order to describe these algorithms, we will use a list of integer values (array list) and two variables: givenvalue, and position: givenvalue (integer) holds the value being searched for in the list. position (integer) is used to indicate whether the given value is in the list or not: it is set to the index of the item if it is found, and -1 otherwise. SIZE (is a macro constant) that names the number of elements in the list. Linear Search Linear search starts with the first position in the list and compares the given value with each subsequent element in the list, until it is equal to one of them, or the last position in the list is reached. It is specified in pseudo-code as follows: 1. Set variable position to -1 (not found), and the list index i to As long as variable position is -1 and i is less than SIZE, do the following: 2.1 if givenvalue is equal to list[i] do the following: Set variable position to i (it is found in position i). 2.2 increment list index i by If variable position is -1, do the following: 3.1 report that the given value is not found in the list. 4. Otherwise, do the following: 4.1 report that it is found in position (value of variable position) Gilbert Ndjatou Page 266
calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!
Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns
More informationLecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)
Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of
More informationArrays and functions Multidimensional arrays Sorting and algorithm efficiency
Introduction Fundamentals Declaring arrays Indexing arrays Initializing arrays Arrays and functions Multidimensional arrays Sorting and algorithm efficiency An array is a sequence of values of the same
More informationChapter 3 Problem Solving and the Computer
Chapter 3 Problem Solving and the Computer An algorithm is a step-by-step operations that the CPU must execute in order to solve a problem, or to perform that task. A program is the specification of an
More informationBITG 1113: Array (Part 1) LECTURE 8
BITG 1113: Array (Part 1) LECTURE 8 1 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional (1 D)
More informationReview of Important Topics in CS1600. Functions Arrays C-strings
Review of Important Topics in CS1600 Functions Arrays C-strings Array Basics Arrays An array is used to process a collection of data of the same type Examples: A list of names A list of temperatures Why
More informationIntroduction to Computer Science Midterm 3 Fall, Points
Introduction to Computer Science Fall, 2001 100 Points Notes 1. Tear off this sheet and use it to keep your answers covered at all times. 2. Turn the exam over and write your name next to the staple. Do
More informationFORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):
FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. If a function has default arguments, they can be located anywhere
More informationChapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:
Chapter 8 Arrays and Strings Objectives In this chapter, you will: Learn about arrays Declare and manipulate data into arrays Learn about array index out of bounds Learn about the restrictions on array
More informationBITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)
BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18) 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional
More informationKOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming
KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 ARRAYS ~ VECTORS KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 What is an array? Arrays
More informationC++ Programming Chapter 7 Pointers
C++ Programming Chapter 7 Pointers Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics & Department
More informationChapter 1 INTRODUCTION
Chapter 1 INTRODUCTION A digital computer system consists of hardware and software: The hardware consists of the physical components of the system. The software is the collection of programs that a computer
More informationSubject: Computer Science
Subject: Computer Science Topic: Data Types, Variables & Operators 1 Write a program to print HELLO WORLD on screen. 2 Write a program to display output using a single cout statement. 3 Write a program
More informationHomework #3 CS2255 Fall 2012
Homework #3 CS2255 Fall 2012 MULTIPLE CHOICE 1. The, also known as the address operator, returns the memory address of a variable. a. asterisk ( * ) b. ampersand ( & ) c. percent sign (%) d. exclamation
More informationArrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA.
Arrays Defining arrays, declaration and initialization of arrays Introduction Many applications require the processing of multiple data items that have common characteristics (e.g., a set of numerical
More informationFORM 2 (Please put your name and form # on the scantron!!!!)
CS 161 Exam 2: FORM 2 (Please put your name and form # on the scantron!!!!) True (A)/False(B) (2 pts each): 1. Recursive algorithms tend to be less efficient than iterative algorithms. 2. A recursive function
More informationPOINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory
More informationC++ for Java Programmers
Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even
More informationKingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS
Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size
More informationChapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:
Chapter-11 POINTERS Introduction: Pointers are a powerful concept in C++ and have the following advantages. i. It is possible to write efficient programs. ii. Memory is utilized properly. iii. Dynamically
More informationPointers Pointer Variables. Pointer Variables Getting the Address of a Variable. Each variable in program is stored at a
3.1. Getting the Address of a Variable Pointers (read Chapter 9. Starting Out with C++: From Control Structures through Objects, Tony Gaddis.) Le Thanh Huong School of Information and Communication Technology
More informationLecture 3 Tao Wang 1
Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers
More informationCSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 6: One Dimensional Array
Lesson Outcomes At the end of this chapter, student should be able to: Define array Understand requirement of array Know how to access elements of an array Write program using array Know how to pass array
More informationLecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?
Lecture 14 No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions? Friday, February 11 CS 215 Fundamentals of Programming II - Lecture 14 1 Outline Static
More informationExam 3 Chapters 7 & 9
Exam 3 Chapters 7 & 9 CSC 2100-002/003 29 Mar 2017 Read through the entire test first BEFORE starting Put your name at the TOP of every page The test has 4 sections worth a total of 100 points o True/False
More informationCS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010
CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please
More informationCS 161 Exam II Winter 2018 FORM 1
CS 161 Exam II Winter 2018 FORM 1 Please put your name and form number on the scantron. True (A)/False (B) (28 pts, 2 pts each) 1. The following array declaration is legal double scores[]={0.1,0.2,0.3;
More informationFunctions. Introduction :
Functions Introduction : To develop a large program effectively, it is divided into smaller pieces or modules called as functions. A function is defined by one or more statements to perform a task. In
More informationCS201 Spring2009 Solved Sunday, 09 May 2010 14:57 MIDTERM EXAMINATION Spring 2009 CS201- Introduction to Programming Question No: 1 ( Marks: 1 ) - Please choose one The function of cin is To display message
More informationC++ PROGRAMMING SKILLS Part 4: Arrays
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
More informationLab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1
Lab 2: Pointers 1. Goals Further understanding of pointer variables Passing parameters to functions by address (pointers) and by references Creating and using dynamic arrays Combing pointers, structures
More informationObjectives. Chapter 8 Arrays and Strings. Objectives (cont d.) Introduction 12/14/2014. In this chapter, you will:
Objectives Chapter 8 Arrays and Strings In this chapter, you will: Learn about arrays Declare and manipulate data into arrays Learn about array index out of bounds Learn about the restrictions on array
More informationProcedural Programming
Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Procedural Programming Session Five: Arrays Name: First Name: Tutor: Matriculation-Number: Group-Number: Date: Prof. Dr.Ing. Axel Hunger Dipl.-Ing.
More informationCS2255 HOMEWORK #1 Fall 2012
CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The
More informationComputer Programming: C++
The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming: C++ Experiment #7 Arrays Part II Passing Array to a Function
More informationPROGRAMMAZIONE I A.A. 2017/2018
PROGRAMMAZIONE I A.A. 2017/2018 A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. DECLARING POINTERS POINTERS A pointer represents both
More informationComputer Programming C++ (wg) CCOs
Computer Programming C++ (wg) CCOs I. The student will analyze the different systems, and languages of the computer. (SM 1.4, 3.1, 3.4, 3.6) II. The student will write, compile, link and run a simple C++
More informationObjectives of This Chapter
Chapter 6 C Arrays Objectives of This Chapter Array data structures to represent the set of values. Defining and initializing arrays. Defining symbolic constant in a program. Using arrays to store, list,
More informationHelp File on C++ and Programming at CSUSM by Rika Yoshii
Help File on C++ and Programming at CSUSM by Rika Yoshii Compiler versus Editor empress.csusm.edu is a machine that you remotely log into from anywhere using putty, empress.csusm.edu uses the operating
More informationHere, 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
Arrays 1. Introduction An array is a consecutive group of memory locations that all have the same name and the same type. A specific element in an array is accessed by an index. The lowest address corresponds
More informationObjectives. In this chapter, you will:
Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about
More informationCS201- Introduction to Programming Current Quizzes
CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements
More informationHigh Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd
El-Shorouk Academy Acad. Year : 2013 / 2014 High Institute of Computer Science & Information Technology Term : 1 st Year : 2 nd Computer Science Department Object Oriented Programming Section (1) Arrays
More informationC How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.
C How to Program, 7/e This chapter serves as an introduction to data structures. Arrays are data structures consisting of related data items of the same type. In Chapter 10, we discuss C s notion of
More informationOutput of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8
Pointers Variables vs. Pointers: A variable in a program is something with a name and a value that can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within
More informationPointer Basics. Lecture 13 COP 3014 Spring March 28, 2018
Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory
More informationIntroduction to Scientific Computing and Problem Solving
Introduction to Scientific Computing and Problem Solving Lecture #22 Pointers CS4 - Introduction to Scientific Computing and Problem Solving 2010-22.0 Announcements HW8 due tomorrow at 2:30pm What s left:
More informationIntroduction to Arrays
Introduction to Arrays One Dimensional Array. Two Dimensional Array. Inserting Elements in Array. Reading Elements from an Array. Searching in Array. Sorting of an Array. Merging of 2 Arrays. What is an
More informationFORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:
FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. The declaration below declares three pointer variables of type pointer to double that is
More informationLab 3. Pointers Programming Lab (Using C) XU Silei
Lab 3. Pointers Programming Lab (Using C) XU Silei slxu@cse.cuhk.edu.hk Outline What is Pointer Memory Address & Pointers How to use Pointers Pointers Assignments Call-by-Value & Call-by-Address Functions
More information9.2 Pointer Variables. Pointer Variables CS Pointer Variables. Pointer Variables. 9.1 Getting the Address of a. Variable
CS 1400 Chapter 9 9.1 Getting the Address of a Variable A variable has: Name Value Location in a memory Type The location in memory is an address Use address operator & to get address of a variable: int
More informationCISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts)
CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts) For this lab you may work with a partner, or you may choose to work alone. If you choose to work with a partner, you are still responsible for the lab
More informationCSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011
CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 Date: 01/18/2011 (Due date: 01/20/2011) Name and ID (print): CHAPTER 6 USER-DEFINED FUNCTIONS I 1. The C++ function pow has parameters.
More informationChapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.
Chapter 9: Pointers 9.1 Getting the Address of a Variable C++ Variables [ not in book ] A Variable has all of the following attributes: 1. name 2. type 3. size 4. value 5. storage class static or automatic
More informationArrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff
and Arrays Comp Sci 1570 Introduction to C++ Outline and 1 2 Multi-dimensional and 3 4 5 Outline and 1 2 Multi-dimensional and 3 4 5 Array declaration and An array is a series of elements of the same type
More informationCHAPTER 4 FUNCTIONS. 4.1 Introduction
CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main
More informationFunctions, Arrays & Structs
Functions, Arrays & Structs Unit 1 Chapters 6-7, 11 Function Definitions! Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements... Where a parameter is: datatype identifier
More informationControl Structures. Flowchart Symbols
Control Structures The basic operations of a C/C++ programming language are specified using the following statements or structures: the input statement the output statement the assignment statements the
More informationScott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes
Scott Gibson Pointers & Dynamic Memory Lecture #1 Office: LAH 103 Email: sgibson@brookdalecc.edu sgib@optonline.net Web: www.brookdalecc.edu/fac/cos/sgibson Phone: (732) 224 2285 1 2 Pre & Co Requisites
More informationPointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.
Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference
More informationComputer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];
Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data
More information! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body
Week 3 Pointers, References, Arrays & Structures Gaddis: Chapters 6, 7, 9, 11 CS 5301 Fall 2013 Jill Seaman 1 Arguments passed by value! Pass by value: when an argument is passed to a function, its value
More informationChapter 7 : Arrays (pp )
Page 1 of 45 Printer Friendly Version User Name: Stephen Castleberry email Id: scastleberry@rivercityscience.org Book: A First Book of C++ 2007 Cengage Learning Inc. All rights reserved. No part of this
More informationCS2141 Software Development using C/C++ C++ Basics
CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short
More informationMore on Arrays CS 16: Solving Problems with Computers I Lecture #13
More on Arrays CS 16: Solving Problems with Computers I Lecture #13 Ziad Matni Dept. of Computer Science, UCSB Announcements Homework #12 due today No homework assigned today!! Lab #7 is due on Monday,
More informationRecursion. Example R1
Recursion Certain computer problems are solved by repeating the execution of one or more statements a certain number of times. So far, we have implemented the repetition of one or more statements by using
More informationArrays. Lecture 9 COP 3014 Fall October 16, 2017
Arrays Lecture 9 COP 3014 Fall 2017 October 16, 2017 Array Definition An array is an indexed collection of data elements of the same type. Indexed means that the array elements are numbered (starting at
More informationC++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay
C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming
More informationPointers. Variable Declaration. Chapter 10
Pointers Chapter 10 Variable Declaration When a variable is defined, three fundamental attributes are associated with it: Name Type Address The variable definition associates the name, the type, and the
More informationC++ for Engineers and Scientists. Third Edition. Chapter 12 Pointers
C++ for Engineers and Scientists Third Edition Chapter 12 Pointers CSc 10200! Introduction to Computing Lecture 24 Edgardo Molina Fall 2013 City College of New York 2 Objectives In this chapter you will
More informationChapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)
Chapter - Arrays 1.1 Introduction 2.1 Introduction.2 Arrays.3 Declaring Arrays. Examples Using Arrays.5 Passing Arrays to Functions.6 Sorting Arrays. Case Study: Computing Mean, Median and Mode Using Arrays.8
More informationUNIT- 3 Introduction to C++
UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage
More informationInstructor: Eng.Omar Al-Nahal
Faculty of Engineering & Information Technology Software Engineering Department Computer Science [2] Lab 6: Introduction in arrays Declaring and Creating Arrays Multidimensional Arrays Instructor: Eng.Omar
More informationObjectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program
Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationSTUDENT LESSON A12 Iterations
STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of
More informationChapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationChapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types
Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using
More informationChapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction
Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers
More informationPointer Data Type and Pointer Variables
Pointer Data Type and Pointer Variables Pointer variable: content is a memory address There is no name associated with the pointer data type in C++. Declaring Pointer Variables Syntax: Data-type *identifier
More informationProgramming for Engineers Arrays
Programming for Engineers Arrays ICEN 200 Spring 2018 Prof. Dola Saha 1 Array Ø Arrays are data structures consisting of related data items of the same type. Ø A group of contiguous memory locations that
More information! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)
Final Exam Exercises Chapters 1-7 + 11 Write C++ code to:! Determine if a number is odd or even CS 2308 Fall 2018 Jill Seaman! Determine if a number/character is in a range - 1 to 10 (inclusive) - between
More informationTutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays
Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Outline 13.1 Test-Driving the Salary Survey Application 13.2 Introducing Arrays 13.3 Declaring and Initializing Arrays 13.4 Constructing
More informationAbstract Data Type (ADT) & ARRAYS ALGORITHMS & DATA STRUCTURES I COMP 221
Abstract Data Type (ADT) & ARRAYS ALGORITHMS & DATA STRUCTURES I COMP 221 Abstract Data Type (ADT) Def. a collection of related data items together with an associated set of operations e.g. whole numbers
More informationArrays. Week 4. Assylbek Jumagaliyev
Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays
More information! A pointer variable (or pointer): ! An asterisk is used to define a pointer variable. ! ptr is a pointer to an int or
Ch 9. Pointers CS 2308 Spring 2014 Jill Seaman 1 A Quote A pointer is a variable that contains the address of a variable. Pointers are much used in C, partly because they are sometimes the only way to
More informationPrinciples of Programming. Chapter 6: Arrays
Chapter 6: Arrays In this chapter, you will learn about Introduction to Array Array declaration Array initialization Assigning values to array elements Reading values from array elements Simple Searching
More informationUEE1302 (1102) F10 Introduction to Computers and Programming (I)
Computational Intelligence on Automation Lab @ NCTU UEE1302 (1102) F10 Introduction to Computers and Programming (I) Programming Lecture 10 Pointers & Dynamic Arrays (I) Learning Objectives Pointers Data
More informationChapter 7 Array. Array. C++, How to Program
Chapter 7 Array C++, How to Program Deitel & Deitel Spring 2016 CISC 1600 Yanjun Li 1 Array Arrays are data structures containing related data items of same type. An array is a consecutive group of memory
More informationby Pearson Education, Inc. All Rights Reserved.
Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]
More informationC++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I
C++ ARRAYS POINTERS POINTER ARITHMETIC Problem Solving with Computers-I General model of memory Sequence of adjacent cells Each cell has 1-byte stored in it Each cell has an address (memory location) Memory
More information[0569] p 0318 garbage
A Pointer is a variable which contains the address of another variable. Declaration syntax: Pointer_type *pointer_name; This declaration will create a pointer of the pointer_name which will point to the
More informationPointers. Memory. void foo() { }//return
Pointers Pointers Every location in memory has a unique number assigned to it called it s address A pointer is a variable that holds a memory address A pointer can be used to store an object or variable
More informationArrays. Arizona State University 1
Arrays CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 8 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationUNIT-I Fundamental Notations
UNIT-I Fundamental Notations Introduction to Data Structure We know that data are simply values or set of values and information is the processed data. And actually the concept of data structure is much
More informationTopics: Material through example 19 (types, operators, expressions, functions, selection, loops, arrays)
CPSC 122 Study Guide: Examination 1 Topics: Material through example 19 (types, operators, expressions, functions, selection, loops, arrays) 1. What is the output? int x, y; x = y = 0; while(x < 5) y +=
More informationAdd Subtract Multiply Divide
ARITHMETIC OPERATORS if AND if/else AND while LOOP Order of Operation (Precedence Part 1) Copyright 2014 Dan McElroy Add Subtract Multiply Divide + Add - Subtract * Multiply / Divide = gives the quotient
More informationCOMP26120: Pointers in C (2018/19) Lucas Cordeiro
COMP26120: Pointers in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Organisation Lucas Cordeiro (Senior Lecturer, FM Group) lucas.cordeiro@manchester.ac.uk Office: 2.44 Office hours: 10-11
More informationArrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur
Arrays CS10001: Programming & Data Structures Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Array Many applications require multiple data items that have common
More informationArrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal
Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Review what an array is Review how to declare arrays Review what reference variables are Review how to pass arrays to methods Review
More information