SlideShare a Scribd company logo
1 of 50
Arrays, Lists, Stacks, Queues
Processing Sequences of Elements
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
1. Declaring and Creating Arrays
2. Accessing Array Elements
3. Reading and Printing Arrays at the Console
4. Iterating over Arrays Using for and foreach
5. Resizable Arrays: List<T>
6. Other Structures: Stack<T> and Queue<T>
7. LINQ Extension Methods for Collections
2
Declaring and
Creating Arrays
What are Arrays?
 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)
0 1 2 3 4Array of 5
elements
Element index
(position)
Element of an array
… … … … …
4
Declaring Arrays
 Declaration defines the type of the elements
 Square brackets [] mean "array"
 Examples:
 Declaring array of integers:
 Declaring array of strings:
int[] intArr;
string[] stringArr;
5
Creating Arrays
 Use the operator new
 Specify the array length (fixed number of elements)
 Example: creating (allocating) array of 5 integers:
myIntArray = new int[5];
myIntArray
managed heap
(dynamic memory)
0 1 2 3 4
… … … … …
6
Creating and Initializing Arrays
 Creating and initializing can be done in a single statement:
 The new operator is not required when using curly brackets
initialization
myIntArray = {1, 2, 3, 4, 5};
myIntArray
managed heap
(dynamic memory)
0 1 2 3 4
1 2 3 4 5
7
8
 Creating an array to hold the names of the days of the week
Creating Array – Example
string[] daysOfWeek =
{
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
};
Accessing Array Elements
Read and Modify Elements by Index
How to Access Array Element?
 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
 Elements can be retrieved and changed by the [] operator
10
string[] arr = new string[2];
string arr[1] = "Maria";
arr[0] = arr[1];
Accessing Array Elements – Examples
11
string[] towns = { "Sofia", "Varna", "Bourgas" };
Console.WriteLine(towns); // System.String[]
Console.WriteLine(towns.Length); // 3
Console.WriteLine(towns[0]); // Sofia
Console.WriteLine(string.Join(", ", towns)); // Sofia, Varna,
Bourgas
towns[0] = "Pleven";
towns[2] = null;
Console.WriteLine(string.Join(", ", towns)); // Pleven, Varna,
Console.WriteLine(towns[3]); // IndexOutOfRangeException
towns.Length = 4; // Length is read-only
Accessing Elements By Index
Live Demo
Arrays: Input and Output
Reading and Printing Arrays on the Console
14
 First, read from the console the length of the array
 Next, create the array of given size n and read its elements:
Reading Arrays From the Console
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = int.Parse(Console.ReadLine());
}
15
 We can also read all array values separated by a space
 Or even write the above at a single line:
Reading Array Values at a Single Line
string values = Console.ReadLine();
string[] items = values.Split(' ');
int[] arr = new int[items.Length];
for (int i = 0; i < items.Length; i++)
{
arr[i] = int.Parse(items[i]);
}
int[] arr = Console.ReadLine().Split(' ')
.Select(int.Parse).ToArray();
Printing Arrays on the Console
 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
Console.WriteLine(element[{0}] = {1}",
index, array[index]);
}
16
Printing with String.Join(…) / ForEach(…)
 Use string.Join(separator, collection) to print an array:
 Or use the functional-style for-each:
int[] arr = { 1, 2, 3 };
Console.WriteLine(string.Join(", ", arr)); // 1, 2, 3
string[] strings = { "one", "two", "three" };
Console.WriteLine(string.Join("-", strings)); // one-two-three
17
int[] arr = { 1, 2, 3 };
arr.ToList().ForEach(a => Console.WriteLine(a));
Printing Arrays
Live Demo
Processing Array Elements
Using for and foreach
20
 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
 In the loop body use the element at the loop index
(array[index]):
Processing Arrays: for Statement
for (int index = 0; index < array.Length; index++)
{
squares[index] = array[index] * array[index];
}
21
 Printing array of integers in reversed order:
 Initialize array elements with their index:
Processing Arrays Using for Loop – Examples
int[] arr = new int[] {1, 2, 3, 4, 5};
Console.WriteLine("Reversed: ");
for (int i = array.Length - 1; i >= 0; i--)
Console.Write(array[i] + " ");
// Result: 5 4 3 2 1
for (int index = 0; index < array.Length; index++)
{
array[index] = index;
}
Processing Arrays: foreach
 How the foreach loop works?
 type – the type of the element
 value – local name of a variable
 collection – the collection/array to iterate
 Used when no indexing is needed
 All elements are accessed sequentially
 Elements can not be modified (read only)
