SlideShare una empresa de Scribd logo
1 de 16
C++ Programming
Data Types, Arrays, Pointers
Mohammed Jehan
Lecturer
Data Types
The operating system allocates memory and selects what will be stored in the reserved memory based on the
variable's data type. The data type defines the proper use of an identifier, what kind of data can be stored, and
which types of operations can be performed.
The examples below show legal and illegal C++ expressions.
55+15 // legal C++ expression
//Both operands of the + operator are integers
55 + "John" // illegal
// The + operator is not defined for integer and string
Numeric Data Types
Numeric data types include:
Integers (whole numbers), such as -7, 42.
Floating point numbers, such as 3.14, -42.67.
Which of the following are correct values for the numeric data types?
Select all that apply
1. "hello"
2. 1000
3. 'abc'
4. 3.14
Strings & Characters
A string is composed of numbers, characters, or symbols. String literals are placed in
double quotation marks; some examples are "Hello", "My name is David", and similar.
Characters are single letters or symbols, and must be enclosed between single quotes, like
'a', 'b', etc.
Signed and unsigned Integers
Use the int keyword to define the integer data type.int a = 42;
Several of the basic types, including integers, can be modified using one or more of these type
modifiers:
signed: A signed integer can hold both negative and positive numbers.
unsigned: An unsigned integer can hold only positive values.
short: Half of the default size.
long: Twice the default size.
For example:
unsigned long int a;
NOTE: The size of the integer type varies according to the architecture of the system on which the
program runs, although 4 bytes is the minimum size in most modern system architectures.
Floating Point Numbers
A floating point type variable can hold a real number, such as 420.0, -3.33, or 0.03325.
The words floating point refer to the fact that a varying number of digits can appear before and after
the decimal point. You could say that the decimal has the ability to "float".
There are three different floating point data types: float, double, and long double.
In most modern architectures, a float is 4 bytes, a double is 8, and a long double can be equivalent to
a double (8 bytes), or 16 bytes.
For example: double temp = 4.21;
Floating point data types are always signed, which means that they have the capability to hold both
positive and negative values.
Strings
A string is an ordered sequence of characters, enclosed in double quotation marks. It is part of the Standard Library.
You need to include the <string> library to use the string data type. Alternatively, you can use a library that includes
the string library.
#include <string>
using namespace std;
int main() {
string a = "I am learning C++";
return 0;
}
Characters
A char variable holds a 1-byte integer. However, instead of interpreting the value of the
char as an integer, the value of a char variable is typically interpreted as an ASCII
character.
A character is enclosed between single quotes (such as 'a', 'b', etc).
For example:
char test = 'S';
American Standard Code for Information Interchange (ASCII) is a character-encoding
scheme that is used to represent text in computers.
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.

Más contenido relacionado

La actualidad más candente

C programming session 04
C programming session 04C programming session 04
C programming session 04
Dushmanta Nath
 

La actualidad más candente (20)

C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
 
Strings in c language
Strings in  c languageStrings in  c language
Strings in c language
 
Arrays in c_language
Arrays in c_language Arrays in c_language
Arrays in c_language
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
Arrays
ArraysArrays
Arrays
 
Data types in java | What is Datatypes in Java | Learning with RD | Created b...
Data types in java | What is Datatypes in Java | Learning with RD | Created b...Data types in java | What is Datatypes in Java | Learning with RD | Created b...
Data types in java | What is Datatypes in Java | Learning with RD | Created b...
 
Java: Primitive Data Types
Java: Primitive Data TypesJava: Primitive Data Types
Java: Primitive Data Types
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
 
Computer programming 2 Lesson 5
Computer programming 2  Lesson 5Computer programming 2  Lesson 5
Computer programming 2 Lesson 5
 
Array and string
Array and stringArray and string
Array and string
 
arrays of structures
arrays of structuresarrays of structures
arrays of structures
 
2 arrays
2   arrays2   arrays
2 arrays
 
Arrays
ArraysArrays
Arrays
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
arrays in c
arrays in carrays in c
arrays in c
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 

Similar a Lecture 7

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
 
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxCS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
faithxdunce63732
 
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
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
phanleson
 
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxCOMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
donnajames55
 

Similar a Lecture 7 (20)

Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Chapter-Five.pptx
Chapter-Five.pptxChapter-Five.pptx
Chapter-Five.pptx
 
Array
ArrayArray
Array
 
Arrays
ArraysArrays
Arrays
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>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
 
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxCS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptx
 
Array assignment
Array assignmentArray assignment
Array assignment
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
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
 
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
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Array lecture
Array lectureArray lecture
Array lecture
 
Array
ArrayArray
Array
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxCOMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
 

Más de Mohammed Khan

Más 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
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.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
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Último (20)

Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
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
 
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
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
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
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 

Lecture 7

  • 1. C++ Programming Data Types, Arrays, Pointers Mohammed Jehan Lecturer
  • 2. Data Types The operating system allocates memory and selects what will be stored in the reserved memory based on the variable's data type. The data type defines the proper use of an identifier, what kind of data can be stored, and which types of operations can be performed. The examples below show legal and illegal C++ expressions. 55+15 // legal C++ expression //Both operands of the + operator are integers 55 + "John" // illegal // The + operator is not defined for integer and string
  • 3. Numeric Data Types Numeric data types include: Integers (whole numbers), such as -7, 42. Floating point numbers, such as 3.14, -42.67. Which of the following are correct values for the numeric data types? Select all that apply 1. "hello" 2. 1000 3. 'abc' 4. 3.14
  • 4. Strings & Characters A string is composed of numbers, characters, or symbols. String literals are placed in double quotation marks; some examples are "Hello", "My name is David", and similar. Characters are single letters or symbols, and must be enclosed between single quotes, like 'a', 'b', etc.
  • 5. Signed and unsigned Integers Use the int keyword to define the integer data type.int a = 42; Several of the basic types, including integers, can be modified using one or more of these type modifiers: signed: A signed integer can hold both negative and positive numbers. unsigned: An unsigned integer can hold only positive values. short: Half of the default size. long: Twice the default size. For example: unsigned long int a; NOTE: The size of the integer type varies according to the architecture of the system on which the program runs, although 4 bytes is the minimum size in most modern system architectures.
  • 6. Floating Point Numbers A floating point type variable can hold a real number, such as 420.0, -3.33, or 0.03325. The words floating point refer to the fact that a varying number of digits can appear before and after the decimal point. You could say that the decimal has the ability to "float". There are three different floating point data types: float, double, and long double. In most modern architectures, a float is 4 bytes, a double is 8, and a long double can be equivalent to a double (8 bytes), or 16 bytes. For example: double temp = 4.21; Floating point data types are always signed, which means that they have the capability to hold both positive and negative values.
  • 7. Strings A string is an ordered sequence of characters, enclosed in double quotation marks. It is part of the Standard Library. You need to include the <string> library to use the string data type. Alternatively, you can use a library that includes the string library. #include <string> using namespace std; int main() { string a = "I am learning C++"; return 0; }
  • 8. Characters A char variable holds a 1-byte integer. However, instead of interpreting the value of the char as an integer, the value of a char variable is typically interpreted as an ASCII character. A character is enclosed between single quotes (such as 'a', 'b', etc). For example: char test = 'S'; American Standard Code for Information Interchange (ASCII) is a character-encoding scheme that is used to represent text in computers.
  • 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.