SlideShare a Scribd company logo
1 of 26
A First Book of C++A First Book of C++
Chapter 7 (Pt 1)Chapter 7 (Pt 1)
ArraysArrays
∗ In this chapter, you will learn about:
∗ One-Dimensional Arrays
∗ Array Initialization
∗ Arrays as Arguments
∗ Two-Dimensional Arrays
∗ Common Programming Errors
∗ Searching and Sorting Methods
Objectives
A First Book of C++ 4th Edition 2
∗ One-dimensional array (single-dimension array or
vector) : a list of related values
∗ All items in list have same data type
∗ All list members stored using single group name
∗ Example: a list of grades
98, 87, 92, 79, 85
∗ All grades are integers and must be declared
∗ Can be declared as single unit under a common name (the
array name)
One-Dimensional Arrays
A First Book of C++ 4th Edition 3
∗ Array declaration statement provides:
∗ The array (list) name
∗ The data type of array items
∗ The number of items in array
∗ Syntax
dataType arrayName[numberOfItems]
∗ Common programming practice requires defining
number of array items as a constant before declaring
the array
One-Dimensional Arrays (cont'd.)
A First Book of C++ 4th Edition 4
normally define as a
constant
∗ Examples of array declaration statements:
const int NUMELS = 5; // define a constant
// for number of items
int amt[NUMELS]; // declare array amt
const int NUMELS = 4;
char code[NUMELS]; // array name code
const int SIZE = 100;
double amount[SIZE]; // array name amount
One-Dimensional Arrays (cont'd.)
A First Book of C++ 4th Edition 5
∗ Each array allocates sufficient memory to hold the
number of data items given in declaration
∗ Array element (component): an item of the array
∗ Individual array elements stored sequentially
∗ A key feature of arrays that provides a simple
mechanism for easily locating single elements
One-Dimensional Arrays (cont'd.)
A First Book of C++ 4th Edition 6
int num[10]
array
element
One-Dimensional Arrays (cont'd.)
A First Book of C++ 4th Edition 7
1 char = 1 byte
4 char = 4 x 1 = 4 bytes
1 int = 4 bytes
6 int = 4 x 6 = 24 bytes
int num[6]
char ch[4]
∗ Index (subscript value): position of individual element in
an array
∗ Accessing of array elements: done by giving array name
and element’s index
∗ grade[0] refers to first grade stored in grade array
∗ Subscripted variables can be used anywhere that scalar
variables are valid:
grade[0] = 95.75;
grade[1] = grade[0] - 11.0;
One-Dimensional Arrays (cont'd.)
A First Book of C++ 4th Edition 8
assigning value to an array
subtracting value
from an array
One-Dimensional Arrays (cont'd.)
A First Book of C++ 4th Edition 9
∗ Subscripts: do not have to be integers
∗ Any expression that evaluates to an integer may be
used as a subscript
∗ Subscript must be within the declared range
∗ Examples of valid subscripted variables (assumes i
and j are int variables):
grade[i]
grade[2*i]
grade[j-i]
One-Dimensional Arrays (cont'd.)
A First Book of C++ 4th Edition 10
∗ Individual array elements can be assigned values
interactively using a cin stream object
cin >> grade[0];
cin >> grade[1] >> grade[2] >> grade[3];
cin >> grade[4] >> prices[6];
∗ Instead, a for loop can be used
const int NUMELS = 5;
for (int i = 0; i < NUMELS; i++)
{
cout << "Enter a grade: ";
cin >> grade[i];
}
Input and Output of Array Values
A First Book of C++ 4th Edition 11
∗ Bounds checking: C++ does not check if value of an
index is within declared bounds
∗ If an out-of-bounds index is used, C++ will not provide
notification
∗ Program will attempt to access out-of-bounds element,
causing program error or crash
∗ Using symbolic constants (to define size of array) helps
avoid this problem
Input and Output of Array Values
(cont'd.)
A First Book of C++ 4th Edition 12
∗ Using cout to display subscripted variables:
∗ Example 1
cout << prices[5];
∗ Example 2
cout << "The value of element " << i
<< " is " << grade[i];
∗ Example 3
const int NUMELS = 20;
for (int k = 5; k < NUMELS; k++)
cout << k << " " << amount[k];
Input and Output of Array Values
(cont'd.)
A First Book of C++ 4th Edition 13
∗ Program example of array I/O (Program 7.1):
#include <iostream>
using namespace std;
int main()
{
const int NUMELS = 5;
int i, grade[NUMELS];//array grade of type int of size 5
for (i = 0; i < NUMELS; i++) // Enter the grades
{
cout << "Enter a grade: ";
cin >> grade[i]; // user enter 5 different values
}
cout << endl;
//loop through array list and display each item’s value
for (i = 0; i < NUMELS; i++) // Print the grades
cout << "grade [" << i << "] is " << grade[i] << endl;
return 0;
}
Input and Output of Array Values
(cont'd.)
A First Book of C++ 4th Edition 14
∗ Sample run using Program 7.1:
Enter a grade: 85
Enter a grade: 90
Enter a grade: 78
Enter a grade: 75
Enter a grade: 92
grade[0] is 85
grade[1] is 90
grade[2] is 78
grade[3] is 75
grade[4] is 92
Input and Output of Array Values
(cont'd.)
A First Book of C++ 4th Edition 15
∗ Array elements can be initialized within declaration
statements
∗ Initializing elements must be included in braces
∗ Example:
const int NUMGALS = 20;//size of array is 20
int gallons[NUMGALS] =
{19, 16, 14, 19, 20, 18, // initializing values
12, 10, 22, 15, 18, 17, // can extend across
16, 14, 23, 19, 15, 18, // multiple lines
21, 5}; // 20 different values for gallons
Array Initialization
A First Book of C++ 4th Edition 16
∗ Size of array may be omitted when initializing values are included in
declaration statement
∗ Example: the following are equivalent
const int NUMCODES = 6;
char code[6] = {'s', 'a', 'm', 'p', 'l', 'e'};
char code[NUMCODES] = {'s', 'a', 'm', 'p', 'l', 'e'};
char code[ ] = {'s', 'a', 'm', 'p', 'l', 'e'};
∗ All declarations set aside six character locations for an array named
code
Array Initialization (cont'd.)
A First Book of C++ 4th Edition 17
Different ways to initialize array :
=
∗ Simplified method for initializing character arrays
char codes[ ] = “sample”; //a string, no braces or commas
∗ This statement uses the string “sample” to initialize the code
array
∗ The array is comprised of seven characters
∗ The first six characters are the letters:
s, a, m, p, l, e
∗ The last character (the escape sequence 0) is called the null
character (“sample0”)
∗ Strings stored as an array of characters are known as C-Strings
Array Initialization (cont'd.)
A First Book of C++ 4th Edition 18
Array Initialization (cont'd.)
A First Book of C++ 4th Edition 19
used as a sentinel to
mark end of string
char codes[ ] = “sample”
Array Initialization (cont'd.)
A First Book of C++ 4th Edition 20
char code[ ] = {'s', 'a', 'm', 'p', 'l', 'e'}
∗ Array elements are passed to a called function in
same manner as individual scalar variables
∗ Example (function call):
findMax(grades[2], grades[6]);
∗ Passing a complete array to a function provides
access to the actual array, NOT a copy
∗ Making copies of large arrays is wasteful of storage
Arrays as Arguments
A First Book of C++ 4th Edition 21
∗ Examples of function calls that pass arrays:
int nums[5]; // an array of five integers
char keys[256]; // an array of 256 characters
double units[500], grades[500];// two arrays of
// 500 doubles
∗ The following function calls can then be made:
findMax(nums); //use only name of arrays
findCharacter(keys);
calcTotal(nums, units, grades);
Arrays as Arguments (cont'd.)
A First Book of C++ 4th Edition 22
∗ Suitable receiving side function header lines:
int findMax(int vals[5])
char findCharacter(char inKeys[256])
void calcTotal(int arr1[5],
double arr2[500],
double arr3[500])
Arrays as Arguments (cont'd.)
A First Book of C++ 4th Edition 23
∗ Example of passing arrays as arguments
(Program 7.4):
∗ Constant MAXELS is declared globally
∗ Prototype for findMax() uses constant MAXELS to
declare that findMax() expects an array of five
integers as an argument
∗ As shown in Figure 7.5, only one array is created in
Program 7.4
∗ In main(), the array is known as nums
∗ In findMax(), it is known as vals
Arrays as Arguments (cont'd.)
A First Book of C++ 4th Edition 24
A First Book of C++ 4th Edition 25
// datatype and size of array
Arrays as Arguments (cont'd.)
A First Book of C++ 4th Edition 26
=
nums is mapped to vals

More Related Content

What's hot (20)

Array ppt
Array pptArray ppt
Array ppt
 
Data structure array
Data structure  arrayData structure  array
Data structure array
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
 
Array lecture
Array lectureArray lecture
Array lecture
 
Array
ArrayArray
Array
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 
Arrays
ArraysArrays
Arrays
 
2 arrays
2   arrays2   arrays
2 arrays
 
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
 
1 D Arrays in C++
1 D Arrays in C++1 D Arrays in C++
1 D Arrays in C++
 
Array
ArrayArray
Array
 

Similar to Csc1100 lecture07 ch07_pt1-1

Csc1100 lecture09 ch07_pt2
Csc1100 lecture09 ch07_pt2Csc1100 lecture09 ch07_pt2
Csc1100 lecture09 ch07_pt2IIUM
 
19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.pptAqeelAbbas94
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-stringsPrincess Sam
 
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.pdfajajkhan16
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyworldchannel
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersANUSUYA S
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysMaulen Bale
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptxMrMaster11
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
 

Similar to Csc1100 lecture07 ch07_pt1-1 (20)

Csc1100 lecture09 ch07_pt2
Csc1100 lecture09 ch07_pt2Csc1100 lecture09 ch07_pt2
Csc1100 lecture09 ch07_pt2
 
Arrays
ArraysArrays
Arrays
 
19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
Arrays
ArraysArrays
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
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technology
 
Unit 2
Unit 2Unit 2
Unit 2
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
ARRAYS.pptx
ARRAYS.pptxARRAYS.pptx
ARRAYS.pptx
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
 
Arrays
ArraysArrays
Arrays
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 

More from IIUM

How to use_000webhost
How to use_000webhostHow to use_000webhost
How to use_000webhostIIUM
 
Chapter 2
Chapter 2Chapter 2
Chapter 2IIUM
 
Chapter 1
Chapter 1Chapter 1
Chapter 1IIUM
 
Kreydle internship-multimedia
Kreydle internship-multimediaKreydle internship-multimedia
Kreydle internship-multimediaIIUM
 
03phpbldgblock
03phpbldgblock03phpbldgblock
03phpbldgblockIIUM
 
Chap2 practice key
Chap2 practice keyChap2 practice key
Chap2 practice keyIIUM
 
Group p1
Group p1Group p1
Group p1IIUM
 
Tutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seoTutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seoIIUM
 
Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009IIUM
 
03 the htm_lforms
03 the htm_lforms03 the htm_lforms
03 the htm_lformsIIUM
 
Exercise on algo analysis answer
Exercise on algo analysis   answerExercise on algo analysis   answer
Exercise on algo analysis answerIIUM
 
Redo midterm
Redo midtermRedo midterm
Redo midtermIIUM
 
Heaps
HeapsHeaps
HeapsIIUM
 
Report format
Report formatReport format
Report formatIIUM
 
Edpuzzle guidelines
Edpuzzle guidelinesEdpuzzle guidelines
Edpuzzle guidelinesIIUM
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam PaperIIUM
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam PaperIIUM
 
Group assignment 1 s21516
Group assignment 1 s21516Group assignment 1 s21516
Group assignment 1 s21516IIUM
 
Avl tree-rotations
Avl tree-rotationsAvl tree-rotations
Avl tree-rotationsIIUM
 
Week12 graph
Week12   graph Week12   graph
Week12 graph IIUM
 

More from IIUM (20)

How to use_000webhost
How to use_000webhostHow to use_000webhost
How to use_000webhost
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Kreydle internship-multimedia
Kreydle internship-multimediaKreydle internship-multimedia
Kreydle internship-multimedia
 
03phpbldgblock
03phpbldgblock03phpbldgblock
03phpbldgblock
 
Chap2 practice key
Chap2 practice keyChap2 practice key
Chap2 practice key
 
Group p1
Group p1Group p1
Group p1
 
Tutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seoTutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seo
 
Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009
 
03 the htm_lforms
03 the htm_lforms03 the htm_lforms
03 the htm_lforms
 
Exercise on algo analysis answer
Exercise on algo analysis   answerExercise on algo analysis   answer
Exercise on algo analysis answer
 
Redo midterm
Redo midtermRedo midterm
Redo midterm
 
Heaps
HeapsHeaps
Heaps
 
Report format
Report formatReport format
Report format
 
Edpuzzle guidelines
Edpuzzle guidelinesEdpuzzle guidelines
Edpuzzle guidelines
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam Paper
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam Paper
 
Group assignment 1 s21516
Group assignment 1 s21516Group assignment 1 s21516
Group assignment 1 s21516
 
Avl tree-rotations
Avl tree-rotationsAvl tree-rotations
Avl tree-rotations
 
Week12 graph
Week12   graph Week12   graph
Week12 graph
 

Csc1100 lecture07 ch07_pt1-1

  • 1. A First Book of C++A First Book of C++ Chapter 7 (Pt 1)Chapter 7 (Pt 1) ArraysArrays
  • 2. ∗ In this chapter, you will learn about: ∗ One-Dimensional Arrays ∗ Array Initialization ∗ Arrays as Arguments ∗ Two-Dimensional Arrays ∗ Common Programming Errors ∗ Searching and Sorting Methods Objectives A First Book of C++ 4th Edition 2
  • 3. ∗ One-dimensional array (single-dimension array or vector) : a list of related values ∗ All items in list have same data type ∗ All list members stored using single group name ∗ Example: a list of grades 98, 87, 92, 79, 85 ∗ All grades are integers and must be declared ∗ Can be declared as single unit under a common name (the array name) One-Dimensional Arrays A First Book of C++ 4th Edition 3
  • 4. ∗ Array declaration statement provides: ∗ The array (list) name ∗ The data type of array items ∗ The number of items in array ∗ Syntax dataType arrayName[numberOfItems] ∗ Common programming practice requires defining number of array items as a constant before declaring the array One-Dimensional Arrays (cont'd.) A First Book of C++ 4th Edition 4 normally define as a constant
  • 5. ∗ Examples of array declaration statements: const int NUMELS = 5; // define a constant // for number of items int amt[NUMELS]; // declare array amt const int NUMELS = 4; char code[NUMELS]; // array name code const int SIZE = 100; double amount[SIZE]; // array name amount One-Dimensional Arrays (cont'd.) A First Book of C++ 4th Edition 5
  • 6. ∗ Each array allocates sufficient memory to hold the number of data items given in declaration ∗ Array element (component): an item of the array ∗ Individual array elements stored sequentially ∗ A key feature of arrays that provides a simple mechanism for easily locating single elements One-Dimensional Arrays (cont'd.) A First Book of C++ 4th Edition 6 int num[10] array element
  • 7. One-Dimensional Arrays (cont'd.) A First Book of C++ 4th Edition 7 1 char = 1 byte 4 char = 4 x 1 = 4 bytes 1 int = 4 bytes 6 int = 4 x 6 = 24 bytes int num[6] char ch[4]
  • 8. ∗ Index (subscript value): position of individual element in an array ∗ Accessing of array elements: done by giving array name and element’s index ∗ grade[0] refers to first grade stored in grade array ∗ Subscripted variables can be used anywhere that scalar variables are valid: grade[0] = 95.75; grade[1] = grade[0] - 11.0; One-Dimensional Arrays (cont'd.) A First Book of C++ 4th Edition 8 assigning value to an array subtracting value from an array
  • 9. One-Dimensional Arrays (cont'd.) A First Book of C++ 4th Edition 9
  • 10. ∗ Subscripts: do not have to be integers ∗ Any expression that evaluates to an integer may be used as a subscript ∗ Subscript must be within the declared range ∗ Examples of valid subscripted variables (assumes i and j are int variables): grade[i] grade[2*i] grade[j-i] One-Dimensional Arrays (cont'd.) A First Book of C++ 4th Edition 10
  • 11. ∗ Individual array elements can be assigned values interactively using a cin stream object cin >> grade[0]; cin >> grade[1] >> grade[2] >> grade[3]; cin >> grade[4] >> prices[6]; ∗ Instead, a for loop can be used const int NUMELS = 5; for (int i = 0; i < NUMELS; i++) { cout << "Enter a grade: "; cin >> grade[i]; } Input and Output of Array Values A First Book of C++ 4th Edition 11
  • 12. ∗ Bounds checking: C++ does not check if value of an index is within declared bounds ∗ If an out-of-bounds index is used, C++ will not provide notification ∗ Program will attempt to access out-of-bounds element, causing program error or crash ∗ Using symbolic constants (to define size of array) helps avoid this problem Input and Output of Array Values (cont'd.) A First Book of C++ 4th Edition 12
  • 13. ∗ Using cout to display subscripted variables: ∗ Example 1 cout << prices[5]; ∗ Example 2 cout << "The value of element " << i << " is " << grade[i]; ∗ Example 3 const int NUMELS = 20; for (int k = 5; k < NUMELS; k++) cout << k << " " << amount[k]; Input and Output of Array Values (cont'd.) A First Book of C++ 4th Edition 13
  • 14. ∗ Program example of array I/O (Program 7.1): #include <iostream> using namespace std; int main() { const int NUMELS = 5; int i, grade[NUMELS];//array grade of type int of size 5 for (i = 0; i < NUMELS; i++) // Enter the grades { cout << "Enter a grade: "; cin >> grade[i]; // user enter 5 different values } cout << endl; //loop through array list and display each item’s value for (i = 0; i < NUMELS; i++) // Print the grades cout << "grade [" << i << "] is " << grade[i] << endl; return 0; } Input and Output of Array Values (cont'd.) A First Book of C++ 4th Edition 14
  • 15. ∗ Sample run using Program 7.1: Enter a grade: 85 Enter a grade: 90 Enter a grade: 78 Enter a grade: 75 Enter a grade: 92 grade[0] is 85 grade[1] is 90 grade[2] is 78 grade[3] is 75 grade[4] is 92 Input and Output of Array Values (cont'd.) A First Book of C++ 4th Edition 15
  • 16. ∗ Array elements can be initialized within declaration statements ∗ Initializing elements must be included in braces ∗ Example: const int NUMGALS = 20;//size of array is 20 int gallons[NUMGALS] = {19, 16, 14, 19, 20, 18, // initializing values 12, 10, 22, 15, 18, 17, // can extend across 16, 14, 23, 19, 15, 18, // multiple lines 21, 5}; // 20 different values for gallons Array Initialization A First Book of C++ 4th Edition 16
  • 17. ∗ Size of array may be omitted when initializing values are included in declaration statement ∗ Example: the following are equivalent const int NUMCODES = 6; char code[6] = {'s', 'a', 'm', 'p', 'l', 'e'}; char code[NUMCODES] = {'s', 'a', 'm', 'p', 'l', 'e'}; char code[ ] = {'s', 'a', 'm', 'p', 'l', 'e'}; ∗ All declarations set aside six character locations for an array named code Array Initialization (cont'd.) A First Book of C++ 4th Edition 17 Different ways to initialize array : =
  • 18. ∗ Simplified method for initializing character arrays char codes[ ] = “sample”; //a string, no braces or commas ∗ This statement uses the string “sample” to initialize the code array ∗ The array is comprised of seven characters ∗ The first six characters are the letters: s, a, m, p, l, e ∗ The last character (the escape sequence 0) is called the null character (“sample0”) ∗ Strings stored as an array of characters are known as C-Strings Array Initialization (cont'd.) A First Book of C++ 4th Edition 18
  • 19. Array Initialization (cont'd.) A First Book of C++ 4th Edition 19 used as a sentinel to mark end of string char codes[ ] = “sample”
  • 20. Array Initialization (cont'd.) A First Book of C++ 4th Edition 20 char code[ ] = {'s', 'a', 'm', 'p', 'l', 'e'}
  • 21. ∗ Array elements are passed to a called function in same manner as individual scalar variables ∗ Example (function call): findMax(grades[2], grades[6]); ∗ Passing a complete array to a function provides access to the actual array, NOT a copy ∗ Making copies of large arrays is wasteful of storage Arrays as Arguments A First Book of C++ 4th Edition 21
  • 22. ∗ Examples of function calls that pass arrays: int nums[5]; // an array of five integers char keys[256]; // an array of 256 characters double units[500], grades[500];// two arrays of // 500 doubles ∗ The following function calls can then be made: findMax(nums); //use only name of arrays findCharacter(keys); calcTotal(nums, units, grades); Arrays as Arguments (cont'd.) A First Book of C++ 4th Edition 22
  • 23. ∗ Suitable receiving side function header lines: int findMax(int vals[5]) char findCharacter(char inKeys[256]) void calcTotal(int arr1[5], double arr2[500], double arr3[500]) Arrays as Arguments (cont'd.) A First Book of C++ 4th Edition 23
  • 24. ∗ Example of passing arrays as arguments (Program 7.4): ∗ Constant MAXELS is declared globally ∗ Prototype for findMax() uses constant MAXELS to declare that findMax() expects an array of five integers as an argument ∗ As shown in Figure 7.5, only one array is created in Program 7.4 ∗ In main(), the array is known as nums ∗ In findMax(), it is known as vals Arrays as Arguments (cont'd.) A First Book of C++ 4th Edition 24
  • 25. A First Book of C++ 4th Edition 25 // datatype and size of array
  • 26. Arrays as Arguments (cont'd.) A First Book of C++ 4th Edition 26 = nums is mapped to vals