foreach (type value in collection)
22
23
 Print all elements of a string[] array:
Processing Arrays Using foreach – Example
string[] capitals =
{
"Sofia",
"Washington",
"London",
"Paris"
};
foreach (string capital in capitals)
{
Console.WriteLine(capital);
}
Processing Arrays
Live Demo
Static Methods in the Array Class
 Array.Clear(arr, index, length) – deletes all elements
 Array.ConvertAll(arr, convertFunction)
 Converts an array of one type to an array of another type
 Array.IndexOf(arr, item)
 Finds an item in array (returns the first occurrence index or -1)
 Array.Reverse() – reverses the elements order
 Array.Sort() – sorts an array in increasing order
25
Array Static Methods
Live Demo
Exercises in Class
Resizable Arrays
List<T>
29
 List<T> – array that can resize dynamically
 Can add / remove / insert elements
 Also provides indexed access with [] (like arrays)
 T is the type for the list elements
 E.g. List<int> will hold integers, List<object> will hold objects
 Basic properties
 Count – returns the current size of the list
 Capacity – returns the current capacity of the list
Lists (Resizable Arrays)
30
 This code:
 Is like this:
 The main difference
 The number of elements in List<T> is variable
List Example
List<int> intList = new List<int>();
for (int i = 0; i < 5; i++)
intList.Add(i);
int[] intArray = new int[5];
for (int i = 0; i < 5; i++)
intArray[i] = i;
Lists <T>
Live Demo
32
 List<T> internally keeps its items in an array – T[]
 It has bigger Capacity (buffer) than the elements inside (Count)
 Typically "Add" is fast  just adds an element is an empty cell
 Resizing is slow, but happens rarely: log2(n) times
How The List<T> Works?
3 -2 5 11 9 -1 7 33 8
List<int>:
Count = 9
Capacity = 15
Capacity
used buffer
(Count)
unused
buffer
Resizing Lists
Live Demo
List<T> Methods
Brief Overview
35
 List<T>.Add(item) – adds an item to the end
 List<T>.AddRange(items) – adds many items at the end
 List<T>.Clear() – clears the list
 List<T>.IndexOf(item) – search for item
 Return the first occurrence index or -1
 List<T>.Insert(item, index) – inserts an item at position
 List<T>.InsertRange(items, index)
 Inserts many items at specified position
List<T> Methods (1)
36
 List<T>.Remove()
 Removes the first occurrence of a specific item
 List<T>.RemoveAt()
 Removes the element at the specified index
 List<T>.Reverse()
 List<T>.Sort()
 List<T>.ToArray()
List<T> Methods (2)
37
 Stack is last-in-first-out (LIFO) collection of elements
Stack – LIFO Data Structure
38
 Stack<T> holds a stack of elements
 Count – the number of elements in the Stack<T>
 Peek() – check the value of the last element
 Pop() – return the last element and remove it from the stack
 Push() – add an element to the Stack<T>
 ToArray() – converts list to array
 Contains() – determines whether an element is in the stack
Stack<T>
Working with Stacks
Live Demo
40
 Queue is first-in-first-out (FIFO) collection of elements
Queue – FIFO Data Structure
41
 Queue<T> holds a queue of elements:
 Enqueue() – add an element at the end of the queue
 Dequeue() – remove the first element and remove it
 Count – return the number of elements in the queue
 Peek() – check the value of the first element
 ToArray() – converts the queue to array
 Contains() – checks whether an element is in the queue
Queue<T>
Queue<T>
Live Demo
LINQ Extension Methods
for Collections
Brief Overview
44
 What are extension methods?
 Attach functionality to existing types
 How to use LINQ extension methods?
 Add "using System.Linq;" at the start of your C# file
 Call them as you call a regular instance method
Using System.LINQ with collections
var array = {1, 2, 3, 4, 5};
Console.WriteLine(array.Sum()); // 15
Console.WriteLine(array.Max()); // 5
45
 Distinct() – returns the distinct elements from a sequence
 First() and FirstOrDefault()
 Intersect() and Union()
 Min(), Max(), Sum() and Average()
 Skip() – bypasses a specified number of elements in a
sequence and then returns the remaining elements
 Take() – returns a specified number of contiguous elements
from the start of a sequence
LINQ Extension Methods
LINQ Extension Methods
Live Demo
Summary
 Arrays are a fixed-length sequences of elements of the same type
 Array elements are accessible by index (read / modify)
 Iterate over array elements with for and foreach loops
 List<T> holds resizable arrays
 Good when we don't know the number of elements initially
 Stack<T> and Queue<T> provides LIFO and FIFO lists
 LINQ extension methods attach additional functionality for
