SlideShare une entreprise Scribd logo
1  sur  16
C++ Programming
Multi-Dimensional Arrays & Pointers
Mohammed Jehan
Lecturer
Multi-Dimensional Arrays
A multi-dimensional array holds one or more arrays. Declare a multidimensional array as follows.
type name[size1][size2]...[sizeN];
Here, we've created a two-dimensional 3x4 integer array: int x[3][4];
Two-Dimensional Arrays
Multi-dimensional arrays may be initialized by specifying bracketed values for each
row.
Following is an array with 2 rows and 3 columns:
int x[2][3] = {
{2, 3, 4}, {8, 9, 10}
};
The elements are accessed by using the row index and column index of the array.
For example:
#include <iostream>
using namespace std;
int main()
{ int x[2][3] = {{2, 3, 4}, {8, 9, 10}};
cout << x[0][2] << endl;
return 0;}
QUESTION TIME
Write a code to print X's
element's value to the
screen, which is located
at the first row and the
second column.
Multi-Dimensional Arrays
Arrays can contain an unlimited number of dimensions.
string threeD[42][8][3];
The example above declares a three-dimensional array of strings. As we did previously, it's
possible to use index numbers to access and modify the elements.
QUESTION TIME:
Write a code to declare a multidimensional array with 2 rows and 3 columns. Enter the
value using cin for the element in the second column of the second row.
Pointers
Every variable is a memory location, which has its address defined. That address can be accessed
using the ampersand (&) operator (also called the address-of operator), which denotes an address in
memory. A pointer is a variable, with the address of another variable as its value. In C++, pointers
help make certain tasks easier to perform. Other tasks, such as dynamic memory allocation, cannot
be performed without using pointers. All pointers share the same data type - a long hexadecimal
number that represents a memory address.
For example:
int score = 5;
cout << &score << endl;
//Outputs "0x29fee8“
This outputs the memory address, which stores the variable score.
Pointers
A pointer is a variable, and like any other variable, it must be declared before you can work with it.
The asterisk sign is used to declare a pointer (the same asterisk that you use for multiplication),
however, in this statement the asterisk is being used to designate a variable as a pointer.
Following are valid pointer declarations:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch; // pointer to a character
Just like with variables, we give the pointers a name and define the type, to which the pointer points
to. The asterisk sign can be placed next to the data type, or the variable name, or in the middle.
Using Pointers
Here, we assign the address of a variable to the pointer.
int score = 5;
int *scorePtr;
scorePtr = &score;
cout << scorePtr << endl;
The code above declares a pointer to an integer called scorePtr, and assigns to it the memory location of the score
variable using the ampersand (address-of) operator. Now, scorePtr's value is the memory location of score.
Pointer Operations
There are two operators for pointers: Address-of operator (&): returns the memory address of its operand.
Contents-of (or dereference) operator (*): returns the value of the variable located at the address specified by its
operand.
For example:
int var = 50;
int *p;
p = &var;
cout << var << endl;
// Outputs 50 (the value of var)
cout << p << endl;
// Outputs 0x29fee8 (var's memory location)
cout << *p << endl;
/* Outputs 50 (the value of the variable
stored in the pointer p) */
The asterisk (*) is used in declaring a pointer for the simple purpose
of indicating that it is a pointer (The asterisk is part of its type
compound specifier). Don't confuse this with the dereference
operator, which is used to obtain the value located at the specified
address. They are simply two different things represented with the
same sign.
Type in the missing parts to declare the x variable
with a value of 25 and a p pointer containing the x's
address. Print the memory location stored in the
pointer to the screen.
int x = 25;
int * p = ___ x;
cout <<___ << endl;
Booleans
Boolean variables only have two possible values: true (1) and false (0).
To declare a boolean variable, we use the keyword bool.
bool online = false;
bool logged_in = true;
If a Boolean value is assigned to an integer, true becomes 1 and false becomes 0.
If an integer value is assigned to a Boolean, 0 becomes false and any value that has a non-
zero value becomes true.
Variable Naming Rules
Use the following rules when naming variables:
- All variable names must begin with a letter of the alphabet or an underscore( _ ).
- After the initial letter, variable names can contain additional letters, as well as
numbers. Blank spaces or special characters are not allowed in variable names.
There are two known naming conventions:
Pascal case: The first letter in the identifier and the first letter of each subsequent
concatenated word are capitalized. For example: BackColor
Camel case: The first letter of an identifier is lowercase and the first letter of each
subsequent concatenated word is capitalized. For example: backColor
Arrays
An array is used to store a collection of data, but it may be useful to think of an array as a collection of
variables that are all of the same type. Instead of declaring multiple variables and storing individual
values, you can declare a single array to store all the values. When declaring an array, specify its
element types, as well as the number of elements it will hold.
For example:
int a[5];
In the example above, variable a was declared as an array of five integer values [specified in square
brackets].
You can initialise the array by specifying the values it holds:
int b[5] = {11, 45, 62, 70, 88};
The values are provided in a comma separated list, enclosed in {curly braces}. The number of values between
braces { } must not exceed the number of the elements declared within the square brackets [ ].
Initializing Arrays
If you omit the size of the array, an array just big enough to hold the initialization is created.
For example:
int b[] = {11, 45, 62, 70, 88};
This creates an identical array to the one created in the previous example. Each element, or member, of the array
has an index, which pinpoints the element's specific position. The array's first member has the index of 0, the
second has the index of 1. So, for the array b that we declared above:
To access array elements, index the array name by placing the element's index in square brackets following the array
name.
For example:
int b[] = {11, 45, 62, 70, 88};
cout << b[0] << endl;
cout<< b[3] << endl;
Initializing Arrays
If you omit the size of the array, an array just big enough to hold the initialization is created.
For example:
int b[] = {11, 45, 62, 70, 88};
This creates an identical array to the one created in the previous example. Each element, or member, of the array
has an index, which pinpoints the element's specific position. The array's first member has the index of 0, the
second has the index of 1. So, for the array b that we declared above:
To access array elements, index the array name by placing the element's index in square brackets following the array
name.
For example:
int b[] = {11, 45, 62, 70, 88};
cout << b[0] << endl;
cout<< b[3] << endl;
Fill in the blanks to print to the screen the first and the last
elements of an array with a size of 5.
cout << arr[] << endl;
cout << arr[] << endl;
Accessing Array Elements
Index numbers may also be used to assign a new value to an element.
int b[] = {11, 45, 62, 70, 88};
b[2] = 42;
This assigns a value of 42 to the array's third element.
Always remember that the list of elements always begins with the index of 0.
Arrays in Loops
It's occasionally necessary to iterate over the elements of an array, assigning the elements values
based on certain calculations. Usually, this is accomplished using a loop. Let's declare an array, that is
going to store 5 integers, and assign a value to each element using the for loop:
int myArr[5];
for(int x=0; x<5; x++) {
myArr[x] = 42;
}
Let's output each index and corresponding value in the array.
Arrays in Calculations
The following code creates a program that uses a for loop to calculate the sum of all elements of an
array.
int arr[] = {11, 35, 62, 555, 989};
int sum = 0;
for (int x = 0; x < 5; x++) {
sum += arr[x];
}
cout << sum << endl;
To review, we declared an array and a variable sum that will hold the sum of the elements. Next, we utilized a for
loop to iterate through each element of the array, and added the corresponding element's value to our sum
variable. In the array, the first element's index is 0, so the for loop initializes the x variable to 0.

