LEC03_Notes - 1 14:440:127– Introduction to Computers for...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1 14:440:127– Introduction to Computers for Engineers Notes for Lecture 03 Rutgers University, Spring 2011 1 Instructor - Brenda V. Cortez Introduction In these lecture notes, you will learn about the built-in math functions that you can use in your code to calculate things like the absolute value or the square root of a value. Following this topic, we will reconsider the previously mentioned example of the Professor who wants to know the average of the scores in his/her class. It seems more plausible that the Professor would want to access the individual student’s score after it has been entered; perhaps to compare it to the average. However, we currently do not have the tools to store individual values as a set, for later consideration. To solve this problem, we will introduce and implement arrays. Later in the semester, when we move on to MatLab scripting, it will become more evident why learning arrays now is so important - an array is the main data type in MatLab! After thoroughly reading and doing the exercises in these lecture notes, you should not only be familiar with the concept of arrays, but you should also be able to work with strings and other header files that provide further functionality to a program. 2 C++ Standard Library Header Files & Built-in Functions You already know that if you want to use the C++ standard input and output functions, you must include the <iostream> header file in your program; but this is not the only header file available for use. For instance, we can also include <cmath>, which contains function prototypes for typical mathematical operations such as the exponent xy , pow(x,y), or the trigonometric sine of x, sin(x). When using the <cmath> header file, include it in your code, right after <iostream>. Consider the following example illustrating the mathematical functions you have available for use: Example 1: #include <iostream> #include <cmath> using namespace std; int main(){ int x = 45, y = 25, z = 2; float v = -3.5, u = 1.5; // ceil(): Ceiling, always rounds up 2 cout << "Ceiling u = " << u << " rounds it up to " << ceil(u) << endl; cout << "Ceiling v = " << v << " rounds it up to " << ceil(v) << endl; // floor(): Floor, always rounds down cout << "Flooring u = " << u << " floors it down to " << floor(u) << endl; cout << "Flooring v = " << v << " floors it down to " << floor(v) << endl; // to calculate the cosine of x (radians) cout << "The cosine of x = " << x << " radians is " << cos(x) << endl; // to calculate the sine of x (radians) cout << "The sine of x = " << x << " radians is " << sin(x) << endl; // to calculate the tangent of x (radians) cout << "The tangent of x = " << x << " radians is " << tan(x) << endl; // to calculate exponential e to the power of variable cout << "e^"<< z << " = "<< exp(z) << endl; // to take square root of a positive number cout << "The square root of y = " << y << " is " << sqrt(y) << endl; // to calculate absolute value of variable cout << "The absolute value of v = " << v << " is " << fabs(v) << endl; // to calculate the natural logarithm of x (base e) cout << "The natural log of u = " << u << " is " << log(u) << endl; // to calculate the logarithm of x (base 10) cout << "The base 10 logarithm of x = " << x << " is " << log10(x) << endl; return 0; } You should definitely write/compile/run this code, so that you can become familiar with using the mentioned mathematical functions, that in this case would render the following output: Ceiling u = 1.5 rounds it up to 2 Ceiling v = -3.5 rounds it up to -3 Flooring u = 1.5 floors it down to 1 Flooring v = -3.5 floors it down to -4 The cosine of x = 45 radians is 0.525322 The sine of x = 45 radians is 0.850904 The tangent of x = 45 radians is 1.61978 e^2 = 7.38906 The square root of y = 25 is 5 The absolute value of v = -3.5 is 3.5 The natural log of u = 1.5 is 0.405465 The base 10 logarithm of x = 45 is 1.65321 Exercise 1: Write a program containing a main function and one other function. Your main function should prompt the user to enter an integer and should output to the screen the square root of that number. The square root calculation should be done within a second function called mySqrt, which you will write, and which will take an int as a parameter, and return the square root of that value to the main function for display to the user. 3 3 Strings When it comes to creating strings, there are two methods that you should become familiar with. The first is to create a variable of type string, and the second is to use an array of characters (char). We will first look at the use of the string object, and then move to the topic of arrays, in which the character array will be included. 3.1 String Object The first thing on your mind should be: Why can’t I just use a char variable to store a whole word with multiple characters? The answer is that char can only store one character at a time. As stated earlier, there are two ways to solve this limitation, so let’s first look at using the string object. You can think of a string as being just another data type, like int or float. In order to create these string variables, you have to include the <string> header file. A string is a class in the C++ Standard Library and belongs to namespace std, just as the io operations do. Using a string variable allows you to save strings of characters like the name “Julia”, or the name of this course, “Intro. to Computers for Engineers”. Consider the following example: Example 2: #include <iostream> // MUST include <string> #include <string> using namespace std; int main(){ string name; cout << "Enter your full name: "; // The following will not work cin >> name; cout << "Your name is: " << name << endl; return 0; } If you run this code, you will see the following output: Enter your full name: Brenda Cortez Your name is: Brenda There is problem! The last name did not print. Well, in reality it is not a problem because this is actually how cin works. What is happening is that cin, along with the extraction operator (>>), reads in the input until the first white space is encountered (between the first and last name). So when you enter your full name, separating the first name from the last name with a space, cin will only read in your first name and skip your last name, as shown above, when the value in name is printed to the screen and only the first name appears. In order to avoid this problem, we need to use the getline function. 4 See the modified version of the Example 2 below: Example 3: #include <iostream> #include <string> using namespace std; int main(){ string name; cout << "Enter your full name: "; // The following statement is new getline(cin, name); cout << "Your name is: " << name << endl; return 0; } Notice the difference in the code. The function getline is used to read in the input until the end of the line (signified by a newline character ). The function getline ignores the newline character, so it will not be stored in name and will not be printed to the screen. Following is a sample of what you would see if you ran the code above: Enter your full name: Brenda Cortez Your name is: Brenda Cortez Now, this is much better! You can now compare it to another string using the equality operator (==), and perform some task based on whether or not the two strings are the identical. For instance, suppose you want write a program that will check to see if the user’s name, which they will input, is identical to my name. If it is, the program tells the user that she is the instructor, otherwise it assumes the user is a student and reminds the student of this. The following code does just that: Example 4: #include <iostream> #include <string> using namespace std; int main(){ // declare the string object, "name" string name; cout << "Enter your full name: "; // read in the name using getline getline(cin, name); cout << "Your name is: " << name << endl; 5 if (name == "Brenda Cortez") // If condition is TRUE cout << "You are the instructor.!\n"; // The user is the instructor else // Otherwise, if condition is FALSE cout << "You are a student.\n"; // The user is a student return 0; } Exercise 2: Modify the code from Example 3 so that the user is prompted to enter age and major. Then print to the screen the message “Your name is ... , you are ... years old and studying ... at Rutgers University.” Use the values entered in place of the “...”. 4 Arrays An array is a group of consecutive elements of the same data type, which can be accessed by indexing the elements in the group. Remember when you had to create a char variable to store each letter in your name, and then asked to print each character consecutively to the screen to appear in a single line? Well, this is exactly what can be accomplish with a character array. Consider the following illustration of an array: In this illustration, each cell of the array is represented by a simple box. These boxes are what will hold any given value. This array has 10 cells, so it can store up to 10 elements. Each cell has an index that can later be used to access the value in that particular cell. Note that in C++ as well as most other languages (except MatLab, as we will see later in the course), we start counting with 0, not 1. Example array of integers: Value : 8 8 9 7 8 3 Indices: 0 1 2 3 4 5 6 4.0.1 Declaring & Initializing 1-D Arrays In order to declare array variables, you use square brackets, [ ]. The format is the following: data_type array_identifier[number_of_elements]; int numbers[6]; // Declares an array of 6 integers with the array name "numbers" If you want to assign values explicitly, enclose those values in curly braces, { }, after the assignment operator (=), separated by commas and followed by a semicolon (;). int number[6] = {8,8,9,7,8,3}; Otherwise, you can assign values implicitly later in the program: numbers[0] = 8; // Set the first cell to 8 numbers[1] = 8; // Set the second cell to 8 If you do not initialize an array of numbers with any particular values, it is automatically assigned zeros to all of its elements, as shown below. Example 5: #include <iostream> using namespace std; int main(){ int numbers[5]; cout << numbers[2] << endl; return 0; } The output of this code will be: 0 Exercise 3: Create 2 arrays of type float that will store 3 elements each. Assign values explicitly to the first array and implicitly to the second array. Access each element in each array, one by one, and print it to the screen. 7 4.0.2 Accessing 1-D Array Elements Example 5 demonstrated how you would access the third (2) element in array numbers. When you want to access the value at a particular index, you must use the index value of the element of interest. For instance, if we want to know the value at index 3, you would access it with numbers[4]. Remember that the first index is 0, so index 3 is the fourth element in the array. Consider the following example: Example 6: #include <iostream> using namespace std; int main(){ // declare array of elements of type int int numArray[6] = {8,8,9,7,8,3}; // Access elements using loop, k represents the index of the array elements for(int k = 0; k < 6; k++) { cout << numArray[k] << endl; } return 0; } Explanation of code: 1. The for loop will iterate 6 times, form 0 to 5, since 5 < 6 2. On first loop iteration, k=0 numArray[0] = 8 8 is printed to the screen along with a newline character k is incremented by 1 3. On second loop iteration, k=1 numArray[1] = 8 8 is printed to the screen along with a newline character k is incremented by 1 4. On third loop iteration, k=2 numArray[2] = 9 9 is printed to the screen along with a newline character k is incremented by 1 5. The same process if followed until k = 5 On the sixth loop iteration, k=5 numArray[5] = 3, the sixth and last element in the array 3 is printed to the screen along with a newline character loop finishes iterating 8 Exercise 4: Re-write the code in Example 6 using a while-loop instead of the for-loop. Exercise 5: Using the loop in Example 6 as a guide, modify your code in Exercise 3, such that you use a loop to access and print the elements in the two arrays, instead of doing so one by one. 9 4.1 Character Array A string is simply a sequence of characters, and can therefore be represent with an array of characters. So let’s consider character arrays, which can be handled in the same way as the integer array seen before. 4.1.1 Declaring Character Arrays Examine the following declaration of an array called name of type char: char name[7]; Illustration of what this means: char name[7] Indices: 0123456 The value inside the [ ] represents the number of characters this array will be able to store. You must include this when defining your arrays, so if you think that a person’s name will be 15 letters long, then define the array size to be a number slightly larger than what the user might enter. In future C++ courses you will learn about dynamic memory allocation, but for now just keep in mind that you must include the size of the arrays in your declarations. An array of size 15 will be able to store up to 15 characters, and therefore can store shorter strings. In the case of name, we can store up to 7 letters, but because we can store less than 7 letters, we have to have some way of indicating the end of the valid sequence of characters. For instance, suppose we stored the name “Lee” in name: char name[7] L e e Indices: 0 1 2 \0 3 456 The last character you see in the sequence of characters is the null character sequence, denoted by a backslash and a zero, \0. This null characters defines the end of a valid sequence that ignores all other elements in the array which are left undefined - garbage data will be in those elements. It also takes up its own element space and is automatically part of a sequence of characters, such that you don’t have to worry about getting rid of it. For instance, if you wanted to print the array name to the screen, you would do so as follows: Example 7: #include <iostream> using namespace std; int main(){ char name[7] = "Lee"; cout << "Your name is " << name << endl; return 0;} 10 The output would be: Your name is Lee Notice how you didn’t have to tell the program to ignore the null character, since it is simply a flag denoting the end of valid characters - in this case the end of the name “Lee”. NOTE: Because of the null character, you must always make your character arrays 1 element larger than the strings which you would like to store in them. 4.1.2 Accessing Character Arrays If you wanted to print a particular letter in the name “Lee”, you again use the index of the letter. Example 8: #include <iostream> using namespace std; int main(){ char name[7] cout << "The cout << "The cout << "The return 0; } = "Lee"; first letter is: " << name[0] << endl; second letter is: " << name[1] << endl; last letter is: " << name[2] << endl; Exercise 6: Draw an array diagram as those shown above for an array that would store your first and last name. Include the indices of each element. Exercise 7: Now write a program with an array containing your name that prints the last letter in your first and last name to the screen on separate lines. 11 Now let’s consider a situation where you ask the user to enter their name, and the user enters “Lee”. Your program then compares this to a name that is stored in an array that is slightly larger in size, but has the same string stored in it. If the names match, then the program should give a message saying “Same”, otherwise nothing. Consider the following initial attempt of this code: Example 9: #include <iostream> using namespace std; int main(){ char name[7] = "Lee", myname[10] = "Lee"; cout << "Your name is " << name << endl; if(name == myname) cout << "Same" << endl; return 0; } When you write, compile and run this code, you will see that nothing happens after the message “Your name is Lee” is printed to the screen, which means that the if statement’s condition evaluated to false. You would think that because the content of the arrays is the same, the condition should evaluate to true, but when you work with arrays, even if they are the same size and have the same value, they will not be considered to be the same according to the equals operator (==). To avoid this, you instead have to compare the arrays element by element. See the following modified code: Example 10: #include <iostream> using namespace std; int main(){ // arrays with identical strings stored in them char name[7] = "Lee", myname[10] = "Lee"; cout << "Your name is " << name << endl; int index = 0; bool same = false; while (name[index] != ’\0’){ if(name[index] == myname[index]){ same = true; } // increment index so we can access the other elements index+=1; } 12 // since the loop stopped at ’\0’, and because "Lee" is not // the same as "Lee " we must check that the value at the // last index is in fact the null character if(name[index] != myname[index]){ same = false; } if (same == true) cout << "Same!" << endl; return 0; } After writing, compiling, and running this sample code, you will see that it does exactly what we want it to do. It checks each element in name against each element in myname while the value in name[index] is not the null character. As you read earlier, the null character defines the end of a valid string sequence, so we wouldn’t want to compare the garbage values stored in the latter elements of name to those in myname, not to mention that the two arrays are of different size as well. A while-loop becomes the best choice for doing this comparison, which also includes a nested if statement. Look at this if statement carefully. Notice how it takes the value at index in name and determines if it “is not equal to” the value in the same index in myname. If the if statement condition evaluates to true, then the boolean variable same is set to false. This boolean variable was initiated to true before the while-loop simply to represent a flag, which could then be changed if something changed - in this example, the change is that the characters being compared did not match. Depending on the application, you may want to use an array or a string object to store a sequence of characters, and you will just have to think about what is more suitable. In addition to this, you should remember that without an array or string object, we would not be able to store a word in a regular single char variable. Exercise 8: Write a program that asks the user to enter the name of a geometrical figure and using a for-loop check if it matches the word “triangle”. If it does, then send a message to the user saying: “Your entry matches ´riangle´ otherwise it should say, “Your entry doesn’t match t ’’, anything in the database.”. As an additional instruction, your program should be case sensitive, so that ‘T’ is not treated to be the same as ‘t’. 13 In upper lever courses that focus solely in C++, you will be required to learn pointers, which are essential to a full understanding of the language. However, since this class doesn’t introduce you to this concept, it is not necessary that you understand, why a char array is a pointer. However, since you just finished learning how to compare strings in a char array using a loop, it is fit to mention that there is a function to do this. When working with char arrays, if you want to compare two strings, you can use the function strcmp. This function’s format is: strcmp(str1, str2), which compares str1 to str2. If str1 is equal to str2, this function returns a zero. If the strings in the arrays don’t match, but the character being compared in str1 comes after that in str2, then the function will return a negative number. Otherwise, if the strings don’t match, but the character being compared in str1 comes before that in str2, then the function will return a positive number. Note: some compilers simply return 0, -1, or 1, respectively. Consider the following example: #include <iostream> #include <cstring> using namespace std; int main(){ char name = "Brenda"; char myname = "Brenda"; cout << strcmp(name, myname) << endl; return 0; } Notice that you have to include the <cstring> header file in order to be able to use strcmp. A sample run of this code would render the following output: 0 Note what happens when the code is modified as follows: char myname = "Arenda"; Output: 1 Because alphabetically, A comes before B. Now consider the following modification: char myname = "Crenda"; Output: -1 Because alphabetically, C comes after B. 14 4.1.3 Character Handling To lay down the usefulness of char arrays, we will examine a program that prompts the user for a number. The initial program will not validate the input. In a later version, we will validate the input. The validation itself will not fix the initial problems, but we will eventually reach a solution that is widely implemented. With this in mind, let’s start by examining the following example: Example 11: #include <iostream> using namespace std; int main(){ int num; cout << "Enter a number: "; cin >> num; cout << num << endl; return 0; } If you compile and run this code, and enter a character, you would get something like following output: Enter a number: f 32767 This program is obviously incorrect, as it did not handle the input with an error. One way to solve this problem is to use a char data type variable instead of an int data type variable. When using char data type variables you can include the <cctype> header file, and use some of its functions to check if the input from the user is a letter or a digit (one digit number) as follows: Example 12: #include <iostream> #include <cctype> using namespace std; int main(){ char num; cout << "Enter a number: "; cin >> num; if(isdigit(num)) { cout << "You entered a number.\n"; cout << num << endl; } else { cout << "You entered a character.\n"; 15 } return 0; } Here is sample run: Enter a number: f You entered a character. Our program can now make a distinction between an input that is a digit or a letter. However, try re-running the program and enter an integer that is two or more digits long. What happens? Here is a sample of what you should see: Enter a number: 23 You entered a number. 2 Can you see what the problem is? Since a variable of type char can only store one character at a time, then num can only store 2 and not 23. So how can we fix this? Well, we make use of an array! Let’s modify the code in Example 12 to reflect the changes just mentioned: Example 13: #include <iostream> #include <cctype> using namespace std; int main() { char num[8]; bool isInt = false; cout << "Enter a number: "; cin >> num; int k=0; while(num[k] != ‘\0’) { if(isdigit(num[k])) { isInt = true; } else { // if element at position k is not an int, break out of the for-loop isInt = false; break; } k++; } if(isInt == true) { 16 cout << "You entered a number.\n"; cout << num << endl; } else { cout << "You entered one or more letters.\n"; } return 0; } Consider the following explanation of this code: 1. Array variable num of type char was declared and initialized to allocate space for 8 elements - the 8 is arbitrary 2. The user’s input is stored in num 3. Using a while-loop, we can traverse (travel) through all the elements in num, since num is a char type array and we can use the null-sequence to determine the end of the valid sequence 4. Inside the while-loop there is an if/else statement that determines if the element k in num is a digit by using the isdigit function included in the header file <cctype> 5. If this condition evaluates to true, the boolean variable isInt is set to true 6. As soon as the condition is no longer true, the boolean variable isInt is set to false and the loops breaks Up to now, it seems that everything is working out well, but remember that the program asks the user enter a number, so edit the code in Example 13 to print the the input number squared. What happens? If you edit your code to include the following line of code: cout << (num*num) << endl; and you try to compile the program, you will get the following error: In function ‘int main()’: error: invalid operands of types char [8] and char [8] to binary operator* Why does this happen? To find out, we can do a data-type check: • "23" * "23" is char * char, which cannot be done! • The error tells you that you cannot perform a multiplication (*, or operator*), i.e. “invalid operands of types char [8] and char [8] to binary operator*” So how could this be fixed? We have two char arrays and cannot multiply their contents. We can fix this by converting the characters to integers. This can be accomplished by including the <cstdlib> header file. This header file will allow us to use the function atoi, which will convert a letter (ascii) to an integer. Let’s see how it would be applied to the program in Example 13. You would simply have to pass the variable to the function atoi that you want to convert; in this case: atoi(num), and this is how the program would look overall: 17 Example 14: #include <iostream> // Include in order to use isdigit #include <cctype> // Include to be able to use atoi #include <cstdlib> using namespace std; int main() { char num[8]; bool isInt = false; cout << "Enter a number: "; cin >> num; int k=0; while(num[k] != ‘\0’) { if(isdigit(num[k])) { isInt = true; } else { // if element at k position is not an int, break out of for-loop isInt = false; break; } k++; } if(isInt == true) { cout << "You entered a number.\n"; cout << num << endl; // Output product // Convert char array to integer first cout << (atoi(num) * atoi(num)) << endl; } else { cout << "You entered one or more letters.\n"; } return 0; } Sample output: Enter a number: 23 You entered a number. 23 529 18 or, with wrong input: Enter a number: 3e You entered one or more letters. Following are two tables with some other useful functions included in the <cctype> or <cstdlib> header files. Table 1: <cctype> Function isalpha isupper islower tolower toupper Example Description isalpha(variable) Returns true if variable is a letter and false if not. isupper(variable) Returns true if variable is uppercase and false if not. islower(variable) Returns true if variable is lowercase and false if not. tolower(variable) Returns uppercase variable in lowercase form, otherwise returns variable unchanged. toupper(variable) Returns lowercase variable in uppercase form, otherwise returns variable unchanged. Table 2: <cstdlib> Function Example Description atof atof(num) Converts string num to float Exercise 9: Write a program that prompts the user to enter 2 integer numbers. Save these numbers into char arrays and validate them (i.e. make sure they are integers), then return the sum of the two inputs. 19 Exercise 10: Write a program that prompts the user to enter 2 integer numbers greater than zero. Save these numbers into char arrays and validate them (i.e. make sure they are integers & greater than zero), then return the result of calculation xy , where x is the first input and y is the second input from the user. 20 4.2 Integer Array The idea for an integer array is the same as that of a character array. To define an array of a different data type, such as int, you can do the following: int array1[5]; Consider the following code. What do you expect the for-loops to do? Example 15: #include <iostream> using namespace std; // global variable int globalVariable[6]; // file-scoped variable static int staticVariable[4]; int main(){ // local array variable int localVariable[2]; // print static array variable values for(int j=0; j < 2; j++) { cout << "The " << j << "-th local array value = " << localVariable[j]; cout << endl; } cout << endl; // print line to sparate output // print static variable values for(int k=0; k < 4; k++) { cout << "The " << k << "-th static array value = " << staticVariable[k]; cout << endl; } cout << endl; // print line to separate output // print global array variable values for(int i=0; i < 6; i++) { cout << "The " << i << "-th global array value = " << globalVariable[i]; cout << endl; } return 0; } The code above declares three arrays, a local, global, and a static variable. As you can see, these three arrays were not assigned any values, but they are automatically assigned zeros by default. 21 You can verify this by writing/compiling/running Example 15, which will give you the following output: The 0-th local array value = 0 The 1-th local array value = 0 The The The The 0-th 1-th 2-th 3-th static static static static array array array array value value value value = = = = 0 0 0 0 The The The The The The 0-th 1-th 2-th 3-th 4-th 5-th global global global global global global array array array array array array value value value value value value = = = = = = 0 0 0 0 0 0 Notice that you cannot simply print arrays and expect to see their values: cout << localVariable << endl; cout << staticVariable << endl; cout << globalVariable << endl; If you try this, you will get some memory addresses instead: 0xbffff88c 0x2050 0x2034 Let’s look into the code of Example 15 more carefully. The declaration int localVariable[2]; tells the compiler to allocate space for 2 int values. Even though an array declared in this manner will be initialized to zero by default, you can also assign values to the array implicitly or explicitly. The following is an explicit initialization: int localVariable[2] = {3, 5}; Be careful to not forget the commas (,) that separate the elements that we assign to the array - it will cause an error if you do. Another way to declare this same array is: int localVariable = {3, 5}; This will automatically create the array with the correct size to hold all of the values. However, there may be times when you want to assign values to each element in an array later on in the program. For instance, let’s suppose you wanted to assign the sqrt(n) to each element, where n is the element’s index. Take a look at the code below where an array of type float is created, and memory is allocated for it to hold 5 elements. 22 Example 16: #include <iostream> // Include <cmath> to be able to use sqrt #include <cmath> using namespace std; int main() { float array1[5]; for (int t = 0; t < 5; t++) { array1[t] = sqrt(t); cout << "The " << t << "-th element in array1 = " << array1[t] << endl; } return 0; } The array array1 now stores the square roots of each of its elements’ indices. Since they were being printed to the screen on each iteration, the output is: The The The The The 0-th 1-th 2-th 3-th 4-th element element element element element in in in in in array1 array1 array1 array1 array1 = = = = = 0 1 1.41421 1.73205 2 Exercise 11: What is/are the errors in the following code? Fix them, if there are any, compile/run it and see that the output would be. int a[5]; for{int k = 0; k <= 5; k++}{ a[k] = k*(k+1) } Exercise 12: Write a program the assigns 2+k, where k is the index of the element, to each element in an array with space to for 5 elements. Use a for-loop to traverse the array and make the assignments. For instance, the first element in the array should be assigned 2 + k = 2 + 0 = 2. 23 4.3 Multidimensional Arrays Now that you have seen how 1-D arrays are created and accessed for manipulation, we can expand this idea to multidimensional arrays, which are simply arrays with more than one dimension. For this class, you are only required to know how to create and manipulate 1-D (previously addressed in the character and integer array sections) and 2-D arrays, which will be demonstrated in this section. However, 3-D and N-D arrays are beyond the scope of this C++ introduction, but you should know that the concept is the same and you should be able to see how the idea can be extended to other multidimensional arrays. These notes only cover 1-D and 2-D arrays. 4.3.1 Declaring 2-D Arrays Following is a declaration of a 2-D integer array: int array2[2][5]; This array declaration tells us that array2 has 2 rows and 5 columns. int array[2][5] Row indices: [0][1] [0][2] [0][3] [0][4] [0][5] [1][1] [1][2] [1][3] [1][4] [1][5] 0 1 Column indices : 0 1 2 3 4 Just as before, you can assign values to the array explicitly or implicitly. 4.3.2 Assigning Values to 2-D Arrays You can assign values to an array explicitly : int array2d[2][2] = {{2,4},{6,8}}; In this case array2d is a 2 X 2 array (read two by two ), meaning that it is 2-rows by 2-columns in size. In addition to this, you should be aware that the following declaration and initialization is equivalent: int array2d = {{2,4},{6,8}}; Or, as was the case for 1-D arrays, you can also assign the 2-D arrays values implicitly using a loop, as you saw earlier for 1-D arrays and will see later on for 2-D arrays. 4.3.3 Accessing Values in 2-D Arrays In order to access and manipulate each element in array2d, you need to use the element’s indices (row,column) or for-loops. Given the implicitly declared array array2d, let’s see how its elements could be accessed. int array2d[2][2] Row indices: Column indices : 0 1 2 6 4 8 0 1 If you wanted to access the value 2 and print it to the screen, you would do it as follows: 24 cout << array2d[0][0] << endl; or the value 8: cout << array2d[1][1] << endl; Notice that you are basically saying, what is the value at array Name[row Num][col Num]. There will be times when your arrays will have more elements than you care to access one at a time, and when this is the case, you may want to use loops. When working with 2-D array, you will need to nest a for-loop inside another for-loop - nested for-loop. One loop will help you traverse through the rows and the other through the columns. A sample format of this structure is: // OUTTER LOOP TO TRAVERSE ROWS IN ARRAY for (int k = 0; k < NUM_ROWS; k++){ // INNER LOOP (NESTED) TO TRAVERSE COLUMNS IN ARRAY for (int t = 0; t < NUM_COLS; t++){ // what to do to each element? } } Let’s apply this structure to array2d and simply print each element to the screen: Example 17: #include <iostream> using namespace std; int main(){ int array2[2][2] = {{2,4},{6,8}}; for(int k = 0; k < 2; k++){ for (int t = 0; t < 2; t++){ cout << array2d[k][t] << endl; } } return 0; } The output of this code will be: 2 4 6 8 25 Well, what if you wanted to print this array to look like a matrix or table? Here is the modified code, using a tab escape sequence ("\t"): Example 18: #include <iostream> using namespace std; int main(){ int array2[2][2] = {{2,4},{6,8}}; for(int w = 0; w < 2; w++){ for (int v = 0; v < 2; v++){ cout << array2d[w][v] << "\t"; } cout << endl; } return 0; } The output will now look like: 2 6 4 8 You have now created and accessed individual elements in a 2-D array, when the array is declared and initialized explicitly. In order to initialize an array explicitly you will need to use a for loop. Let’s see how this would be done, if array2d was simply declared (int array2d[2][2];), but not initialized. The following code will initialize each element in array2d to 3. Example 19: #include <iostream> using namespace std; int main(){ int array2d[2][2]; // Outer loop will iterate through the ROWS for(int w = 0; w < 2; w++){ // Inner loop will iterate through the COLUMNS for (int v = 0; v < 2; v++){ array2d[w][v] = 3; } } return 0; } 26 If we wanted to print this array to the screen, formated to look like a matrix, you would make use of the tab scape sequence, to separate the elements, and include a new line after the each iteration of each row. Example 20: for(int w = 0; w < 2; w++){ for (int v = 0; v < 2; v++){ array2d[w][v] = 3; // print each element in array2d separate by a tab cout << array2d[w][v] << "\t"; } // after each ROW iteration, print out a new line cout << endl; } The output of this code is: 3 3 3 3 Exercise 13: Write a program that initializes the elements of a 2 by 3 array to the sqrt(col index) using loops. For instance, the value at location [1][2] should be the evaluation result of sqrt(2) because the column index is 2. 27 Exercise 14: Write a program that initializes the elements of a 3 by 3 array to colrow using loops. For instance, the value at location [1][2] should be the evaluation result of 21 , because the column is 2 and the row is 1. 4.4 Length of Array What if you want to know the length of an array? Consider the following example: Example 21: #include <iostream> using namespace std; int main(){ int numArray[6] = {8,8,9,7,8,3}; // What is the legth of numArray? // We know it is 6, but we can write the code to do this for us cout << sizeof(numArray)/sizeof(int) << endl; return 0; } The output will be: 6 Notice how we used the function sizeof, which will tell us how many bytes numArray is in size. Then knowing how many bytes it is, we can divide by the number of bytes it takes to save an int, since the array is of int type. 28 Exercise 15: Create a program containing a 1-D float array with whatever amount of values you want. Then use the sizeof function to determine its length and use this value in a loop to assign 3 to all the elements in the array. Print the array to the screen Exercise 16: Create a program containing a 1-D char array with whatever amount of values you want. Then use the sizeof function to determine its length and use this value in a loop to assign an a to all the elements in the array. Print the array to the screen ...
View Full Document

Ask a homework question - tutors are online