collection processing
47
?
Arrays, Lists, Stacks, Queues
https://softuni.bg/courses/advanced-csharp
License
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
 Attribution: this work may contain portions from
 "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license
 "C# Part I" course by Telerik Academy under CC-BY-NC-SA license
 "C# Part II" course by Telerik Academy under CC-BY-NC-SA license
49
Free Trainings @ Software University
 Software University Foundation – softuni.org
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University @ YouTube
 youtube.com/SoftwareUniversity
 Software University Forums – forum.softuni.bg

More Related Content

What's hot

13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: ArraysSvetlin Nakov
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersKimikazu Kato
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsJames Brotsos
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and ClassesSvetlin Nakov
 
INTRODUCTION TO MATLAB session with notes
  INTRODUCTION TO MATLAB   session with  notes  INTRODUCTION TO MATLAB   session with  notes
INTRODUCTION TO MATLAB session with notesInfinity Tech Solutions
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)gekiaruj
 
Machine learning with scikit-learn
Machine learning with scikit-learnMachine learning with scikit-learn
Machine learning with scikit-learnQingkai Kong
 
The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheetanand_study
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2Hang Zhao
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data scienceJohn Cant
 

What's hot (20)

13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
Parameters
ParametersParameters
Parameters
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning Programmers
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loops
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
INTRODUCTION TO MATLAB session with notes
  INTRODUCTION TO MATLAB   session with  notes  INTRODUCTION TO MATLAB   session with  notes
INTRODUCTION TO MATLAB session with notes
 
Chapter 3 Arrays in Java
Chapter 3 Arrays in JavaChapter 3 Arrays in Java
Chapter 3 Arrays in Java
 
Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
 
Machine learning with scikit-learn
Machine learning with scikit-learnMachine learning with scikit-learn
Machine learning with scikit-learn
 
The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheet
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Python Cheat Sheet
Python Cheat SheetPython Cheat Sheet
Python Cheat Sheet
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 

Similar to 16. Arrays Lists Stacks Queues

arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01Abdul Samee
 
Arrays in python
Arrays in pythonArrays in python
Arrays in pythonmoazamali28
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09Terry Yoast
 
Aj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructuresAj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructuresArthik Daniel
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structuresmaznabili
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
 
The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212Mahmoud Samir Fayed
 
COLLECTIONS.pptx
COLLECTIONS.pptxCOLLECTIONS.pptx
COLLECTIONS.pptxSruthyPJ
 
ARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptxARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptxDarellMuchoko
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In ScalaKnoldus Inc.
 

Similar to 16. Arrays Lists Stacks Queues (20)

07 Arrays
07 Arrays07 Arrays
07 Arrays
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
 
07 java collection
07 java collection07 java collection
07 java collection
 
Chap09
Chap09Chap09
Chap09
 
Aj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructuresAj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructures
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Scala collection
Scala collectionScala collection
Scala collection
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
COLLECTIONS.pptx
COLLECTIONS.pptxCOLLECTIONS.pptx
COLLECTIONS.pptx
 
ACP-arrays.pptx
ACP-arrays.pptxACP-arrays.pptx
ACP-arrays.pptx
 
ARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptxARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptx
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In Scala
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
 

More from Intro C# Book

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversalIntro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming CodeIntro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem SolvingIntro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming CodeIntro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 

More from Intro C# Book (20)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 

Recently uploaded

Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMartaLoveguard
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Lucknow
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
Complet Documnetation for Smart Assistant Application for Disabled Person
Complet Documnetation   for Smart Assistant Application for Disabled PersonComplet Documnetation   for Smart Assistant Application for Disabled Person
Complet Documnetation for Smart Assistant Application for Disabled Personfurqan222004
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Roomdivyansh0kumar0
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 

Recently uploaded (20)

Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptx
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Complet Documnetation for Smart Assistant Application for Disabled Person
Complet Documnetation   for Smart Assistant Application for Disabled PersonComplet Documnetation   for Smart Assistant Application for Disabled Person
Complet Documnetation for Smart Assistant Application for Disabled Person
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 

