Creating and Initializing Arrays, Accessing Elements, Multiple Dimensions Learning & Development Team Telerik Software Academy.

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Make swiftly iOS development Telerik Academy Telerik Academy Plus.
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Asynchronous Programming with C# and WinRT
Unleash the Power of JavaScript Tooling Telerik Software Academy End-to-end JavaScript Applications.
Touch and Gestures with Xamarin Forms
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
C++ for Engineers and Scientists Third Edition
With Mocha and Karma Telerik Academy Telerik Software Academy.
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
1.7 Arrays academy.zariba.com 1. Lecture Content 1.Basic Operations with Arrays 2.Console Input & Output of Arrays 3.Iterating Over Arrays 4.List 5.Cloning.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Optimization problems, Greedy Algorithms, Optimal Substructure and Greedy choice Learning & Development Team Telerik Software.
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Brief Overview of Combinations, Permutations and Binary Vectors Nikolay Kostov Telerik Corporation Technical Trainer.
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Telerik Software Academy End-to-end JavaScript Applications.
What is a Database, MySQL Specifics Trần Anh Tuấn Edit from Telerik Software Academy
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
Language enhancements and additions Learning & Development Team Telerik Software Academy.
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team Telerik.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Processing Sequences of Elements Technical Trainer Telerik Corporation Doncho Minkov.
Telerik Software Academy Databases.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
Data Structures and Algorithms Telerik Software Academy
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Definition, Constructors, Methods, Access Modifiers, Static/Instance members, Learning & Development Team Telerik Software Academy.
Processing Sequences of Elements
Presentation transcript:

Creating and Initializing Arrays, Accessing Elements, Multiple Dimensions Learning & Development Team Telerik Software Academy

1. What are Arrays? 2. Declaring and Initializing Arrays 3. Accessing Array Elements 4. Array Input and Output 5. Multidimensional Arrays 6. STL vectors 2

Compound Data

 Arrays are collections of data (variables)  Under the same name  Sequential  All members have an index  i.e. number/position  Each member is accessed through  The array name  Combined with the member's index  "Members" are also called "elements"

 What an int array looks like (sort of)  Sequence of int variables, each with a value  Each variable has an index, starting at 0 (zero)  E.g. variable at index 1 has a value of 10  An array can be of any type  char, string, double, etc.  But only one type – cannot mix different types Index Value int a[6] = {13, 10, 5, 100, -3, 1000};

 Arrays are essential to programming  Allow group operations (i.e. looping through) on elements  Part of many fundamental algorithms  Easy to manage by just tracking indices  Can represent real life concepts  Queues, Grades of students, Protons per element in the Periodic table, etc.

Creating C++ arrays

 Array declaration requires  Data type, Identifier  Array size (could be inferred from initialization)  If defined, array size must be constant  Declared arrays assume random values  When they are not initialized  And are local to functions  Memory is always assigned at declaration int numberArray[5]; //"undefined" values char characterArray[2];//"undefined" values

 Array initialization  Values provided in braces {}, size can be skipped  If array size is given explicitly  Items in braces less than (or equal to) array size  If number of items is less than array size  Remaining items initialized to default values int numberArray[5] = {42, 13, 7, -1, 5}; int characterArray[] = {'a', 'z'}; //array has size 2 int someDefaults[3] = {1}; //array has values 1, 0, 0 int allDefaults[3] = {}; //array has values 0, 0, 0 int initListArr[] {1, 2, 3}; //using an initializer list //initializer list only available at declaration until C++11

 Looping through arrays also a popular method  E.g. initializing with square roots of the indices  Once created, an array cannot be re-assigned  Only way to create an array is declaration  i.e. no way to assign an array to a variable const int N = 100;... double arr[N]; for(int i=0; i<N; i++) { arr[i] = sqrt(i); }

Live Demo

