1 / 36

Introduction to Computer Science

Introduction to Computer Science. COMP 51 – Fall 2012 – Section 2. Arrays. Arrays. Motivation for Arrays. Projects and labs to-date have worked with small amounts of data Ex: Write a function to find the smaller (or larger) of two integers

Download Presentation

Introduction to Computer Science

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Arrays

  2. Arrays

  3. Motivation for Arrays • Projects and labs to-date have worked with small amounts of data • Ex: Write a function to find the smaller (or larger) of two integers • Suppose we need to work with a large amount of data? • Ex: Write a function to find the smallest (or largest) value of a set of 1000 integers

  4. Motivation for Arrays • Do you need to declare individual variables? • int num1, num2, num3, num4, … • Do you need to save data to each variable individually? • cin >> num1 >> num2 >> num3 >> num4 … • Do you need to pass a huge list of arguments to your function? • result = min(num1, num2, num3, …); • Does your function need to have a huge number of if-statements to compare all these variables?

  5. Arrays • Fortunately, no! • High-level languages (include C++) utilize a concept called arrays • An array is a single variable that can hold multiple items of the same type • So, in the previous example, you can use a single variable that holds 1000 integers

  6. Array Items • Refer to each item in the array variable by a number • Subscript or index number • The items are numbered starting with 0 Array (variable name): numbersToProcess 4 3 1 0 2

  7. Array Syntax • How do I declare arrays? • int myArray[100]; • Declares an new array • Name: myArray • Type: Integers • Maximum number of elements in array: 100 • Numbered 0-99 • Must declare an array before using it • Just like other variables and functions

  8. Array Syntax • How do I access individual items in an array? • Example using element 16 of array “myArray” • myArray[15] • Print it out: • cout << myArray[15]; • Use it in a calculation: • sum = myArray[15] + 32; • Use it in a function call: • myFunction(myArray[15]); • Why did we use [15] when we wanted the 16th element?

  9. Array Syntax • The index number can be an expression • These produce identical resultsBoth access element number 15 in the array • cout << myArray[15]; • int n = 8;cout << myArray[n+7]; • This makes it easy to access all the items in an array using a for or while statement

  10. Example • Read in 1000 integers, and print them out in reverse order int values[1000]; for(inti=0; i<1000; i++) { cin >> values[i]; } for(inti=999; i>=0; i--) { cout << values[i] << endl; }

  11. Pitfall – Arrays start at Zero, not One! • Take an array of 100 items • int myArray[100]; • The first array index is ZERO • myArray[0] • The last array index is 99 • myArray[99] • Array indexes run from 0 to <ArraySize> - 1 • Attempting to access myArray[100] will cause problems!

  12. Arrays in Memory Address Value • Think of memory as a very large table where we can store data • Each element in the table is numbered consecutively • This number is called the address • If you’ve used a spreadsheet application, it’s similar to the rows or columns

  13. Arrays in Memory Address Value • Let’s declare some integer variables • int var1 = 15;int var2 = 8421; var1 var2

  14. Arrays in Memory Address Value • Now let’s declare an array and another variable • int myArray[5];int var3 = 19; var1 var2 myArray[0] myArray[1] myArray[2] myArray[3] myArray[4] var3

  15. Arrays in Memory Address Value • Now let’s set some valuesmyArray[3] = 1745;myArray[1] = 1527;myArray[2] = 1621;myArray[4] = 1893;myArray[0] = 1441; • Once the array is defined, we can access the items in any order var1 var2 myArray[0] myArray[1] myArray[2] myArray[3] myArray[4]

  16. Pitfall – Array Out-of-Bounds Address Value • What happens if I attempt to write a value outside of the array range? • myArray[5] = 1921; • I overwrite the contents of var3! (which happened to come next in memory) var1 var2 myArray[0] myArray[1] myArray[2] myArray[3] myArray[4] Bad!!

  17. Pitfall – Array Out-of-Bounds Address Value • What happens if I attempt to read a value outside of the array range? • value=myArray[5]; • I don’t get an error • Instead, I get the contents of var3! (which happened to come next in memory) var1 var2 myArray[0] myArray[1] myArray[2] myArray[3] myArray[4] Bad!!

  18. Array Initialization • We can declare and initialize variables at the same time • intmyVar = 15; • We can also declare and initialize arrays at the same time • int myArray[5] = {1,2,3,4,5}; equivalent to • int myArray[5];myArray[0] = 1;myArray[1] = 2;myArray[2] = 3;myArray[3] = 4;myArray[4] = 5;

  19. Array Initialization Tips • You don’t have to specify the max size of the array when initializing it • intmyArray[] = {10, 15, 20, 25, 30, 35, 40}; • Empty brackets tells the compiler to automatically create an array big enough to hold the initialized values • In this case, 7 elements • But you can’t later try to change the size of the array; if it’s supposed to be bigger, you must either declare it as such, or add “dummy” initializers

  20. Setting Array Size • You could just use a literal number • int myArray[20]; • But, a better way to do it is to declare a constant variable first • const int ARRAY_SIZE=20;intmyArray[ARRAY_SIZE]; • Now we can use the identifier to make the code easier to understand (and avoid bugs)! • for(inti=0; i<ARRAY_SIZE; i++) • All-caps name is programmer convention for constants

  21. Pitfall – Array Size • Array size must be known to the compiler at compile-time • You cannot do this: • int size;cin >> size;intmyArray[size]; • There is a way to accomplish this concept that you’ll learn later (dynamic allocation), but it requires a different way to create the array

  22. Pitfall – Copying Array • It’s reasonable to need to copy an array • const int ARRAY_SIZE = 10;int array1[ARRAY_SIZE] = {…};int array2[ARRAY_SIZE];array2 = array1; • This does not work! • Compiler should produce an error here

  23. Copying Array • The correct way to copy an array • const int ARRAY_SIZE = 10;int array1[ARRAY_SIZE] = {…};int array2[ARRAY_SIZE];for(inti=0; i<ARRAY_SIZE; i++){ array2[i] = array1[i];} • Must copy array element-by-element

  24. Pitfall – Outputting Array • Likewise, you may want to output an array • const int ARRAY_SIZE = 10;int array1[ARRAY_SIZE] = {…};cout << array1; • This does not work! • Program will instead print out the memory address of the first item in array1

  25. Outputting Array • The correct way to output an array • const int ARRAY_SIZE = 10;int array1[ARRAY_SIZE] = {…};for(inti=0; i<ARRAY_SIZE; i++){cout << array1[i] << endl;} • Must also output array element-by-element

  26. Arrays Elements in Function Calls • You can use individual array elements in functions calls • Pass-by-value and pass-by-reference both work • Example function: • calculateSomething(double var1); • Takes a double as an argument • Example array: • double myArray[10]; • Example function calls: • calculateSomething(myArray[3]); • calculateSomething(myArray[i]); • As long as i evaluates to an int between 0 and 9

  27. Whole Arrays in Function Calls • You can also use an entire array in your function call • This works using pass-by-reference • If you modify the array inside the function, the original array (outside of the function) is actually modified • There is only one copy of the data storage element (the array), with two labels… • Don’t need to use the & symbol • Arrays are always pass-by-reference • You cannot do pass-by-value for an entire array, only for one element of the array

  28. Whole Arrays in Function Calls // This function will read in <size> integers // and save them in <array> void populateArray(int array[], int size) { cout << “Enter ” << size << “ integers:” << endl; for(inti=0; i<size; i++) { cin >> array[i]; } } int main() { const int NUMBER_OF_GRADES = 25; intgrades[NUMBER_OF_GRADES]; populateArray(grades, NUMBER_OF_GRADES); } Empty brackets so we can accept arrays of any size No square bracket or index – we want the entire array

  29. Arrays as Function Return Values • Functions cannot return an array • They can only return single values • One int, one double, one char, … • We’ll learn a different way to accomplish this idea later (by using pointers…)

  30. Summary of Arrays and Functions • Individual array elements (indexed variables) can be passed as arguments to a function • Pass-by reference or pass-by-value • An entire array may be passed as arguments • Essentially pass-by-reference only • Do not need the & symbol • Array size is not known by the function • Usually need to pass it as an argument to • Nice benefit: the same function can be used for different sized arrays!

  31. Special Preview! Strings

  32. Declaring Strings • String library • Add a new type of data: Many characters in a row • Works similar to built-in data types like int, char, and double • Include the library: • #include <string>using namespace std; • Declare a new string variable and initialize • string mystring1 = “AMD”;

  33. Strings – Basic Operators • Some of the basic operators work with strings too! • At least, the ones that make sense… • Use + to concatenate strings • Use = to assign strings • string str1=“Computer “;string str2=“Science“;string str3;str3 = str1+ str2; // Value is “Computer Science”

  34. String – Basic Operators • Use == or != to compare strings • Use coutto output values • string str1=“Orange”;string str2=“Apple“;if(str1 != str2)cout << str1 << “ is not equal to “ << str2; • Use cinto input values • string str1, str2;cin >> str1 >> str2; • Input finishes on whitespace! • “University of the Pacific” • str1 = “University” • str2 = “of”

  35. String – Member Functions • at(i) – Character at position n (count starts at 0) • Example: string str1=“Computer”;cout << str1.at(3); // Should print ‘p’ • And many more functions!

  36. Questions? ? ? ?

More Related