SlideShare a Scribd company logo
1 of 45
Arrays
Processing Sequences of Elements
Doncho Minkov
Telerik Software Academy
academy.telerik.com
TechnicalTrainer
http://minkov.it/
Table of Contents
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<T>
 Copying Arrays
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
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[] myIntArray;
string[] myStringArray;
5
Creating Arrays
 Use the operator new
 Specify array length
 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 together:
 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
Creating Array – Example
 Creating an array that contains the names of
the days of the week
string[] daysOfWeek =
{
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
};
8
Days ofWeek
Live Demo
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
 Array elements can be retrieved and changed
by the [] operator
11
Reversing an Array – Example
 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];
}
12
Reversing an Array
Live Demo
Arrays: Input and Output
Reading and Printing Arrays on the Console
Reading Arrays From 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());
}
15
Symmetry Check – Example
 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])
{
isSymmetric = false;
}
}
1 2 3 2 11 2 2 1 1 2 3 3 2 1
16
Symmetry Check
Live Demo
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]);
}
18
Printing Arrays
Live Demo
Processing Array Elements
Using for and foreach
Processing Arrays: for Statement
 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];
}
21
Processing Arrays Using
for Loop – Examples
 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] + " ");
}
// Result: 5 4 3 2 1
for (int index = 0; index < array.Length; index++)
{
array[index] = index;
}
22
Processing Arrays: foreach
 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
Processing Arrays Using
foreach – Example
 Print all elements of a string[] array:
string[] capitals =
{
"Sofia",
"Washington",
"London",
"Paris"
};
foreach (string capital in capitals)
{
Console.WriteLine(capital);
}
24
Processing Arrays
Live Demo
Resizable Arrays
List<T>
Lists (Resizable Arrays)
 List<T> – 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<int> will hold integers
 List<object> 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 Example