16. Arrays Lists Stacks Queues

  • 1. Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University http://softuni.bg
  • 2. Table of Contents 1. Declaring and Creating Arrays 2. Accessing Array Elements 3. Reading and Printing Arrays at the Console 4. Iterating over Arrays Using for and foreach 5. Resizable Arrays: List<T> 6. Other Structures: Stack<T> and Queue<T> 7. LINQ Extension Methods for Collections 2
  • 4. What are Arrays?  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) 0 1 2 3 4Array of 5 elements Element index (position) Element of an array … … … … … 4
  • 5. Declaring Arrays  Declaration defines the type of the elements  Square brackets [] mean "array"  Examples:  Declaring array of integers:  Declaring array of strings: int[] intArr; string[] stringArr; 5
  • 6. Creating Arrays  Use the operator new  Specify the array length (fixed number of elements)  Example: creating (allocating) array of 5 integers: myIntArray = new int[5]; myIntArray managed heap (dynamic memory) 0 1 2 3 4 … … … … … 6
  • 7. Creating and Initializing Arrays  Creating and initializing can be done in a single statement:  The new operator is not required when using curly brackets initialization myIntArray = {1, 2, 3, 4, 5}; myIntArray managed heap (dynamic memory) 0 1 2 3 4 1 2 3 4 5 7
  • 8. 8  Creating an array to hold the names of the days of the week Creating Array – Example string[] daysOfWeek = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
  • 9. Accessing Array Elements Read and Modify Elements by Index
  • 10. How to Access Array Element?  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  Elements can be retrieved and changed by the [] operator 10 string[] arr = new string[2]; string arr[1] = "Maria"; arr[0] = arr[1];
  • 11. Accessing Array Elements – Examples 11 string[] towns = { "Sofia", "Varna", "Bourgas" }; Console.WriteLine(towns); // System.String[] Console.WriteLine(towns.Length); // 3 Console.WriteLine(towns[0]); // Sofia Console.WriteLine(string.Join(", ", towns)); // Sofia, Varna, Bourgas towns[0] = "Pleven"; towns[2] = null; Console.WriteLine(string.Join(", ", towns)); // Pleven, Varna, Console.WriteLine(towns[3]); // IndexOutOfRangeException towns.Length = 4; // Length is read-only
  • 12. Accessing Elements By Index Live Demo
  • 13. Arrays: Input and Output Reading and Printing Arrays on the Console
  • 14. 14  First, read from the console the length of the array  Next, create the array of given size n and read its elements: Reading Arrays From the Console int n = int.Parse(Console.ReadLine()); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = int.Parse(Console.ReadLine()); }
  • 15. 15  We can also read all array values separated by a space  Or even write the above at a single line: Reading Array Values at a Single Line string values = Console.ReadLine(); string[] items = values.Split(' '); int[] arr = new int[items.Length]; for (int i = 0; i < items.Length; i++) { arr[i] = int.Parse(items[i]); } int[] arr = Console.ReadLine().Split(' ') .Select(int.Parse).ToArray();
  • 16. Printing Arrays on the Console  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 Console.WriteLine(element[{0}] = {1}", index, array[index]); } 16
  • 17. Printing with String.Join(…) / ForEach(…)  Use string.Join(separator, collection) to print an array:  Or use the functional-style for-each: int[] arr = { 1, 2, 3 }; Console.WriteLine(string.Join(", ", arr)); // 1, 2, 3 string[] strings = { "one", "two", "three" }; Console.WriteLine(string.Join("-", strings)); // one-two-three 17 int[] arr = { 1, 2, 3 }; arr.ToList().ForEach(a => Console.WriteLine(a));
  • 20. 20  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  In the loop body use the element at the loop index (array[index]): Processing Arrays: for Statement for (int index = 0; index < array.Length; index++) { squares[index] = array[index] * array[index]; }
  • 21. 21  Printing array of integers in reversed order:  Initialize array elements with their index: Processing Arrays Using for Loop – Examples int[] arr = new int[] {1, 2, 3, 4, 5}; Console.WriteLine("Reversed: "); for (int i = array.Length - 1; i >= 0; i--) Console.Write(array[i] + " "); // Result: 5 4 3 2 1 for (int index = 0; index < array.Length; index++) { array[index] = index; }
  • 22. Processing Arrays: foreach  How the foreach loop works?  type – the type of the element  value – local name of a variable  collection – the collection/array to iterate  Used when no indexing is needed  All elements are accessed sequentially  Elements can not be modified (read only) foreach (type value in collection) 22
  • 23. 23  Print all elements of a string[] array: Processing Arrays Using foreach – Example string[] capitals = { "Sofia", "Washington", "London", "Paris" }; foreach (string capital in capitals) { Console.WriteLine(capital); }
  • 25. Static Methods in the Array Class  Array.Clear(arr, index, length) – deletes all elements  Array.ConvertAll(arr, convertFunction)  Converts an array of one type to an array of another type  Array.IndexOf(arr, item)  Finds an item in array (returns the first occurrence index or -1)  Array.Reverse() – reverses the elements order  Array.Sort() – sorts an array in increasing order 25
  • 29. 29  List<T> – array that can resize dynamically  Can add / remove / insert elements  Also provides indexed access with [] (like arrays)  T is the type for the list elements  E.g. List<int> will hold integers, List<object> will hold objects  Basic properties  Count – returns the current size of the list  Capacity – returns the current capacity of the list Lists (Resizable Arrays)
  • 30. 30  This code:  Is like this:  The main difference  The number of elements in List<T> is variable List Example List<int> intList = new List<int>(); for (int i = 0; i < 5; i++) intList.Add(i); int[] intArray = new int[5]; for (int i = 0; i < 5; i++) intArray[i] = i;
  • 32. 32  List<T> internally keeps its items in an array – T[]  It has bigger Capacity (buffer) than the elements inside (Count)  Typically "Add" is fast  just adds an element is an empty cell  Resizing is slow, but happens rarely: log2(n) times How The List<T> Works? 3 -2 5 11 9 -1 7 33 8 List<int>: Count = 9 Capacity = 15 Capacity used buffer (Count) unused buffer
  • 35. 35  List<T>.Add(item) – adds an item to the end  List<T>.AddRange(items) – adds many items at the end  List<T>.Clear() – clears the list  List<T>.IndexOf(item) – search for item  Return the first occurrence index or -1  List<T>.Insert(item, index) – inserts an item at position  List<T>.InsertRange(items, index)  Inserts many items at specified position List<T> Methods (1)
  • 36. 36  List<T>.Remove()  Removes the first occurrence of a specific item  List<T>.RemoveAt()  Removes the element at the specified index  List<T>.Reverse()  List<T>.Sort()  List<T>.ToArray() List<T> Methods (2)
  • 37. 37  Stack is last-in-first-out (LIFO) collection of elements Stack – LIFO Data Structure
  • 38. 38  Stack<T> holds a stack of elements  Count – the number of elements in the Stack<T>  Peek() – check the value of the last element  Pop() – return the last element and remove it from the stack  Push() – add an element to the Stack<T>  ToArray() – converts list to array  Contains() – determines whether an element is in the stack Stack<T>
  • 40. 40  Queue is first-in-first-out (FIFO) collection of elements Queue – FIFO Data Structure
  • 41. 41  Queue<T> holds a queue of elements:  Enqueue() – add an element at the end of the queue  Dequeue() – remove the first element and remove it  Count – return the number of elements in the queue  Peek() – check the value of the first element  ToArray() – converts the queue to array  Contains() – checks whether an element is in the queue Queue<T>
  • 43. LINQ Extension Methods for Collections Brief Overview
  • 44. 44  What are extension methods?  Attach functionality to existing types  How to use LINQ extension methods?  Add "using System.Linq;" at the start of your C# file  Call them as you call a regular instance method Using System.LINQ with collections var array = {1, 2, 3, 4, 5}; Console.WriteLine(array.Sum()); // 15 Console.WriteLine(array.Max()); // 5
  • 45. 45  Distinct() – returns the distinct elements from a sequence  First() and FirstOrDefault()  Intersect() and Union()  Min(), Max(), Sum() and Average()  Skip() – bypasses a specified number of elements in a sequence and then returns the remaining elements  Take() – returns a specified number of contiguous elements from the start of a sequence LINQ Extension Methods
  • 47. Summary  Arrays are a fixed-length sequences of elements of the same type  Array elements are accessible by index (read / modify)  Iterate over array elements with for and foreach loops  List<T> holds resizable arrays  Good when we don't know the number of elements initially  Stack<T> and Queue<T> provides LIFO and FIFO lists  LINQ extension methods attach additional functionality for collection processing 47
  • 48. ? Arrays, Lists, Stacks, Queues https://softuni.bg/courses/advanced-csharp
  • 49. License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license  "C# Part I" course by Telerik Academy under CC-BY-NC-SA license  "C# Part II" course by Telerik Academy under CC-BY-NC-SA license 49
  • 50. Free Trainings @ Software University  Software University Foundation – softuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University @ YouTube  youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bg

Editor's Notes

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  2. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  3. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  4. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  5. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  6. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  7. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  8. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  9. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  10. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*