Reading and Writing the Values of Arrays

 Elements are accessed through their index  Index is placed inside brackets []  Indexing starts from 0 to the size of the array  Access is both read and write int numberArray[5] = {42, 13, 7, -1, 5}; cout<numberArray[1]<<endl; //prints 13 numberArray[1] = 9; numberArray[3] += numberArray[1]; cout<<numberArray[1]; //prints 9 cout<<endl; cout<<numberArray[3]; //prints 8

 Loops can provide an arbitrary number of executions of a piece of code  Arrays can provide an arbitrary number of elements  Hence, arrays and loops are often used together  i.e. starting a loop going through each index  Often called "iterating" or "traversing" an array

 Example: sum of elements of an array const int numElements = 10; int arr[numElements] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; int sum = 0; for(int i=0; i<numElements; i++) { sum += arr[i]; sum += arr[i];}cout<<sum;

 Example: reversing an array const int numElements = 11; int arr[numElements] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; for(int i=0; i<numElements/2; i++) { int mirrorIndex = numElements - i - 1; int mirrorIndex = numElements - i - 1; int currentIndexValue = arr[i]; int currentIndexValue = arr[i]; arr[i] = arr[mirrorIndex]; arr[i] = arr[mirrorIndex]; arr[mirrorIndex] = currentIndexValue; arr[mirrorIndex] = currentIndexValue; ///or just use the built-in swap method ///or just use the built-in swap method //swap(arr[i], arr[mirrorIndex]); //swap(arr[i], arr[mirrorIndex]);} //arr is now {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Live Demo

 When accessing by index in an array of size N  The following bounds for index apply: 0 <= index < N  Arrays are not protected against bad indices  Neither compile-time nor runtime  Exceeding array bounds is not defined in the standard, i.e. unpredictable

 Common results of accessing outside the array  You access some part of the program's memory – the access will be successful  Very hard to track this type of error  You access memory outside the program's address space – the OS should deny access  Error 0xC in Windows  Don't rely on that, it could be a fatal error for an unprotected system

Live Demo

Reading and Printing Arrays on the Console

 Need to know the max size the array can be  Usually known in algorithmic problems  Further on, we will discuss how to do it even without knowing the max size in advance  Create an array with the max size  Read the actual number of elements  Start a loop and input each of the elements  Using the loop's "control variable"  for loops are good for this 22

 Example of Reading an Array from the Console const int MAX_SIZE = 100; //asume we know it //need to initialize array with constant expression int arr[MAX_SIZE]; int actualSize = 0; cin>>actualSize; for (int i=0; i<actualSize; i++) { cin>>arr[i]; cin>>arr[i];}

 Assume we know the array size  Probably stored it on creation  Loop through each element index in the array  Print each element to the console const int numElements = 5;... int arr[numElements] =... for (int index = 0; index < numElements; index++) { // Print each element on a separate line // Print each element on a separate line cout << arr[index] << endl; cout << arr[index] << endl;} 24

Live Demo

Arrays of arrays, Representing Tabular Data

 Multidimensional arrays are arrays of arrays  Every element of the array is an array itself  Nesting can be as deep as needed (3D, 4D …)  Useful for multi-dimensional data, e.g. tables IndexValue IndexValue 0index01234 value index01234 value index01234 value43210 int array 2D int array

 2D arrays  Represent tables, mathematical matrices, etc.  A 2D array is usually called a "matrix"  Usually perceived as tables/spreadsheets Second dimension (columns) First dimension (rows)

Live Demo

 3D arrays  Represent matrices with more than one value per cell (e.g. an RGB image)  Some representations of objects in 3D space  Sometimes called "cubes" Note: blurred by magnification

 Declaring multidimensional arrays  Just like normal arrays, with an extra pair of []  Initializing multidimensional arrays  The {} are filled with initializations of arrays  If provided arrays are less, default values are assigned int matrix[10][15]; //creates a 2D int array containing //10 one-dimensional int arrays, //10 one-dimensional int arrays, //each 15 elements long //each 15 elements long //Simply said a 2D array with 10 rows and 15 cols int m[2][3] = { {1, 2, 3}, {1, 2, 3}, {4, 5, 6} {4, 5, 6}} m

 Accessing elements of multidimensional arrays  Multidimensional arrays contain other arrays  Additional [] for each additional dimension  E.g. mat[5][3] accesses the 3 rd element of the 5 th array in mat  In other words, the cell at 5 th row and 3 rd column int m[2][3] = { {1, 2, 3}, {4, 5, 6} } cout<<m[0][0]; //prints 1 cout<<m[1][2]; //prints 6 cout<<m[1]; //prints the memory address of the second //array ({4,5,6}) in m //array ({4,5,6}) in m

 Traversing multidimensional arrays  Extra nested loop for traversing each dimension  Reading a matrix from the console  Printing matrices is similar (consider new lines) const int ROWS =..., COLS =...; int matrix[ROWS][COLS]; for(int row = 0; row < ROWS; row++) { for(int col = 0; col < COLS; col++) for(int col = 0; col < COLS; col++) { cin>>matrix[row][col]; cin>>matrix[row][col]; }}

Syntax, How it Works

 Arrays can be parameters for functions  Array data itself is not passed  Instead, a "reference" is passed  Much faster than copying the entire array  A reference points to the original object  Modifying a reference in the function leads to modifying the object  i.e. changing array elements effects the array in the caller

 Syntax for passing an array as a parameter  Much like declaration syntax  Size of first dimension can be omitted  i.e. normal (1D) arrays can have empty [] int Sum(int arr[], int numElements) { int sum = 0; int sum = 0; for(int i=0; i<numElements; i++) for(int i=0; i<numElements; i++) { sum += arr[i]; sum += arr[i]; } return sum; return sum;} int main() { int numbers[] = {1,2,3}; int numbers[] = {1,2,3}; cout<<Sum(numbers, 3); //prints 6 cout<<Sum(numbers, 3); //prints 6}

 Syntax for passing 2D array as a parameter  Multi-dimensional arrays need to specify size in each dimension, except the first int Print3ColMatrix(int matrix[][3], int rows) { for(int row = 0; row < rows; row++) { for(int row = 0; row < rows; row++) { for(int col = 0; col < 3; col++) { for(int col = 0; col < 3; col++) { cout<<matrix[row][col] cout<<matrix[row][col] } cout << endl; //new line for each row cout << endl; //new line for each row }} int main() { int matrix[2][3] = {{1,2,3},{4,5,6}}; int matrix[2][3] = {{1,2,3},{4,5,6}}; Print3ColMatrix(matrix, 2); Print3ColMatrix(matrix, 2);}

Live Demo

Using the STL vector, Array vs. Vector

 The typical C++ array has a very big problem  Declared and allocated with a constant size  i.e. cannot instantiate an array based on input  Dynamic Array  Concept in programming as a whole  Can change its size – grow, shrink (fast)  And knows its size  Can have elements added and removed (fast)  Has all functionality of a normal array

 The Standard Template Library has a template for a dynamic array  vector, where T can be any type  Can grow indefinitely (depends on RAM)  Initialized dynamically (E.g. based on input)  Declaring and initializing a vector #include //required header … vector numbers; numbers.push_back(42); //numbers is now {42} numbers.push_back(13); //numbers is now {42, 13} int consoleNumber; cin>>consoleNumber; numbers.push_back(consoleNumber)

Live Demo

 Accessing vector elements  Done the same way as with arrays, i.e. []  Vector size and can be obtained by calling size() vector numbers; numbers.push_back(42);numbers.push_back(13); cout<<numbers[1]; //prints 13 cout<<endl; numbers[1] = numbers[0]; cout<<numbers[1]; //prints 42 vector numbers; numbers.push_back(42);numbers.push_back(13); cout<<numbers.size(); //prints 2

 Vectors vs. Arrays  Vectors are dynamic, with fast resize  Vector parameters are copied (slow)  Except when parameter is a reference (fast)  Vectors allocate in dynamic memory (default)  Arrays are allocated on the stack – much smaller  Large arrays can cause a Stack overflow, vectors are safe in this manner  Vectors allocate twice the memory needed  Not all of the time, can be manually "fixed"

Live Demo

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране

1. Write a program that allocates array of 20 integers and initializes each element by its index multiplied by 5. Print the obtained array on the console. 2. Write a program that reads two arrays from the console and compares them element by element. 3. Write a program that compares two char arrays lexicographically (letter by letter). 4. Write a program that finds the maximal sequence of equal elements in an array. Example: {2, 1, 1, 2, 3, 3, 2, 2, 2, 1}  {2, 2, 2}. 47

5. Write a program that finds the maximal increasing sequence in an array. Example: {3, 2, 3, 4, 2, 2, 4}  {2, 3, 4}. 6. Write a program that reads two integer numbers N and K and an array of N elements from the console. Find in the array those K elements that have maximal sum. 7. Sorting an array means to arrange its elements in increasing order. Write a program to sort an array. Use the "selection sort" algorithm: Find the smallest element, move it at the first position, find the smallest from the rest, move it at the second position, etc. 48

8. Write a program that finds the sequence of maximal sum in given array. Example: {2, 3, -6, -1, 2, -1, 6, 4, -8, 8}  {2, -1, 6, 4} Can you do it with only one loop (with single scan through the elements of the array)? 9. Write a program that finds the most frequent number in an array. Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3}  4 (5 times) 10. Write a program that finds in given array of integers a sequence of given sum S (if present). Example: {4, 3, 1, 4, 2, 5, 8}, S=11  {4, 2, 5} 49

11. Write a program that finds the index of given element in a sorted array of integers by using the binary search algorithm (find it in Wikipedia). binary search binary search 12. Write a program that finds all prime numbers in the range [ ]. Use the sieve of Eratosthenes algorithm (find it in Wikipedia). sieve of Eratosthenessieve of Eratosthenes 50