05.Arrays
05.Arrays
0 1 2 3 4
… … … … …
SoftUni Team
Technical Trainers
Software University
https://softuni.bg/
Table of Contents
sli.do
#cpp-fundamentals
3
0 1 2 3 4
… … … … …
Arrays
LIVE DEMO
0 1 2 3 4
… … … … …
Index 0 1 2 3 4
Value 10 9 12 31 15
8
0 1 2 3 4
… … … … …
int array[lenght];
cout << "Enter elements in array: " << endl;
for(int i = 0; i < lenght; i++) {
cin >> array[i];
}
cout << "Elements in array: " << endl;
for(int i = 0; i < lenght; i++) {
cout << array[i] << " ";
}
cout << endl;
cout << "End of elements" << endl;
17
How NOT to Read and Print an Array
int lenght = 0;
cout << "Enter a lenght of array: " << endl;
cin >> lenght;
int array[lenght];
cout << "Enter elements in array: " << endl;
for(int i = 0; i < lenght; i++) {
cin >> array[i];
}
cout << "Elements in array: " << endl;
for(int i = 0; i < lenght; i++) {
cout << array[i] << " ";
}
cout << endl;
cout << "End of elements" << endl;
18
0 1 2 3 4
… … … … …
22
0 1 2 3 4
… … … … …
Arrays as Pointers
Arrays as Pointers
*ptr == arr[0];
*(ptr + 1) is equivalent to arr[1];
*(ptr + 2) is equivalent to arr[2];
26
0 1 2 3 4
… … … … …
Arrays as Pointers
LIVE DEMO
C++11 Range-Based for Loop
C++11 Range-Based for Loop
Tired of writing for loops with indices to iterate over an array?
C++11 added a loop for that use-case
Syntax (for arrays): for (DataType element : array)
Body will execute once for each element in the array
On each iteration, element will be the next item in the array
int numbers[] = { 13, 42,
69 };
for (int i : numbers) {
cout << i << endl;
}
29
Range-Based for Loop
LIVE DEMO
0 1 2 3 4
… … … … …
34
Questions?
© SoftUni – https://about.softuni.bg. Copyrighted document. Unauthorized copy, reproduction or use is not permitted.
SoftUni Diamond Partners
Educational Partners
37
License
38
Trainings @ Software University (SoftUni)
Software University – High-Quality Education,
Profession and Job for Software Developers
softuni.bg, about.softuni.bg
Software University Foundation
softuni.foundation
Software University @ Facebook
facebook.com/SoftwareUniversity
Software University Forums
forum.softuni.bg
39