SlideShare a Scribd company logo
Arrays and Strings

     Lecture: 25

     19.09.2012


                     1
2



        Design Problem

Consider a program to calculate class
average




                              Why??
                              Why??


                                        ?
3



   Add to Design Problem

Now your client says, I need to ALSO
calculate and display “deviations” from
the average




       Describe why this will or will NOT work
       Describe why this will or will NOT work
4



      Possible Solutions

Enter in the scores again    
Use 100 separate variables 
» and cout and cin commands
Read (then re-read) from a file 
The real answer …

                 Use arrays!!
Simple vs Structured Data                5



             Types

 Simple data type => data element
 contains a single value
x ::15
 x 15         avg ::84.35
               avg 84.35         ch ::‘A’
                                  ch ‘A’


 Structured data type => a data element
 contains a collection of data values
scores :: 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



                  Arrays

 Arrays are Structured Data Types
 They have a means of accessing
 individual components
 Values can be retrieved from and stored
 in the structure
scores :: 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



   One Dimensional Array

Structured collection of components
 » All of the same type
Structure given a single name
Individual elements accessed by index
indicating relative position in collection
Type of elements stored in an array can
be “just about” anything
Index of an array must be an integer
8



Use of Array for Our Problem

Store elements in array as read in
Go back and access for deviations

                        Note declaration
                        Note declaration
9



      Declaring Arrays

Syntax:
 Data_type Array_name [constant];
Note declaration from our example




             Tells how many elements set aside
             Tells how many elements set aside
10



        Declaring Arrays

Example 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
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 99
Index 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



     Out of Bounds Index
What 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 of
range
Possible to walk off into “far reaches” of
memory -- clobbers ...
 » other variable locations
 » .exe code
 » the operating system (??)
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 array

float prices [ ] = { 2.41, 85.06, 19.95, 3.91 }
14



    Arrays as Parameters

This is one task that CAN be done to the
WHOLE array
C++ always passes arrays by reference
15



    Arrays as Parameters

The name of the array is a pointer
constant
The address of the array is passed to
the function
Size of the
array also
passed to
control loop
16



    Arrays as Parameters

Note the empty brackets in parameter
list
 » A number can be placed here but it
   will be
   ignored
17



       Multidimensional Arrays

A collection of a fixed number of components
arranged in two dimensions
»   All components are of the same type
The syntax for declaring a two-dimensional
array is:
dataType arrayName[intexp1][intexp2];
where intexp1 and intexp2 are expressions
yielding positive integer values.
18



     Multidimensional Arrays

The two expressions intexp1 and intexp2 specify
the number of rows and the number of columns,
respectively, in the array

Two-dimensional arrays are sometimes called
matrices or tables
19



       Multidimensional Arrays

double sales[10][5];
20



   Accessing Array Elements
The syntax to access a component of a two-
dimensional array is:
 arrayName[indexexp1][indexexp2]
where indexexp1 and indexexp2 are
expressions yielding nonnegative integer
values
indexexp1 specifies the row position and
indexexp2 specifies the column position
21



     Accessing Array Elements
sales[2][3] = 35.60;



                       35.60
22



    2-DIM. Array Initialization
Like one-dimensional arrays
» Two-dimensional arrays can be initialized when
   they are declared
To initialize a two-dimensional array when it is
declared
1. Elements of each row are enclosed within braces
   and separated by commas
2. All rows are enclosed within braces
3. For number arrays, if all components of a row are
   not specified, the unspecified components are
   initialized to zero
23



    2-DIM. Array Initialization
Example:

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



   2-DIM. Array Initialization
Accessing all of the elements of a two-dimensional
array requires two loops: one for the row, and one
for the column.
Since two-dimensional arrays are typically accessed
row by row, generally the row index is used as the
outer loop.

for (int nRow = 0; nRow < nNumRows; nRow++)
  for (int nCol = 0; nCol < nNumCols; nCol++)
         cout << anArray[nRow][nCol];
25



      Multidimensional Arrays
A collection of a fixed number of elements (called
components) arranged in n dimensions (n >= 1)
Also called an n-dimensional array
General syntax of declaring an n-dimensional array is:
dataType arrayName[intExp1][intExp2]...[intExpn];
where intExp1, intExp2, … are constant
expressions yielding positive integer values

Example: 3-Dimensional array:
               int anArray[5][4][3];
26



C-Strings or Character Arrays

We have learned that the elements of
an array can be just about anything
Consider an array whose elements are
all characters
 » Called a C-String
 » Has a collection of special routines
27



  C-Strings or Character Arrays