List<int> intList = new List<int>();
for( int i=0; i<5; i++)
{
intList.Add(i);
}
28
int[] intArray = new int[5];
for( int i=0; i<5; 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
Lists vs. Arrays
 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<T> 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[5] = newValue;
list.Add(newValue);
Lists <T>
Live Demo
HowThe List<T> Works?
 Why adding new elements is not slow?
 When adding n elements in List<T> it resizes
itself log(2)n times instead of n
 Initially a new List<T> has size of 0 elements
 Counter for total capacity (Capacity)
 Counter for number of used capacity (Count)
 When created, Capacity is 4both properties of
the list have values of 0
 When adding the first element Count becomes
1 and Capacity becomes 4
31
HowThe List<T> Works? (2)
 Initially the List<T> 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
Resizing Lists
Live Demo
Copying Arrays
The Array Class
Copying Arrays
 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
Summary
 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<T> 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.NETMVC
безплатен курс"Разработка на софтуер в cloud среда"
BG Coder -онлайн състезателна система -online judge
курсове и уроци по програмиране,книги – безплатно отНаков
безплатен курс"Качествен програменкод"
алго академия – състезателно програмиране,състезания
ASP.NET курс -уеб програмиране,бази данни, C#,.NET,ASP.NET
курсове и уроци по програмиране– Телерик академия
курсмобилни приложения с iPhone, Android,WP7,PhoneGap
freeC#book, безплатна книга C#,книга Java,книга C#
Дончо Минков -сайт за програмиране
Николай Костов -блог за програмиране
C#курс,програмиране,безплатно
Arrays
http://academy.telerik.com
Exercises
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}.
38
Exercises (2)
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.
39
Exercises (3)
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}
40
Exercises (6)
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 inWikipedia).
12. Write a program that creates an array containing all
letters from the alphabet (A-Z). Read a word from
the console and print the index of each of its letters
in the array.
13. * Write a program that sorts an array of integers
using the merge sort algorithm (find it in Wikipedia).
14. Write a program that sorts an array of strings using
the quick sort algorithm (find it in Wikipedia).
41
15. Write a program that finds all prime numbers in the
range [1...10 000 000]. Use the sieve of Eratosthenes
algorithm (find it in Wikipedia).
16. *We are given an array of integers and a number S.
Write a program to find if there exists a subset of
the elements of the array that has a sum S.
Example:
arr={2, 1, 2, 4, 3, 5, 2, 6}, S=14  yes (1+2+5+6)
17. *Write a program that reads three integer numbers
N, K and S and an array of N elements from the
console. Find in the array a subset of K elements
that have sum S or indicate about its absence.
Exercises (7)
42
Exercises (8)
18. *Write a program that reads an array of integers
and removes from it a minimal number of elements
in such way that the remaining array is sorted in
increasing order. Print the remaining sorted array.
Example:
{6, 1, 4, 3, 0, 3, 6, 4, 5}  {1, 3, 3, 4, 5}
19. *Write a program that reads a number N and
generates and prints all the permutations of the
numbers [1 … N]. Example:
n = 3  {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2},
{3, 2, 1}
43
Exercises (9)
20. Write a program that reads two numbers N and K
and generates all the variations of K elements from
the set [1..N]. Example:
N = 3, K = 2  {1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3},
{3, 1}, {3, 2}, {3, 3}
21. Write a program that reads two numbers N and K
and generates all the combinations of K distinct
elements from the set [1..N]. Example:
N = 5, K = 2  {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, {2, 4},
{2, 5}, {3, 4}, {3, 5}, {4, 5}
44
FreeTrainings @Telerik Academy
 Fundamentals of C# Programming
Course
 csharpfundamentals.telerik.com
 Telerik Software Academy
 academy.telerik.com
 Telerik Academy @ Facebook
 facebook.com/TelerikAcademy
 Telerik Software Academy Forums
 forums.academy.telerik.com

More Related Content

What's hot

6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
irdginfo
 

What's hot (20)

6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Python Scipy Numpy
Python Scipy NumpyPython Scipy Numpy
Python Scipy Numpy
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
Arrays
ArraysArrays
Arrays
 
Lec3
Lec3Lec3
Lec3
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
Arrays
ArraysArrays
Arrays
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Arrays
ArraysArrays
Arrays
 
Data structure array
Data structure  arrayData structure  array
Data structure array
 

Viewers also liked

3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp013 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01
Abdul Samee
 
13 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp0213 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp02
Abdul Samee
 
Input outputdisplaydevices-140819061228-phpapp02
Input outputdisplaydevices-140819061228-phpapp02Input outputdisplaydevices-140819061228-phpapp02
Input outputdisplaydevices-140819061228-phpapp02
Abdul Samee
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
Abdul Samee
 
3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp013 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01
Abdul Samee
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
Garima Sareen Nagpal - CV
Garima Sareen Nagpal - CVGarima Sareen Nagpal - CV
Garima Sareen Nagpal - CV
Garima Sareen
 

Viewers also liked (12)

Freme general-overview-version-june-2015
Freme general-overview-version-june-2015Freme general-overview-version-june-2015
Freme general-overview-version-june-2015
 
Freme at feisgiltt 2015 freme use cases
Freme at feisgiltt 2015   freme use casesFreme at feisgiltt 2015   freme use cases
Freme at feisgiltt 2015 freme use cases
 
3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp013 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01
 
13 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp0213 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp02
 
Input outputdisplaydevices-140819061228-phpapp02
Input outputdisplaydevices-140819061228-phpapp02Input outputdisplaydevices-140819061228-phpapp02
Input outputdisplaydevices-140819061228-phpapp02
 
Fremeatfeisgiltt2015 fremelinkeddatalocalisers-150603090934-lva1-app6891
Fremeatfeisgiltt2015 fremelinkeddatalocalisers-150603090934-lva1-app6891Fremeatfeisgiltt2015 fremelinkeddatalocalisers-150603090934-lva1-app6891
Fremeatfeisgiltt2015 fremelinkeddatalocalisers-150603090934-lva1-app6891
 
Sasaki mlkrep-20150710
Sasaki mlkrep-20150710Sasaki mlkrep-20150710
Sasaki mlkrep-20150710
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
 
Linked data tooling XML
Linked data tooling XMLLinked data tooling XML
Linked data tooling XML
 
3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp013 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
Garima Sareen Nagpal - CV
Garima Sareen Nagpal - CVGarima Sareen Nagpal - CV
Garima Sareen Nagpal - CV
 

Similar to arrays-120712074248-phpapp01

Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 
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
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
Terry Yoast
 

Similar to arrays-120712074248-phpapp01 (20)

16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
 
Array
ArrayArray
Array
 
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
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
 
ARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptxARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptx
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Data structures and algorithms arrays
Data structures and algorithms   arraysData structures and algorithms   arrays
Data structures and algorithms arrays
 

Recently uploaded

Recently uploaded (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

arrays-120712074248-phpapp01

  • 1. Arrays Processing Sequences of Elements Doncho Minkov Telerik Software Academy academy.telerik.com TechnicalTrainer http://minkov.it/
  • 2. Table of Contents 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<T>  Copying Arrays 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 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[] myIntArray; string[] myStringArray; 5
  • 6. Creating Arrays  Use the operator new  Specify array length  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 together:  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 Array – Example  Creating an array that contains the names of the days of the week string[] daysOfWeek = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; 8
  • 10. Accessing Array Elements Read and Modify Elements by Index 10
  • 11. 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  Array elements can be retrieved and changed by the [] operator 11
  • 12. Reversing an Array – Example  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]; } 12
  • 14. Arrays: Input and Output Reading and Printing Arrays on the Console
  • 15. Reading Arrays From 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()); } 15
  • 16. Symmetry Check – Example  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]) { isSymmetric = false; } } 1 2 3 2 11 2 2 1 1 2 3 3 2 1 16
  • 18. 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]); } 18
  • 21. Processing Arrays: for Statement  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]; } 21
  • 22. Processing Arrays Using for Loop – Examples  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] + " "); } // Result: 5 4 3 2 1 for (int index = 0; index < array.Length; index++) { array[index] = index; } 22
  • 23. Processing Arrays: foreach  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
  • 24. Processing Arrays Using foreach – Example  Print all elements of a string[] array: string[] capitals = { "Sofia", "Washington", "London", "Paris" }; foreach (string capital in capitals) { Console.WriteLine(capital); } 24
  • 27. Lists (Resizable Arrays)  List<T> – 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<int> will hold integers  List<object> 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
  • 28. List Example List<int> intList = new List<int>(); for( int i=0; i<5; i++) { intList.Add(i); } 28 int[] intArray = new int[5]; for( int i=0; i<5; 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
  • 29. Lists vs. Arrays  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<T> 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[5] = newValue; list.Add(newValue);
  • 31. HowThe List<T> Works?  Why adding new elements is not slow?  When adding n elements in List<T> it resizes itself log(2)n times instead of n  Initially a new List<T> has size of 0 elements  Counter for total capacity (Capacity)  Counter for number of used capacity (Count)  When created, Capacity is 4both properties of the list have values of 0  When adding the first element Count becomes 1 and Capacity becomes 4 31
  • 32. HowThe List<T> Works? (2)  Initially the List<T> 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
  • 35. Copying Arrays  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
  • 36. Summary  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<T> holds resizable arrays  Good when we don't know the number of elements initially 36
  • 37. форум програмиране,форум уеб дизайн курсове и уроци по програмиране,уеб дизайн – безплатно програмиранеза деца – безплатни курсове и уроци безплатен SEO курс -оптимизация за търсачки уроци по уеб дизайн, HTML,CSS, JavaScript,Photoshop уроци по програмиранеи уеб дизайн за ученици ASP.NET MVCкурс – HTML,SQL,C#,.NET,ASP.NETMVC безплатен курс"Разработка на софтуер в cloud среда" BG Coder -онлайн състезателна система -online judge курсове и уроци по програмиране,книги – безплатно отНаков безплатен курс"Качествен програменкод" алго академия – състезателно програмиране,състезания ASP.NET курс -уеб програмиране,бази данни, C#,.NET,ASP.NET курсове и уроци по програмиране– Телерик академия курсмобилни приложения с iPhone, Android,WP7,PhoneGap freeC#book, безплатна книга C#,книга Java,книга C# Дончо Минков -сайт за програмиране Николай Костов -блог за програмиране C#курс,програмиране,безплатно Arrays http://academy.telerik.com
  • 38. Exercises 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}. 38
  • 39. Exercises (2) 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. 39
  • 40. Exercises (3) 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} 40
  • 41. Exercises (6) 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 inWikipedia). 12. Write a program that creates an array containing all letters from the alphabet (A-Z). Read a word from the console and print the index of each of its letters in the array. 13. * Write a program that sorts an array of integers using the merge sort algorithm (find it in Wikipedia). 14. Write a program that sorts an array of strings using the quick sort algorithm (find it in Wikipedia). 41
  • 42. 15. Write a program that finds all prime numbers in the range [1...10 000 000]. Use the sieve of Eratosthenes algorithm (find it in Wikipedia). 16. *We are given an array of integers and a number S. Write a program to find if there exists a subset of the elements of the array that has a sum S. Example: arr={2, 1, 2, 4, 3, 5, 2, 6}, S=14  yes (1+2+5+6) 17. *Write a program that reads three integer numbers N, K and S and an array of N elements from the console. Find in the array a subset of K elements that have sum S or indicate about its absence. Exercises (7) 42
  • 43. Exercises (8) 18. *Write a program that reads an array of integers and removes from it a minimal number of elements in such way that the remaining array is sorted in increasing order. Print the remaining sorted array. Example: {6, 1, 4, 3, 0, 3, 6, 4, 5}  {1, 3, 3, 4, 5} 19. *Write a program that reads a number N and generates and prints all the permutations of the numbers [1 … N]. Example: n = 3  {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1} 43
  • 44. Exercises (9) 20. Write a program that reads two numbers N and K and generates all the variations of K elements from the set [1..N]. Example: N = 3, K = 2  {1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3} 21. Write a program that reads two numbers N and K and generates all the combinations of K distinct elements from the set [1..N]. Example: N = 5, K = 2  {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, {2, 4}, {2, 5}, {3, 4}, {3, 5}, {4, 5} 44
  • 45. FreeTrainings @Telerik Academy  Fundamentals of C# Programming Course  csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com  Telerik Academy @ Facebook  facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com

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.*
  11. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  12. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  13. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  14. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  15. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  16. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*