Contenu connexe

Tendances

Tendances (20)

Module7
Module7Module7
Module7
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
 
C pointers and references
C pointers and referencesC pointers and references
C pointers and references
 
Array
ArrayArray
Array
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
7array in c#
7array in c#7array in c#
7array in c#
 
Arrays
ArraysArrays
Arrays
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
Array assignment
Array assignmentArray assignment
Array assignment
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Array
ArrayArray
Array
 
Structures
StructuresStructures
Structures
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
Arrays
ArraysArrays
Arrays
 

Similaire à Lecture 9

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
ANUSUYA S
 
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
aroraopticals15
 
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
worldchannel
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 

Similaire à Lecture 9 (20)

Lecture 7
Lecture 7Lecture 7
Lecture 7
 
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
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
Arrays
ArraysArrays
Arrays
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
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
 
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
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptx
 
Array lecture
Array lectureArray lecture
Array lecture
 
Pointer in c
Pointer in c Pointer in c
Pointer in c
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
 
Learn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & ArraysLearn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & Arrays
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptx
 
Arrays
ArraysArrays
Arrays
 
Unit 2
Unit 2Unit 2
Unit 2
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
2 arrays
2   arrays2   arrays
2 arrays
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 

Plus de Mohammed Khan

Plus de Mohammed Khan (17)

