SlideShare a Scribd company logo
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

PPT
07 Arrays
PPTX
Data structures in c#
PPT
Arrays in C++
PDF
Arrays In Python | Python Array Operations | Edureka
PPTX
Arrays in Data Structure and Algorithm
PPTX
C# Arrays
PPT
Array in Java
PPT
07 Arrays
Data structures in c#
Arrays in C++
Arrays In Python | Python Array Operations | Edureka
Arrays in Data Structure and Algorithm
C# Arrays
Array in Java

What's hot (20)

PPTX
6 arrays injava
PPTX
Data Structures - Lecture 3 [Arrays]
PPT
Java: Introduction to Arrays
PDF
Arrays in python
PPTX
Arrays in Java
PPTX
Arrays in java
PDF
Python programming : Arrays
PPTX
Python Scipy Numpy
PPTX
15. Streams Files and Directories
PPTX
PPT
PPT
Strings Functions in C Programming
PPTX
Java arrays
PPT
PDF
Python programming : Strings
PPTX
Arrays in java language
PPTX
PPTX
Data structure array
6 arrays injava
Data Structures - Lecture 3 [Arrays]
Java: Introduction to Arrays
Arrays in python
Arrays in Java
Arrays in java
Python programming : Arrays
Python Scipy Numpy
15. Streams Files and Directories
Strings Functions in C Programming
Java arrays
Python programming : Strings
Arrays in java language
Data structure array
Ad

Viewers also liked (12)

PPTX
Freme general-overview-version-june-2015
PPTX
Freme at feisgiltt 2015 freme use cases
PPTX
3 operators-expressions-and-statements-120712073351-phpapp01
PPTX
13 recursion-120712074623-phpapp02
PPTX
Input outputdisplaydevices-140819061228-phpapp02
PPTX
Fremeatfeisgiltt2015 fremelinkeddatalocalisers-150603090934-lva1-app6891
PPTX
Sasaki mlkrep-20150710
PPTX
Part 3-functions1-120315220356-phpapp01
PDF
Linked data tooling XML
PPTX
3 operators-expressions-and-statements-120712073351-phpapp01
PPTX
16 strings-and-text-processing-120712074956-phpapp02
DOCX
Garima Sareen Nagpal - CV
Freme general-overview-version-june-2015
Freme at feisgiltt 2015 freme use cases
3 operators-expressions-and-statements-120712073351-phpapp01
13 recursion-120712074623-phpapp02
Input outputdisplaydevices-140819061228-phpapp02
Fremeatfeisgiltt2015 fremelinkeddatalocalisers-150603090934-lva1-app6891
Sasaki mlkrep-20150710
Part 3-functions1-120315220356-phpapp01
Linked data tooling XML
3 operators-expressions-and-statements-120712073351-phpapp01
16 strings-and-text-processing-120712074956-phpapp02
Garima Sareen Nagpal - CV
Ad

Similar to arrays-120712074248-phpapp01 (20)

PPTX
16. Arrays Lists Stacks Queues
PDF
C sharp chap6
PPTX
07. Arrays
PPTX
arrays in c# including Classes handling arrays
PPT
Lecture 8
PPTX
Loops in C# for loops while and do while loop.
PPTX
Module 7 : Arrays
PDF
(2) collections algorithms
PPT
Cso gaddis java_chapter8
PPTX
Visual Programing basic lectures 7.pptx
PPT
PDF
C# Arrays Presentation - Computer Science and Engineering Department
PDF
PPT
Arrays Basicfundamentaldatastructure.ppt
PPTX
Arrays and Lists in C#, Java, Python and JavaScript
PPTX
Java Foundations: Arrays
PDF
12000121037.pdf
PPTX
Data structures and algorithms arrays
PDF
Lecture 6 - Arrays
PPT
17-Arrays en java presentación documento
16. Arrays Lists Stacks Queues
C sharp chap6
07. Arrays
arrays in c# including Classes handling arrays
Lecture 8
Loops in C# for loops while and do while loop.
Module 7 : Arrays
(2) collections algorithms
Cso gaddis java_chapter8
Visual Programing basic lectures 7.pptx
C# Arrays Presentation - Computer Science and Engineering Department
Arrays Basicfundamentaldatastructure.ppt
Arrays and Lists in C#, Java, Python and JavaScript
Java Foundations: Arrays
12000121037.pdf
Data structures and algorithms arrays
Lecture 6 - Arrays
17-Arrays en java presentación documento

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Modernizing your data center with Dell and AMD
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Electronic commerce courselecture one. Pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Big Data Technologies - Introduction.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
cuic standard and advanced reporting.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
KodekX | Application Modernization Development
Per capita expenditure prediction using model stacking based on satellite ima...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Building Integrated photovoltaic BIPV_UPV.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Modernizing your data center with Dell and AMD
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Electronic commerce courselecture one. Pdf
Empathic Computing: Creating Shared Understanding
Reach Out and Touch Someone: Haptics and Empathic Computing
NewMind AI Monthly Chronicles - July 2025
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Big Data Technologies - Introduction.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
cuic standard and advanced reporting.pdf
A Presentation on Artificial Intelligence
Review of recent advances in non-invasive hemoglobin estimation
KodekX | Application Modernization Development

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

  • #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.*
  • #11: (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.*
  • #18: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #20: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #21: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #26: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #37: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #39: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #40: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #41: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #42: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #43: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #44: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #45: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*