Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.

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
Telerik School Academy ASP.NET MVC.
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
C# Fundamentals – Part I
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?
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.
NoSQL Concepts, Redis, MongoDB, CouchDB Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
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.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Course Introduction Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Telerik Software Academy End-to-end JavaScript Applications.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
Processing Sequences of Elements Svetlin Nakov Telerik Corporation
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.
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
Course Overview Doncho Minkov Telerik Software Academy Technical Trainer
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
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
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.
Creating and Initializing Arrays, Accessing Elements, Multiple Dimensions Learning & Development Team Telerik Software Academy.
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
Lists, Stacks, Queues Svetlin Nakov Telerik Software Academy Manager Technical Trainer
Processing Sequences of Elements
Presentation transcript:

Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2

1. Declaring and Creating Arrays 2. Accessing Array Elements 3. Console Input and Output of Arrays 4. Iterating Over Arrays Using for and foreach 5. Dynamic Arrays  List  List 6. Copying Arrays 2

 An array is a sequence of elements  All elements are of the same type  The order of the elements is fixed  Has fixed size ( Array.Length ) Array of 5 elements Element index Element of an array …………… 4

 Declaration defines the type of the elements  Square brackets [] mean "array"  Examples:  Declaring array of integers:  Declaring array of strings: int[] myIntArray; string[] myStringArray; 5

 Use the operator new  Specify array length  Example creating (allocating) array of 5 integers: myIntArray = new int[5]; myIntArray managed heap (dynamic memory) …………… 6

 Creating and initializing can be done together:  The new operator is not required when using curly brackets initialization myIntArray = {1, 2, 3, 4, 5}; myIntArray managed heap (dynamic memory)

 Creating an array that contains the names of the days of the week string[] daysOfWeek = { "Monday", "Monday", "Tuesday", "Tuesday", "Wednesday", "Wednesday", "Thursday", "Thursday", "Friday", "Friday", "Saturday", "Saturday", "Sunday" "Sunday"}; 8

Live Demo

Read and Modify Elements by Index 10

 Array elements are accessed using the square brackets operator [] (indexer)  Array indexer takes element’s index as parameter  The first element has index 0  The last element has index Length-1  Array elements can be retrieved and changed by the [] operator 11

 Reversing the contents of an array int[] array = new int[] {1, 2, 3, 4, 5}; // Get array size int length = array.Length; // Declare and create the reversed array int[] reversed = new int[length]; // Initialize the reversed array for (int index = 0; index < length; index++) { reversed[length-index-1] = array[index]; reversed[length-index-1] = array[index];} 12

Live Demo

Reading and Printing Arrays on the Console

 First, read from the console the length of the array  Next, create the array of given size and read its elements in a for loop int n = int.Parse(Console.ReadLine()); int[] arr = new int[n]; for (int i=0; i<n; i++) { arr[i] = int.Parse(Console.ReadLine()); arr[i] = int.Parse(Console.ReadLine());} 15

 Read int array from the console and check if it is symmetric: bool isSymmetric = true; for (int i=0; i<array.Length/2; i++) { if (array[i] != array[n-i-1]) if (array[i] != array[n-i-1]) { isSymmetric = false; isSymmetric = false; }}

Live Demo

 Process all elements of the array  Print each element to the console  Separate elements with white space or a new line string[] array = {"one", "two", "three"}; // Process all elements of the array for (int index = 0; index < array.Length; index++) { // Print each element on a separate line // Print each element on a separate line Console.WriteLine("element[{0}] = {1}", Console.WriteLine("element[{0}] = {1}", index, array[index]); index, array[index]);} 18

Live Demo

 Use for loop to process an array when  Need to keep track of the index  Processing is not strictly sequential from the first to the last element  In the loop body use the element at the loop index ( array[index] ): for (int index = 0; index < array.Length; index++) { squares[index] = array[index] * array[index]; squares[index] = array[index] * array[index];} 21

 Printing array of integers in reversed order:  Initialize all array elements with their corresponding index number: Console.WriteLine("Reversed: "); for (int i = array.Length-1; i >= 0; i--) { Console.Write(array[i] + " "); Console.Write(array[i] + " ");} // Result: for (int index = 0; index < array.Length; index++) { array[index] = index; array[index] = index;} 22

 How foreach loop works?  type – the type of the element  value – local name of variable  array – processing array  Used when no indexing is needed  All elements are accessed one by one  Elements can not be modified (read only) foreach (type value in array) 23

 Print all elements of a string[] array: string[] capitals = { "Sofia", "Sofia", "Washington", "Washington", "London", "London", "Paris" "Paris"}; foreach (string capital in capitals) { Console.WriteLine(capital); Console.WriteLine(capital);} 24

Live Demo

List<T>

 List – array that can resize dynamically  When adding or removing elements  Also have indexers [] (like arrays)  T is the type that the list will hold  E.g. List will hold integers  List will hold objects  Basic methods and properties  Add(T element) – adds new element to the end  Remove(element) – removes the element  Count – returns the current size of the list 27

List intList = new List (); for( int i=0; i<5; i++) { intList.Add(i); intList.Add(i);} 28 int[] intArray = new int[5]; for( int i=0; i<5; i++) { intArray[i] = i; intArray[i] = i;}  Is the same as:  The main difference  When using lists we don't have to know the exact number of elements

 Lets have an array with capacity of 5 elements  If we want to add a sixth element (we have already added 5 ) we have to manually resize  With List we simply call 29 int[] intArray = new int[5]; int[] copyArray = intArray; int[] intArray = new int[6]; for (int i = 0; i < 5; i++) { intArray[i] = copyArray[i]; intArray[i] = copyArray[i];} intArray[5] = newValue; list.Add(newValue);

Live Demo

 Why adding new elements is not slow?  When adding n elements in List it resizes itself log (2) n times instead of n  Initially a new List has size of 0 elements  Counter for total capacity (Capacity)  Counter for number of used capacity (Count)  When created, both properties of the list have values of 0  When adding the first element Count becomes 1 and Capacity becomes 4 31

 Initially the List is empty  When adding new element it is resized  But not every time  Only when it is needed  Lets have a list with 3 elements  It looks like this:  When we add new element it is appended to the end  Adding a fifth element doubles the Capacity of the list 32

Live Demo

The Array Class

 Sometimes we must copy the values from one array to another one  If we do it the intuitive way we would copy not only the values but the reference to the array  Changing some of the values in one array will affect the other  The way to avoid this is using Clone()  This way only the values will be copied but not the reference int[] copyArray = (int[])array.Clone(); int[] copyArray = array; 35

 Arrays are a fixed-length sequences of elements of the same type  Array elements are accessible by index  Can be read and modified  Iteration over array elements can be done with for and foreach loops  List holds resizable arrays  Good when we don't know the number of elements initially 36

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен 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# Николай Костов - блог за програмиране

 “C# Telerik Academy  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com forums.academy.telerik.com