Lecture 6
Lecture 6Lecture 6
Lecture 6
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Module 11 therapeutic intervention play yoga
Module 11 therapeutic  intervention  play yogaModule 11 therapeutic  intervention  play yoga
Module 11 therapeutic intervention play yoga
 
Module 10 principles of learning, practice, reinforcement understanding spec...
Module 10 principles of learning, practice, reinforcement understanding  spec...Module 10 principles of learning, practice, reinforcement understanding  spec...
Module 10 principles of learning, practice, reinforcement understanding spec...
 
Module 9 speci ed
Module 9 speci edModule 9 speci ed
Module 9 speci ed
 
Module 8 spec ed
Module 8 spec edModule 8 spec ed
Module 8 spec ed
 
Module 7 special ed
Module 7  special edModule 7  special ed
Module 7 special ed
 
Module 6 spec ed
Module 6 spec edModule 6 spec ed
Module 6 spec ed
 
Module 5 special ed
Module 5 special edModule 5 special ed
Module 5 special ed
 
Module 4 spec needs
Module 4 spec needsModule 4 spec needs
Module 4 spec needs
 
Module 3 special education
Module 3 special educationModule 3 special education
Module 3 special education
 
Module 2 special ed
Module 2 special edModule 2 special ed
Module 2 special ed
 
Module 1 special ed
Module 1 special edModule 1 special ed
Module 1 special ed
 

Dernier

An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Dernier (20)

How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

