Your SlideShare is downloading. ×
Lec 25 - arrays-strings
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

Lec 25 - arrays-strings

254
views

Published on


0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
254
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
16
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Arrays and Strings Lecture: 25 19.09.2012 1
  • 2. 2 Design ProblemConsider a program to calculate classaverage Why?? Why?? ?
  • 3. 3 Add to Design ProblemNow your client says, I need to ALSOcalculate and display “deviations” fromthe average Describe why this will or will NOT work Describe why this will or will NOT work
  • 4. 4 Possible SolutionsEnter in the scores again Use 100 separate variables » and cout and cin commandsRead (then re-read) from a file The real answer … Use arrays!!
  • 5. Simple vs Structured Data 5 Types Simple data type => data element contains a single valuex ::15 x 15 avg ::84.35 avg 84.35 ch ::‘A’ ch ‘A’ Structured data type => a data element contains a collection of data valuesscores :: 85 79 92 57 68 80 scores 85 79 92 57 68 80 name :: ‘C’ ‘L’ ‘Y’ ‘D’ ‘E’ name ‘C’ ‘L’ ‘Y’ ‘D’ ‘E’
  • 6. 6 Arrays Arrays are Structured Data Types They have a means of accessing individual components Values can be retrieved from and stored in the structurescores :: 85 79 92 57 68 80 scores 85 79 92 57 68 80 0 1 2 3 4 5 cout << scores[2]; cout << scores[2]; scores[0] = 100; scores[0] = 100;
  • 7. 7 One Dimensional ArrayStructured collection of components » All of the same typeStructure given a single nameIndividual elements accessed by indexindicating relative position in collectionType of elements stored in an array canbe “just about” anythingIndex of an array must be an integer
  • 8. 8Use of Array for Our ProblemStore elements in array as read inGo back and access for deviations Note declaration Note declaration
  • 9. 9 Declaring ArraysSyntax: Data_type Array_name [constant];Note declaration from our example Tells how many elements set aside Tells how many elements set aside
  • 10. 10 Declaring ArraysExample specifies an array…» each element is an integer» there is space for 100 elements» the are numbered 0 through 99 scores :: 85 79 92 57 68 80 ...... scores 85 79 92 57 68 80 0 1 2 3 4 5 98 99
  • 11. Accessing Individual 11 Components Use the name of the array Followed by an integer expression inside the square brackets [ ]scores :: 85 79 92 57 68 80 ...... scores 85 79 92 57 68 80 0 1 2 3 4 5 98 99Index can be: Index can be: max = scores[0]; max = scores[0];--constant constant for (x = 0; x < 100; x++) for (x = 0; x < 100; x++)--variable variable if (scores[x] > max) if (scores[x] > max)--expression expression max = scores[x]; max = scores[x];MUST be an integer MUST be an integer
  • 12. 12 Out of Bounds IndexWhat happens if … float float f_list [50]; f_list [50]; f_list [100] = 123.456; f_list [100] = 123.456;C++ does NOT check for index out ofrangePossible to walk off into “far reaches” ofmemory -- clobbers ... » other variable locations » .exe code » the operating system (??)
  • 13. Initializing Arrays in 13 Declarations Possible to declare the size & initialize int results [5] = {14, 6, 23, 8, 12 } Possible to omit size at declaration » Compiler figures out size of arrayfloat prices [ ] = { 2.41, 85.06, 19.95, 3.91 }
  • 14. 14 Arrays as ParametersThis is one task that CAN be done to theWHOLE arrayC++ always passes arrays by reference
  • 15. 15 Arrays as ParametersThe name of the array is a pointerconstantThe address of the array is passed tothe functionSize of thearray alsopassed tocontrol loop
  • 16. 16 Arrays as ParametersNote the empty brackets in parameterlist » A number can be placed here but it will be ignored
  • 17. 17 Multidimensional ArraysA collection of a fixed number of componentsarranged in two dimensions» All components are of the same typeThe syntax for declaring a two-dimensionalarray is:dataType arrayName[intexp1][intexp2];where intexp1 and intexp2 are expressionsyielding positive integer values.
  • 18. 18 Multidimensional ArraysThe two expressions intexp1 and intexp2 specifythe number of rows and the number of columns,respectively, in the arrayTwo-dimensional arrays are sometimes calledmatrices or tables
  • 19. 19 Multidimensional Arraysdouble sales[10][5];
  • 20. 20 Accessing Array ElementsThe syntax to access a component of a two-dimensional array is: arrayName[indexexp1][indexexp2]where indexexp1 and indexexp2 areexpressions yielding nonnegative integervaluesindexexp1 specifies the row position andindexexp2 specifies the column position
  • 21. 21 Accessing Array Elementssales[2][3] = 35.60; 35.60
  • 22. 22 2-DIM. Array InitializationLike one-dimensional arrays» Two-dimensional arrays can be initialized when they are declaredTo initialize a two-dimensional array when it isdeclared1. Elements of each row are enclosed within braces and separated by commas2. All rows are enclosed within braces3. For number arrays, if all components of a row are not specified, the unspecified components are initialized to zero
  • 23. 23 2-DIM. Array InitializationExample:int anArray[3][5] ={ { 1, 2, 3, 4, 5, }, // row 0 { 6, 7, 8, 9, 10, }, // row 1 { 11, 12, 13, 14, 15 } // row 2};
  • 24. 24 2-DIM. Array InitializationAccessing all of the elements of a two-dimensionalarray requires two loops: one for the row, and onefor the column.Since two-dimensional arrays are typically accessedrow by row, generally the row index is used as theouter loop.for (int nRow = 0; nRow < nNumRows; nRow++) for (int nCol = 0; nCol < nNumCols; nCol++) cout << anArray[nRow][nCol];
  • 25. 25 Multidimensional ArraysA collection of a fixed number of elements (calledcomponents) arranged in n dimensions (n >= 1)Also called an n-dimensional arrayGeneral syntax of declaring an n-dimensional array is:dataType arrayName[intExp1][intExp2]...[intExpn];where intExp1, intExp2, … are constantexpressions yielding positive integer valuesExample: 3-Dimensional array: int anArray[5][4][3];
  • 26. 26C-Strings or Character ArraysWe have learned that the elements ofan array can be just about anythingConsider an array whose elements areall characters » Called a C-String » Has a collection of special routines
  • 27. 27 C-Strings or Character ArraysCharacter array: An array whose componentsare of type charString: A sequence of zero or more charactersenclosed in double quote marksC-stings are null terminated (‘0’)The last character in a string is the nullcharacter
  • 28. 28 C-Strings or Character Arrayschar str[80] = “Amanuensis”
  • 29. 29 C-Strings or Character ArraysThere is a difference between A and "A"» A is the character A» "A" is the string ABecause strings are null terminated, "A"represents two characters, A and 0‘Similarly, "Hello" contains six characters,H, e, l, l, o, and 0
  • 30. 30 C-Strings or Character ArraysConsider the statement char name[16];Because C-strings are null terminated andname has sixteen components » the largest string that can be stored in name is 15If you store a string of length, say 10 in name » the first 11 components of name are used and the last 5 are left unused
  • 31. 31 Declaration of C-StringsSimilar to declaration of any arraychar name[30]; // no initializationchar title [20] = "Le Grande Fromage"; // initialized at declaration // with a stringchar chList [10] = {a, b, c, d}; // initialized with list of char // values
  • 32. 32 Initializing StringsWhen a character array is declared, it is legalto use the assignment operator to initializeNote : use of the = operator only legal for chararray initializationBut : aggregate array assignment is NOT greeting = “don’t do it;
  • 33. 33 C-Strings: Example-1#include<iostream>#include<conio.h>using namespace std;int main(){const int MAX = 80; //maximum characters in a stringchar str[MAX]; //string variable strcout<< “Enter a string n”;cin>>str; //put string in strcout<< “You entered: ” << str << endl; //display string from strgetch();return 0; }
  • 34. 34 Reading Embedded Blanks#include<iostream>#include<conio.h>using namespace std;int main(){const int MAX = 80;char str[MAX];cout<< “Enter a string n”;cin.get(str,MAX); //member function get() of the stream class of // which cin is an objectcout<< “You entered: ” << str << endl;getch();return 0; }
  • 35. 35 Reading Multiple Lines#include<iostream>#include<conio.h>using namespace std;const int MAX = 2000;char str[MAX];int main(){cout<< “Enter a string n”;cin.get(str, MAX, ‘$’); //terminate with $cout<< “You entered: ” << str << endl;getch();return 0; }
  • 36. 36 Copying a string: Hard-way#include<iostream>#include<cstring> // for copying a string#include<conio.h>using namespace std;int main(){ char str1[] = “C++ is the best programming” “language that I have ever used.”;const int MAX = 80;char str2[MAX];for(int j=0; j < strlen(str1); j++) str2[j] = str1[j];cout<< str2 << endl;getch();return 0; }
  • 37. 37 Copying a string: Easy-way#include<iostream>#include<cstring> // for copying a string#include<conio.h>using namespace std;int main(){ char str1[] = “C++ is the best programming” “language that I have ever used.”;const int MAX = 80;char str2[MAX];strcpy(str2, str1);cout<< str2 << endl;getch();return 0; }
  • 38. 38 Standard C++ string Class#include<iostream>#include<string> //string class#include<conio.h>using namespace std;int main(){ string s1(“Man”); string s2 = “Beast”; string s3;s3 = s1; //assigncout << “s3 = “ << s3 << endl;s3 = “Neither “ + s1 + “ nor ”; //concatenates3 += s2; //concatenatecout << “s3 = ” << s3 << endl;s1.swap(s2); //swap s1 and s2cout << s1 << ” nor “ << s2 << endl;getch(); return 0; }
  • 39. 39Contrast/Compare Strings and C-Strings Assignment is OK Assignment is illegal string s; char cs[30]; s = "hi mom"; cs = "dont do it"; Comparison OK Comparisons not allowed if (s < "geek") … I/O allowed much the I/O allowed cin >> s; same way cin.getline(s,n); cout << s;
  • 40. 40 Working with StringsFunctions provided in #include <cstring> Used instead of assignment Used for comparisons
  • 41. 41 Working with StringsC-strings are compared character by characterusing the collating sequence of the systemIf we are using the ASCII character set1. The string "Air" is smaller than the string "Boat"2. The string "Air" is smaller than the string "An"3. The string "Bill" is smaller than the string "Billy"4. The string "Hello" is smaller than "hello"
  • 42. 42Working with Strings
  • 43. 43 Passing Arrays to FunctionsArrays can be used as arguments to functions.
  • 44. 44 Passing Arguments to Arrays#include<iostream>#include<conio.h>using namespace std;int sum(int list[], int listSize){int index, sum = 0;for(index=0; index<listSize; index++) sum = sum + list[index];return sum; }int main(){ int myArray[] = {2, 3, 5}; cout<< "The is: " << sum(myArray, 3); getch(); return 0; }