Character array: An array whose components
are of type char

String: A sequence of zero or more characters
enclosed in double quote marks

C-stings are null terminated (‘0’)

The last character in a string is the null
character
28



    C-Strings or Character Arrays
char str[80] = “Amanuensis”
29



  C-Strings or Character Arrays
There is a difference between 'A' and "A"

» 'A'   is the character A

» "A"   is the string A

Because strings are null terminated, "A"
represents two characters, 'A' and '0‘

Similarly, "Hello" contains six characters,
'H', 'e', 'l', 'l', 'o', and '0'
30



  C-Strings or Character Arrays
Consider the statement
   char name[16];
Because C-strings are null terminated and
name has sixteen components
 » the largest string that can be stored in name
   is 15
If 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



   Declaration of C-Strings

Similar to declaration of any array
char name[30];
   // no initialization
char title [20] = "Le Grande Fromage";
   // initialized at declaration
   // with a string
char chList [10] = {'a', 'b', 'c', 'd'};
   // initialized with list of char
   // values
32



       Initializing Strings

When a character array is declared, it is legal
to use the assignment operator to initialize




Note : use of the = operator only legal for char
array initialization
But : aggregate array assignment is NOT

      greeting = “don’t do it;
33

              C-Strings: Example-1
#include<iostream>
#include<conio.h>
using namespace std;

int main()
{
const int MAX = 80; //maximum characters in a string
char str[MAX]; //string variable str
cout<< “Enter a string n”;
cin>>str; //put string in str

cout<< “You entered: ” << str << endl;   //display string from str
getch();
return 0; }
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 object
cout<< “You entered: ” << str << endl;
getch();
return 0; }
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

       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

       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

            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; //assign
cout << “s3 = “ << s3 << endl;

s3 = “Neither “ + s1 + “ nor ”; //concatenate
s3 += s2;                        //concatenate
cout << “s3 = ” << s3 << endl;
s1.swap(s2);                //swap s1 and s2
cout << s1 << ” nor “ << s2 << endl;
getch(); return 0; }
39



Contrast/Compare Strings and C-Strings

  Assignment is OK       Assignment is illegal
  string s;              char cs[30];
  s = "hi mom";          cs = "don't 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



    Working with Strings

Functions provided in #include   <cstring>

                  Used instead of assignment




                     Used for comparisons
41

       Working with Strings
C-strings are compared character by character
using the collating sequence of the system
If we are using the ASCII character set
1. 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

Working with Strings
43

     Passing Arrays to Functions
Arrays can be used as arguments to functions.
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; }

More Related Content

What's hot

intorduction to Arrays in java
intorduction to Arrays in javaintorduction to Arrays in java
intorduction to Arrays in java
Muthukumaran Subramanian
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
OXUS 20
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
Arzath Areeff
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Arrays in Java | Edureka
Arrays in Java | EdurekaArrays in Java | Edureka
Arrays in Java | Edureka
Edureka!
 
Java arrays
Java    arraysJava    arrays
Java arrays
Mohammed Sikander
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
Gopal Ji Singh
 
Arrays Class presentation
Arrays Class presentationArrays Class presentation
Arrays Class presentationNeveen Reda
 
array
array array
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
Tareq Hasan
 
Two-dimensional array in java
Two-dimensional array in javaTwo-dimensional array in java
Two-dimensional array in java
Talha mahmood
 
Array in c++
Array in c++Array in c++
Array in c++
Mahesha Mano
 
Array in c#
Array in c#Array in c#
Array in c#
Prem Kumar Badri
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
Hock Leng PUAH
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2
Rajendran
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
imtiazalijoono
 
Array
ArrayArray
Array
PRN USM
 
Array
ArrayArray

What's hot (20)

intorduction to Arrays in java
intorduction to Arrays in javaintorduction to Arrays in java
intorduction to Arrays in java
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Arrays in Java | Edureka
Arrays in Java | EdurekaArrays in Java | Edureka
Arrays in Java | Edureka
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
 
Arrays Class presentation
Arrays Class presentationArrays Class presentation
Arrays Class presentation
 
array
array array
array
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Two-dimensional array in java
Two-dimensional array in javaTwo-dimensional array in java
Two-dimensional array in java
 
Array in c++
Array in c++Array in c++
Array in c++
 
Chap09
Chap09Chap09
Chap09
 
Array in c#
Array in c#Array in c#
Array in c#
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
Array
ArrayArray
Array
 
Array
ArrayArray
Array
 

Similar to Lec 25 - arrays-strings

Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
Ashim Lamichhane
 
Arrays
ArraysArrays
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
ajajkhan16
 
