BITG 1113: Array (Part 2) LECTURE 9 1
LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of C-strings (character arrays) 2. Use C-string functions 3. Use array as function parameter. 4. Manipulate data in arrays using function. 2
THE CONCEPT OF STRINGS Strings are used often in programming. You have used string literals before. String literal : a sequence of characters enclosed in a set of double quotes ( ) Example : Hello There are two ways to process strings in C++. One way is to treat strings as arrays of characters. This is known as C-strings. The other way is to process strings using the string class. However this lecture introduces C-strings only. 3
The Concept of C-strings C-string: a sequence of characters stored in adjacent memory locations and terminated by a NULL character ( \0 ). A NULL character ( \0 ) specifies the end of the C-string. C-string Declaration and Initialization Array of characters is used to declare a C-string. The size of the C-string must be large enough to store the string literal and a NULL character ( \0 ). Example : char name[8]; name is a C-string and it could consists of 8 characters. The largest string literal that it can store has 7 characters. If you store a string literal of a shorter length, say 6 in name, then the first 7 elements of name are used and the last one is left unused. name Example : char name[8]= Aisyah ; [0] [1] [2] [3] [4] [5] [6] [7] A i s y a h \0 Unused element 4
More on C-string Declaration and Initialization We could also declare with initializing a C-string with values (without giving the size) by either of these two ways: char mystring[] = { H, e, l, l, o, \0 }; char mystring [] = Hello ; H e l l o \0 Either statements would allocate the same amount of memory. mystring is declared with a size of 6 characters (its size is determined by the length of its string literal plus a NULL character). In the second case, when using double quotes, NULL character is automatically appended. 5
Characters and C-strings To store a single character, we have two options: Character literal use single quote marks : a String literal use double quote marks : a Example: A is the character A. A is the C-string A, where A represents two characters, A and \0. 6
Summary of C-string declaration and initialization. The statement char name[16] = "John"; declares an array name of length 16 and stores "John" and a \0 in it. The statement char name[] = "John"; declares an array name of length 5 and stores "John" and a \0 in it. 7
C-string Initialization vs. Assignment A C-string can be initialized at the time of its creation. char month[10] = May ; //correct However, a C-string cannot later be assigned a value using the = operator; you must use the strcpy() function. char month[10]; month = May ; // wrong! strcpy(month, May ); //correct 8
C-string input cin operator shows that the compiler expects the user to type a one-word string from the keyboard. char name[31]; cin >> name; // Reads in characters until a // space,tab or new line is // encountered. cout << name; //Will print the string name If you want the user to type text that includes space, use cin.getline() or cin.get() function. Example : cin.getline(name, 31); //Stores the first 30 //characters from the text entered into name. //The last character in name is reserved for the null //character ('\0'). 9
String Functions strcat() strlwr() strupr() 10
String Functions There are many useful functions for manipulating string data such as comparing string, searching string, and determining the length of string. These functions are provided by the string handling library from the standard library. You must include the <cstring> header file when using functions from the string handling library. 11
String Function : strcpy() An array cannot be assigned to another using the = operator. strcpy() function - used to copy one string into another string. The syntax of the strcpy() function is: strcpy (s1, s2); This function takes two arguments: - s1: the destination string that you are trying to replace. - s2: the source (origin) of the string that you want to copy. 12
String Function : strcpy() Can be used : to replace an existing string or to initialize a string. Example : char carname1[20]; char carname2[20]= Honda City ; 1) strcpy(carname1, "Toyota Camry"); cout << "Car Name: " << carname1 ; Output : Car Name: Toyota Camry 2) strcpy(carname1, carname2); cout << "Car Name: " << carname1 ; Output : Car Name: Honda City 13
String Function : strncpy() strncpy() function works like the strcpy() Allows you to specify the number of characters that the compiler would copy from the source string. syntax: strncpy(s1, s2, intnumber); //s1:destination, s2:source The intnumber argument specifies the number of characters that will be copied from the source string. 14
String Function : strncpy() Example : char carname1[20]; char carname2[20]= Honda City ; 1)strncpy(carName1, Toyota Camry, 6); cout << carname1: << carname1 ; Output : carname1: Toyota 2)strncpy(carName1, carname2, 5); cout << carname1: << carname1 ; Output : carname2: Honda 15
String Comparison C-strings are compared character by character using the collating sequence of the system If we are using the ASCII character set "Air" < "Boat" "Air" < "An" "Bill" < "Billy" "Hello" < "hello" 16
String Function : strcmp() The strcmp() function compares two strings and returns an integer as a result of its comparison. The syntax is: strcmp(s1, s2); This function takes two strings, s1 and s2 and compares them. It returns a negative value : if s1 is less than s2 0 : if s1 and s2 are equal a positive value : if s1 is greater than s2 17
String Function : strcmp() Example : char faculty[10] = FTMK "; char input[10]; int i; cout<< Enter your faculty: ; cin>>input; i = strcmp(faculty, input); if(i == 0) { cout<< You are from FTMK ; } 18
String Function : strlen() strlen() function is used to find the number of characters of a string. Its syntax is: strlen(s1); The strlen() function takes one argument, which is the string you are considering. The function returns the number of characters of the string. 19
String Function : strlen() Example : char CarName [20]= Honda City ; int length; length = strlen(carname); cout << "Car Name: " << length; Output : Car Name: 10 20
21
String Function : strcat() If you have two strings, to append one to another, use the strcat() function. Its syntax is: strcat(s1, s2); The strcat() function takes two arguments : - The first string is referred to as the destination - The second argument, called the source string, is the string you want to add to the first string. 22
String Function : strcat() Example : char faculty[20] = FTMK ; char university[13] = UTeM, MELAKA ; strcat(faculty, university); cout << \n\nafter concatenating: << faculty << endl; Output: After concatenating: FTMK UTeM, MELAKA 23
String Function : strncat() strcat() function and considers all characters of the source string. The syntax is: strncat(s1, s2, intnumber); strncat() function allows you to specify the number of characters from the source string that you want to append to the destination string. This means that, if the source string has 12 characters, you can decide to append only a set number of its characters. 24
String Function : strncat() Example : char faculty[20] = FTMK ; char university[13] = UTeM, MELAKA ; strncat(faculty, university,4); cout << "\n\nafter concatenating: << faculty << endl; Output : After concatenating: FTMK UTeM 25
String Function : strlwr() strlwr() function is used to convert a string to lowercase. Its syntax is: strlwr(s); This function takes, as argument, the string that needs to be converted. During conversion, if a Latin character were in uppercase, it would be converted to lowercase. 26
String Function : strlwr() Example : char faculty1[10] = FTMK "; char faculty2[10]; strcpy(faculty2,strlwr(faculty1)); cout << faculty2; Output : ftmk 27
String Function : strupr() strupr() function is used to convert a string to uppercase. Its syntax is: strupr(s); Each lowercase character in the function s argument, S, would be converted to uppercase. Any character or symbol that is not in lowercase would not be changed. 28
String Function : strupr() Example : char faculty1[10] = ftmk "; strcpy(faculty2,strupr(faculty1)); cout << faculty2; Output : FTMK 29
Converting strings to other types The cstdlib (stdlib) library provides three useful functions for this purpose: atoi: converts string to int type. atol: converts string to long type. atof: converts string to float type. All of these functions admit one parameter and return a value of the requested type (int, long or float). Example: int x = atoi( 1234 ); double y = atof( 456.98 ); 30
ARRAYS AND FUNCTIONS Using function to process arrays in large program : 1) Passing a one-dimensional array to function By passing individual elements Same as passing any ordinary variable to a function By passing the whole array When we need the function to operate on the whole array 31
1- D array : Passing individual elements Passing individual element Array element must matches the function parameter type When as a value parameter, function cannot change the value of the element in the calling function E.g : a function, print_square receives an integer and prints its square, using an array, we can loop through the array and pass each element in turn to print_square 32
Passing individual element - Example 33
1- D array : Passing the whole array Passing the whole array When we use large arrays in functions, by passing each value we need an extra memory to do so E.g : if an array containing 20k elements were passed by value to a function, another 20k elements would have to be allocated in the function and each element would have to be copied from one array to another Instead of passing the whole array, C++ passes the address of the array 34
An array name is the address of the first element in the array Because of the name of array is in fact its address, passing an array name allows the called function to refer to the array back in the calling function Two rules associated with passing the whole array: The function must be called by passing only the name of the array In the function definition, the formal parameter must be an array type, the size of the array doesn t need to be specified. If provided, it is ignored by the compiler. A function can change the elements in array by passing the array name without the constant modifier 35
Passing the whole arrays for updating - Example 1 Array used in a function is a reference parameter The symbol & is not used when declaring an array as a formal parameter C++ does not allow functions to return a value of the type array 36
Passing the whole arrays for updating Example 2 #include <iostream> using namespace std; #define SIZE 7 void reverseorder(int [], int); // function prototype int main() { int numbers[size]={1,2,3,4,5,6,7}; reverseorder(numbers, SIZE); return 0; } // end main void reverseorder(int list[], int arraysize) { for (int i = arraysize-1; i >= 0; i--) cout << list[i] << "\t"; } // end reverseorder 37
Passing the whole array as constants : Example const : This means array x CANNOT change the content of array base 38
2 ) Passing a two-dimensional array to function Passing an individual element - Pass the individual element by indexing the array name with the row number and the column number Passing a row Pass the whole row by indexing the array name with only the row number Passing the whole array Use the array name as the actual parameter 39
2 D Array: Passing an individual element - Example #include <iostream> using namespace std; void print(int a); int main() { int i,j,ary1[4][3]={{1,2,3},{2,4,6},{3,6,9},{3,2,1}}; for(int i=0; i<4; i++) { for(int j=0; j<3; j++) print(ary1[i][j]); cout<<endl; } return 0; } void print(int a) { cout<<a<< \t ; } 40
2 D Array : Passing a row - Example 41
2 D Array : Passing the whole array Example 1 42
2 D Array : Passing the whole array - Example 2 #define NUMBER_OF_STUDENTS 5 // const int NUMBER_OF_STUDENTS=5; #define NUMBER_OF_QUESTIONS 10 // const int NUMBER_OF_QUESTIONS=10; void checkanswer(char[], char[][number_of_questions], int, int, int[]); // function prototype int main() { char key[number_of_questions] = {'C','C','B','A','D','B','A','B','C','D' }; char answer[number_of_students][number_of_questions]= { {'C','D','C','C','B','B','A','B','C','B'}, {'C','C','B','C','D','B','A','B','A','B'}, {'D','D','C','A','D','B','A','B','A','D'}, {'B','C','C','C','B','B','B','B','C','C'}, {'C','C','C','A','D','B','C','B','C','D'} }; int checked[number_of_students]; checkanswer(key, answer, NUMBER_OF_STUDENTS, NUMBER_OF_QUESTIONS, checked); // passing array numbers return 0; } // end main 43
cont. eg. 2 D Array : Passing the whole array void checkanswer(char key[], char answer[][number_of_questions], int numstud, int numques, int checked[]) { int i, j; // declaring index for (i = 0; i < numstud; i++) // initializing checked (zeros) checked [i] = 0; for (i = 0; i < numstud; i++) { for (j = 0; j < numques; j++) { if (answer[i][j] == key[j]) checked[i] += 1; } // inner for cout << "Student " << i << "'s marks : " << checked[i] << "/" << NUMBER_OF_QUESTIONS << "." << endl; } // end for } // end checkanswer - END - 44