Lecture 9

  • 1. C++ Programming Multi-Dimensional Arrays & Pointers Mohammed Jehan Lecturer
  • 2. Multi-Dimensional Arrays A multi-dimensional array holds one or more arrays. Declare a multidimensional array as follows. type name[size1][size2]...[sizeN]; Here, we've created a two-dimensional 3x4 integer array: int x[3][4];
  • 3. Two-Dimensional Arrays Multi-dimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 2 rows and 3 columns: int x[2][3] = { {2, 3, 4}, {8, 9, 10} }; The elements are accessed by using the row index and column index of the array. For example: #include <iostream> using namespace std; int main() { int x[2][3] = {{2, 3, 4}, {8, 9, 10}}; cout << x[0][2] << endl; return 0;} QUESTION TIME Write a code to print X's element's value to the screen, which is located at the first row and the second column.
  • 4. Multi-Dimensional Arrays Arrays can contain an unlimited number of dimensions. string threeD[42][8][3]; The example above declares a three-dimensional array of strings. As we did previously, it's possible to use index numbers to access and modify the elements. QUESTION TIME: Write a code to declare a multidimensional array with 2 rows and 3 columns. Enter the value using cin for the element in the second column of the second row.
  • 5. Pointers Every variable is a memory location, which has its address defined. That address can be accessed using the ampersand (&) operator (also called the address-of operator), which denotes an address in memory. A pointer is a variable, with the address of another variable as its value. In C++, pointers help make certain tasks easier to perform. Other tasks, such as dynamic memory allocation, cannot be performed without using pointers. All pointers share the same data type - a long hexadecimal number that represents a memory address. For example: int score = 5; cout << &score << endl; //Outputs "0x29fee8“ This outputs the memory address, which stores the variable score.
  • 6. Pointers A pointer is a variable, and like any other variable, it must be declared before you can work with it. The asterisk sign is used to declare a pointer (the same asterisk that you use for multiplication), however, in this statement the asterisk is being used to designate a variable as a pointer. Following are valid pointer declarations: int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch; // pointer to a character Just like with variables, we give the pointers a name and define the type, to which the pointer points to. The asterisk sign can be placed next to the data type, or the variable name, or in the middle.
  • 7. Using Pointers Here, we assign the address of a variable to the pointer. int score = 5; int *scorePtr; scorePtr = &score; cout << scorePtr << endl; The code above declares a pointer to an integer called scorePtr, and assigns to it the memory location of the score variable using the ampersand (address-of) operator. Now, scorePtr's value is the memory location of score.
  • 8. Pointer Operations There are two operators for pointers: Address-of operator (&): returns the memory address of its operand. Contents-of (or dereference) operator (*): returns the value of the variable located at the address specified by its operand. For example: int var = 50; int *p; p = &var; cout << var << endl; // Outputs 50 (the value of var) cout << p << endl; // Outputs 0x29fee8 (var's memory location) cout << *p << endl; /* Outputs 50 (the value of the variable stored in the pointer p) */ The asterisk (*) is used in declaring a pointer for the simple purpose of indicating that it is a pointer (The asterisk is part of its type compound specifier). Don't confuse this with the dereference operator, which is used to obtain the value located at the specified address. They are simply two different things represented with the same sign. Type in the missing parts to declare the x variable with a value of 25 and a p pointer containing the x's address. Print the memory location stored in the pointer to the screen. int x = 25; int * p = ___ x; cout <<___ << endl;
  • 9. Booleans Boolean variables only have two possible values: true (1) and false (0). To declare a boolean variable, we use the keyword bool. bool online = false; bool logged_in = true; If a Boolean value is assigned to an integer, true becomes 1 and false becomes 0. If an integer value is assigned to a Boolean, 0 becomes false and any value that has a non- zero value becomes true.
  • 10. Variable Naming Rules Use the following rules when naming variables: - All variable names must begin with a letter of the alphabet or an underscore( _ ). - After the initial letter, variable names can contain additional letters, as well as numbers. Blank spaces or special characters are not allowed in variable names. There are two known naming conventions: Pascal case: The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. For example: BackColor Camel case: The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized. For example: backColor
  • 11. Arrays An array is used to store a collection of data, but it may be useful to think of an array as a collection of variables that are all of the same type. Instead of declaring multiple variables and storing individual values, you can declare a single array to store all the values. When declaring an array, specify its element types, as well as the number of elements it will hold. For example: int a[5]; In the example above, variable a was declared as an array of five integer values [specified in square brackets]. You can initialise the array by specifying the values it holds: int b[5] = {11, 45, 62, 70, 88}; The values are provided in a comma separated list, enclosed in {curly braces}. The number of values between braces { } must not exceed the number of the elements declared within the square brackets [ ].
  • 12. Initializing Arrays If you omit the size of the array, an array just big enough to hold the initialization is created. For example: int b[] = {11, 45, 62, 70, 88}; This creates an identical array to the one created in the previous example. Each element, or member, of the array has an index, which pinpoints the element's specific position. The array's first member has the index of 0, the second has the index of 1. So, for the array b that we declared above: To access array elements, index the array name by placing the element's index in square brackets following the array name. For example: int b[] = {11, 45, 62, 70, 88}; cout << b[0] << endl; cout<< b[3] << endl;
  • 13. Initializing Arrays If you omit the size of the array, an array just big enough to hold the initialization is created. For example: int b[] = {11, 45, 62, 70, 88}; This creates an identical array to the one created in the previous example. Each element, or member, of the array has an index, which pinpoints the element's specific position. The array's first member has the index of 0, the second has the index of 1. So, for the array b that we declared above: To access array elements, index the array name by placing the element's index in square brackets following the array name. For example: int b[] = {11, 45, 62, 70, 88}; cout << b[0] << endl; cout<< b[3] << endl; Fill in the blanks to print to the screen the first and the last elements of an array with a size of 5. cout << arr[] << endl; cout << arr[] << endl;
  • 14. Accessing Array Elements Index numbers may also be used to assign a new value to an element. int b[] = {11, 45, 62, 70, 88}; b[2] = 42; This assigns a value of 42 to the array's third element. Always remember that the list of elements always begins with the index of 0.
  • 15. Arrays in Loops It's occasionally necessary to iterate over the elements of an array, assigning the elements values based on certain calculations. Usually, this is accomplished using a loop. Let's declare an array, that is going to store 5 integers, and assign a value to each element using the for loop: int myArr[5]; for(int x=0; x<5; x++) { myArr[x] = 42; } Let's output each index and corresponding value in the array.
  • 16. Arrays in Calculations The following code creates a program that uses a for loop to calculate the sum of all elements of an array. int arr[] = {11, 35, 62, 555, 989}; int sum = 0; for (int x = 0; x < 5; x++) { sum += arr[x]; } cout << sum << endl; To review, we declared an array and a variable sum that will hold the sum of the elements. Next, we utilized a for loop to iterate through each element of the array, and added the corresponding element's value to our sum variable. In the array, the first element's index is 0, so the for loop initializes the x variable to 0.