Arrays
ArraysArrays
Arrays
ArraysArrays
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
Swarup Boro
 
Array,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN CArray,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN C
naveed jamali
 
Array.pptx
Array.pptxArray.pptx
Array.pptx
fixocin377
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
chanchal ghosh
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
maznabili
 
Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1IIUM
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
Thesis Scientist Private Limited
 
ARRAYS
ARRAYSARRAYS
ARRAYS
muniryaseen
 

Similar to Lec 25 - arrays-strings (20)

Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
 
Ch08
Ch08Ch08
Ch08
 
Arrays
ArraysArrays
Arrays
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Array,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN CArray,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN C
 
Array.pptx
Array.pptxArray.pptx
Array.pptx
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
2 arrays
2   arrays2   arrays
2 arrays
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 

More from Princess Sam

Lec 49 - stream-files
Lec 49 - stream-filesLec 49 - stream-files
Lec 49 - stream-filesPrincess Sam
 
Lec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsLec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsPrincess Sam
 
Lec 40.41 - pointers
Lec 40.41 -  pointersLec 40.41 -  pointers
Lec 40.41 - pointersPrincess Sam
 
Lec 38.39 - pointers
Lec 38.39 -  pointersLec 38.39 -  pointers
Lec 38.39 - pointersPrincess Sam
 
Lec 47.48 - stream-files
Lec 47.48 - stream-filesLec 47.48 - stream-files
Lec 47.48 - stream-filesPrincess Sam
 
Lec 45.46- virtual.functions
Lec 45.46- virtual.functionsLec 45.46- virtual.functions
Lec 45.46- virtual.functionsPrincess Sam
 
Lec 33 - inheritance
Lec 33 -  inheritanceLec 33 -  inheritance
Lec 33 - inheritancePrincess Sam
 
Lec 30.31 - inheritance
Lec 30.31 -  inheritanceLec 30.31 -  inheritance
Lec 30.31 - inheritancePrincess Sam
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloadingPrincess Sam
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 

More from Princess Sam (13)

Lec 50
Lec 50Lec 50
Lec 50
 
Lec 49 - stream-files
Lec 49 - stream-filesLec 49 - stream-files
Lec 49 - stream-files
 
Lec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsLec 42.43 - virtual.functions
Lec 42.43 - virtual.functions
 
Lec 40.41 - pointers
Lec 40.41 -  pointersLec 40.41 -  pointers
Lec 40.41 - pointers
 
Lec 38.39 - pointers
Lec 38.39 -  pointersLec 38.39 -  pointers
Lec 38.39 - pointers
 
Lec 47.48 - stream-files
Lec 47.48 - stream-filesLec 47.48 - stream-files
Lec 47.48 - stream-files
 
Lec 45.46- virtual.functions
Lec 45.46- virtual.functionsLec 45.46- virtual.functions
Lec 45.46- virtual.functions
 
Lec 37 - pointers
Lec 37 -  pointersLec 37 -  pointers
Lec 37 - pointers
 
Lec 33 - inheritance
Lec 33 -  inheritanceLec 33 -  inheritance
Lec 33 - inheritance
 
Lec 30.31 - inheritance
Lec 30.31 -  inheritanceLec 30.31 -  inheritance
Lec 30.31 - inheritance
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
Lec 36 - pointers
Lec 36 -  pointersLec 36 -  pointers
Lec 36 - pointers
 

