Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function, when an array is the formal parameter, is the base address of the array (the memory address of the first element in the array). This is true whether the array has one or more dimensions. When declaring a 1-D array parameter, the compiler only needs to know that the parameter is an array; it doesn t need to know its size. The complier will ignore it, if it is included. However, inside the function we still need to make sure that only legitimate array elements are referenced. Thus a separate parameter specifying the length of the array must also be passed to the function. int ProcessValues (int [], int ); // works with ANY 1-d array Example: int SumValues (int [], int ); //function prototype void main( ) int Array[10]=0,1,2,3,4,5,6,7,8,9; int total_sum; total_sum = SumValues (Array, 10); //function call cout << Total sum is <<total_sum; int SumValues (int values[], int num_of_values) //function header int sum = 0; for( int i=0; i < num_of_values; i++) sum+=values[i]; return sum; Note that we are using only the name of the array in the function call: Array, not Array[10]. 1
Since arrays are always passed by reference, all changes made to the array elements inside the function will be made to the original array. The only way to protect the elements of the array from being inadvertently changed, is to declare an array to be a const parameter. Example: int SumValues (const int [], int); //function prototype int main( ) const int length =10; int Array[10]=0,1,2,3,4,5,6,7,8,9; int total_sum; total_sum = SumValues (Array, length); cout << Total sum is <<total_sum; return 0; //function call int SumValues (const int values[], int num_of_values) //function header int sum = 0; for( int i=0; i < num_of_values; i++) sum+=values[i]; return sum; Since you do not intend to change the values of an array in the above function, make it a const parameter to protect yourself. The original array (in the main) should not be const, or you wouldn t be able to make any changes to it at all. You do not however need to make the length of an array a const parameter, since it is passed by value and any changes to it will not affect the actual parameter. The compiler will not allow you to pass it by reference if it was declared as a const int in the main ( ). 2
Passing arrays to functions (examples) 4/9/04 Passing arrays to functions (Examples). //example of passing one-dimensional array to functions int maximum_1_d (int[ ], int); void main() const int size = 5; int nums[size] = 2,18,1,25,3; // 1-D array cout << "The max value of array nums is " << maximum_1_d(nums, size) << endl; int maximum_1_d ( int vals[ ], int number_elements) int i, max = vals[0]; for (i=0; i<number_elements; i++) if (max <vals[i]) max = vals[i]; return max; 1
Passing arrays to functions (examples) 4/9/04 // The called function receives access to the actual array, not a copy of the values in the // array. Thus any changes made to the array within the function change the original // array. void change_1_d(int[], int); // function prototype void main() const int size = 5; int i; int nums[size] = 2,18,1,25,3; cout << "The values in array nums before the functions call are "; for (i=0; i<size;i++) cout<<nums[i]<<' '; cout<<endl; change_1_d(nums,size); //function call cout << "The values in array nums after the functions call are "; for (i=0; i<size;i++) cout<<nums[i]<<' '; cout<<endl; void change_1_d(int vals[], int number_elements) //function header int i; // let's try to change the values in vals for (i=0;i<number_elements; i++) vals[i]=i; 2
1D Arrays Code example: passing arrays to functions void get_array(int[], int); int calc_sum(int[], int); void display_array(int[], int); void main () int num[1000]; int n; cout << "Enter size of array (must be < 1000):"; cin >> n; int sum; get_array(num, n); cout << endl; display_array(num, n); cout << endl; sum = calc_sum(num, n); cout << "The sum is " << sum << endl; void get_array(int arr[], int size) for (int k = 0; k < size; k++) cout << "Please enter value for arr[" << k << "]:"; cin >> arr[k]; int calc_sum(int arr[], int size) int s = 0; for (int i = 0; i < size; i++) s += arr[i]; return s; void display_array(int arr[], int size) for(int j = 0; j < size; j++) cout << "arr[" << j << "] = " << arr[j] << endl;
1 Strings A string literal (or string) is any sequence of characters enclosed in double quotes. In C++ strings of characters are held as an array of characters, one character held in each array element. A special null character, represented by `\0', is appended to the end of the string to indicate the end of the string. Think of it as a sentinel that marks the end of every string. If a string has n characters then it requires an n+1 element array (at least) to store it. Note: \0 is stored by the compiler as a single character. A single character enclosed in double quotes, rather than single quotes, is also viewed by the compiler as a string. Character in single quotes - `a'- is stored in a single byte. Character in double quotes -"a" is stored in two consecutive bytes holding the character `a' and the null character. Examples of strings: o This is a string o xyz 123 *!#@@& o m o A string variable s1 could be declared as follows: char s1[10]; The string variable s1 could hold strings of length up to nine (only 9!!!) characters since space is needed for the final null character. Strings can be initialized at the time of declaration just as other variables are initialized. For example: char s1[] = "example"; char s2[20] = "another example" would store the two strings as follows: s1 e x a m p l e \0 s2 a n o t h e r e x a m p l e \0???? In the first case the array would be allocated space for eight characters, that is space for the seven characters of the string and the null character. In the second case the string is set by the declaration to be twenty characters long but only sixteen of these characters are set, i.e. the fifteen characters of the string and the null character. Note that the length of a string does not include the terminating null character.
2 Note: The individual characters in the string can be handled with standard array operations More examples of String Initialization Each of the following declarations produces the same result: char test[5] = abcd ; char test[ ] = abcd ; char test[5] = a, b, c, d, \0 ; char test[ ] = a, b, c, d, \0 ; String Output: A string is output by sending it to an output stream, for example: cout << "The string s1 is " << s1 << endl; would print The string s1 is example String Input (single word) When the input stream cin is used, space characters, newline etc. are used as separators and terminators. Thus when inputting numeric data cin skips over any leading spaces and terminates reading a value when it finds a white-space character (space, tab, newline etc. ). This same system is used for the input of strings, hence a string to be input cannot start with leading spaces, also if it has a space character in the middle then input will be terminated on that space character. The null character will be appended to the end of the string in the character array by the stream functions. If the string s1 was initialized char s1[] = "example"; then the statement cin << s1; would set the string s1 as follows when the string "first" is entered (without the double quotes) f i r s t \0 e \0 Note that the last two elements are a relic of the initialization at declaration time.
3 Note: If the string that is entered is longer than the space available for it in the character array then C++ will just write over whatever space comes next in memory. This can cause some very strange errors when some of your other variables reside in that space! String Input (several words, i.e. strings that contain spaces) To read a string with several words in it we can call cin once for each word. A better way is to use cin.getline( ) or cin.get( ) cin.getline( ) continuously accepts and stores characters typed at the terminal into the character array until either the array size is reached or the end-of-string(null, \0) marker is detected. (Note: \n is input when the Enter key is depressed. This character is interpreted by cin.getline( ) as the end-of-line entry. cin.getline( ) inserts the \0 character in place of the \n character at the end of the array.). whereas cin reads entry up to the first blank space or \n, cin.getline( ) accepts whitespace as a character and terminates with \n (or until the array if full). syntax: o cin.getline(string, terminating-length, terminating-character) string a string or character pointer variable terminating-length an integer constant or variable indicating the maximum number of input characters that can be input terminating-character an optional character constant or variable specifying the terminating character if omitted, the default terminating character is the newline ( \n ) character Examples: cin.getline(message, size); cin.getline(message, size, \n ); cin.getline(message, size, x ); the first two functions stop reading characters when the Return key is pressed or until size characters have been read, whichever comes first. The third function continues until size or the character x have been read. cin.get( ) reads in a single character at a time. Will read any character. if you need to read the ENTER key, a space, or the tab key, you cannot use cin. These characters stop cin from reading!!! You must use cin.get because cin.get will read any character. Example: char c1; cin.get(c1) - reads a single character into variable c1
Character Arrays and Strings: Worksheet 2 1. What is the difference between character arrays and strings? 2. char my_word[5] = c, l, a, s, s ; a. Is it a character array or a string? Why? b. How can you display it to the screen? 3. char my_word[6] = c, l, a, s, s, \0 ; a. Is it a character array or a string? Why? b. How can you display it to the screen? 4. Given the following declaration: char hello[3] = hi ; a. What is hello[0] = b. What is hello[2] = c. What is hello[3] = d. Adding the following lines: hello[1] = m ; cout << hello; What is displayed on a screen?
5. Write a code segment that will prompt the user for his first name and his last name and display to the screen: Hello, first_name last_name. 6. Write a function that will accept two strings and return true if they are equal in length and false if they are not. 7. Write a function that will accept an integer array, its size and a code integer. The function should find the location of that code integer in the array and return it s position (index) in the array or 999 if the code was not found in the array.
1D Arrays Code example: manipulating strings int calc_length(char w[]); bool compare_words(char w1[], char w2[]); void main () char word1[81], word2[81]; int word_length1, word_length2; cout << "Enter word 1 (max 80 chars): "; cin >> word; cout << "Enter word 2 (max 80 chars): "; cin >> word; word_length1 = calc_length(word1); word_length2 = calc_length(word2); cout << "Length of word 1 is " << word_length1; cout << "Length of word 2 is " << word_length2; if (compare_words(word1, word2)) cout << "Words are the same"; else cout << "Words are not the same ; cout << endl; int calc_length(char w[]) int len; // continue looping until we bump into the null char for (len = 0; w[len]!= '\0'; len++); return len; bool compare_words(char w1[], char w2[]) int i; // continue looping as long as chars are equal and not null for (i = 0; w1[i]!= '\0' && w2[i]!= '\0' && w1[i] == w2[i]; i++); // the only way that identical words can end the loop is // by both having a null char at the same time: any other // combination means that they are not identical return (w1[i] == '\0' && w2[i] == '\0');