Lec 25 - arrays-strings

  • 1. Arrays and Strings Lecture: 25 19.09.2012 1
  • 2. 2 Design Problem Consider a program to calculate class average Why?? Why?? ?
  • 3. 3 Add to Design Problem Now your client says, I need to ALSO calculate and display “deviations” from the average Describe why this will or will NOT work Describe why this will or will NOT work
  • 4. 4 Possible Solutions Enter in the scores again  Use 100 separate variables  » and cout and cin commands Read (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 value x ::15 x 15 avg ::84.35 avg 84.35 ch ::‘A’ ch ‘A’ Structured data type => a data element contains a collection of data values scores :: 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 structure scores :: 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 Array Structured collection of components » All of the same type Structure given a single name Individual elements accessed by index indicating relative position in collection Type of elements stored in an array can be “just about” anything Index of an array must be an integer
  • 8. 8 Use of Array for Our Problem Store elements in array as read in Go back and access for deviations Note declaration Note declaration
  • 9. 9 Declaring Arrays Syntax: 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 Arrays Example 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 99 Index 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 Index What 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 of range Possible to walk off into “far reaches” of memory -- 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 array float prices [ ] = { 2.41, 85.06, 19.95, 3.91 }
  • 14. 14 Arrays as Parameters This is one task that CAN be done to the WHOLE array C++ always passes arrays by reference
  • 15. 15 Arrays as Parameters The name of the array is a pointer constant The address of the array is passed to the function Size of the array also passed to control loop
  • 16. 16 Arrays as Parameters Note the empty brackets in parameter list » A number can be placed here but it will be ignored
  • 17. 17 Multidimensional Arrays A collection of a fixed number of components arranged in two dimensions » All components are of the same type The syntax for declaring a two-dimensional array is: dataType arrayName[intexp1][intexp2]; where intexp1 and intexp2 are expressions yielding positive integer values.
  • 18. 18 Multidimensional Arrays The two expressions intexp1 and intexp2 specify the number of rows and the number of columns, respectively, in the array Two-dimensional arrays are sometimes called matrices or tables
  • 19. 19 Multidimensional Arrays double sales[10][5];
  • 20. 20 Accessing Array Elements The syntax to access a component of a two- dimensional array is: arrayName[indexexp1][indexexp2] where indexexp1 and indexexp2 are expressions yielding nonnegative integer values indexexp1 specifies the row position and indexexp2 specifies the column position
  • 21. 21 Accessing Array Elements sales[2][3] = 35.60; 35.60
  • 22. 22 2-DIM. Array Initialization Like one-dimensional arrays » Two-dimensional arrays can be initialized when they are declared To initialize a two-dimensional array when it is declared 1. Elements of each row are enclosed within braces and separated by commas 2. All rows are enclosed within braces 3. For number arrays, if all components of a row are not specified, the unspecified components are initialized to zero
  • 23. 23 2-DIM. Array Initialization Example: 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 Initialization Accessing all of the elements of a two-dimensional array requires two loops: one for the row, and one for the column. Since two-dimensional arrays are typically accessed row by row, generally the row index is used as the outer loop. for (int nRow = 0; nRow < nNumRows; nRow++) for (int nCol = 0; nCol < nNumCols; nCol++) cout << anArray[nRow][nCol];
  • 25. 25 Multidimensional Arrays A collection of a fixed number of elements (called components) arranged in n dimensions (n >= 1) Also called an n-dimensional array General syntax of declaring an n-dimensional array is: dataType arrayName[intExp1][intExp2]...[intExpn]; where intExp1, intExp2, … are constant expressions yielding positive integer values Example: 3-Dimensional array: int anArray[5][4][3];
  • 26. 26 C-Strings or Character Arrays We have learned that the elements of an array can be just about anything Consider an array whose elements are all characters » Called a C-String » Has a collection of special routines
  • 27. 27 C-Strings or Character Arrays Character array: An array whose components are of type char String: A sequence of zero or more characters enclosed in double quote marks C-stings are null terminated (‘0’) The last character in a string is the null character
  • 28. 28 C-Strings or Character Arrays char str[80] = “Amanuensis”
  • 29. 29 C-Strings or Character Arrays There is a difference between 'A' and "A" » 'A' is the character A » "A" is the string A Because 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 Arrays Consider the statement char name[16]; Because C-strings are null terminated and name has sixteen components » the largest string that can be stored in name is 15 If 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-Strings Similar to declaration of any array char name[30]; // no initialization char title [20] = "Le Grande Fromage"; // initialized at declaration // with a string char chList [10] = {'a', 'b', 'c', 'd'}; // initialized with list of char // values
  • 32. 32 Initializing Strings When a character array is declared, it is legal to use the assignment operator to initialize Note : use of the = operator only legal for char array initialization But : 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 string char str[MAX]; //string variable str cout<< “Enter a string n”; cin>>str; //put string in str cout<< “You entered: ” << str << endl; //display string from str getch(); 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 object cout<< “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; //assign cout << “s3 = “ << s3 << endl; s3 = “Neither “ + s1 + “ nor ”; //concatenate s3 += s2; //concatenate cout << “s3 = ” << s3 << endl; s1.swap(s2); //swap s1 and s2 cout << s1 << ” nor “ << s2 << endl; getch(); return 0; }
  • 39. 39 Contrast/Compare Strings and C-Strings Assignment is OK Assignment is illegal string s; char cs[30]; s = "hi mom"; cs = "don't 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 Strings Functions provided in #include <cstring> Used instead of assignment Used for comparisons
  • 41. 41 Working with Strings C-strings are compared character by character using the collating sequence of the system If we are using the ASCII character set 1. 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"
  • 43. 43 Passing Arrays to Functions Arrays 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; }