SlideShare a Scribd company logo
Arrays
Processing Sequences of Elements
Svetlin Nakov
Telerik Corporation
www.telerik.com
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. Matrices and Multidimensional Arrays
6. Dynamic Arrays
 Lists<T>
 Copying Arrays
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
… … … … …
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;
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
… … … … …
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
… … … … …
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"
};
Days ofWeek
Live Demo
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
Array elements can be retrieved and changed
by the [] operator
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];
}
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());
}
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+1)/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
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]);
}
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];
}
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-1; index++)
{
array[index] = index;
}
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)
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);
}
Processing Arrays
Live Demo
Multidimensional Arrays
Using Array of Arrays, Matrices and Cubes
What is Multidimensional Array?
Multidimensional arrays have more than one
dimension (2, 3, …)
The most important multidimensional arrays
are the 2-dimensional
 Known as matrices or tables
Example of matrix of integers with 2 rows and
4 columns:
5 0 -2 4
5 6 7 8
0 1 2 3
0
1
Declaring and Creating
Multidimensional Arrays
Declaring multidimensional arrays:
Creating a multidimensional array
Use new keyword
Must specify the size of each dimension
int[,] intMatrix;
float[,] floatMatrix;
string[,,] strCube;
int[,] intMatrix = new int[3, 4];
float[,] floatMatrix = new float[8, 2];
string[,,] stringCube = new string[5, 5, 5];
Initializing Multidimensional
Arrays withValues
Creating and initializing with values
multidimensional array:
Matrices are represented by a list of rows
 Rows consist of list of values
The first dimension comes first, the second
comes next (inside the first)
int[,] matrix =
{
{1, 2, 3, 4}, // row 0 values
{5, 6, 7, 8}, // row 1 values
}; // The matrix size is 2 x 4 (2 rows, 4 cols)
AccessingThe Elements of
Multidimensional Arrays
Accessing N-dimensional array element:
Getting element value example:
Setting element value example:
nDimensionalArray[index1, … , indexn]
int[,] array = {{1, 2}, {3, 4}}
int element11 = array[1, 1]; //element11 = 4
int[,] array = new int[3, 4];
for (int row=0; row<array.GetLength(0); row++)
for (int col=0; col<array.GetLength(1); col++)
array[row, col] = row + col;
Number
of rows
Number of
columns
Reading Matrix – Example
Reading a matrix from the console
int rows = int.Parse(Console.ReadLine());
int columns = int.Parse(Console.ReadLine());
int[,] matrix = new int[rows, columns];
String inputNumber;
for (int row=0; row<rows; row++)
{
for (int column=0; column<cols; column++)
{
Console.Write("matrix[{0},{1}] = ", row, column);
inputNumber = Console.ReadLine();
matrix[row, column] = int.Parse(inputNumber);
}
}
Printing Matrix – Example
Printing a matrix on the console:
for (int row=0; row<matrix.GetLength(0); row++)
{
for (int col=0; col<matrix.GetLength(1); col++)
{
Console.Write("{0} ", matrix[row, col]);
}
Console.WriteLine();
}
Reading and
Printing Matrices
Live Demo
Finding a 2 x 2 platform in a matrix with a
maximal sum of its elements
int[,] matrix = {
{7, 1, 3, 3, 2, 1},
{1, 3, 9, 8, 5, 6},
{4, 6, 7, 9, 1, 0}
};
int bestSum = int.MinValue;
for (int row=0; row<matrix.GetLength(0)-1; row++)
for (int col=0; col<matrix.GetLength(1)-1; col++)
{
int sum = matrix[row, col] + matrix[row, col+1]
+ matrix[row+1, col] + matrix[row+1, col+1];
if (sum > bestSum)
bestSum = sum;
}
Maximal Platform – Example
Maximal Platform
Live Demo
Dynamic Arrays
List<T>
Lists
Lists are arrays that resize dynamically
When adding or removing elements
Also have indexers ( like Array)
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
List Example
List<int> intList=new List<int>();
for( int i=0; i<5; i++)
{
intList.Add(i);
}
38
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 do
With List we simply do
39
int[] intArray=new int[5];
int[] copyArray = intArray;
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
40
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 Array.Copy()
 This way only the values will be copied but not
the reference
Array.Copy(sourceArray, copyArray);
int[] copyArray=array;
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
Matrices (2-dimensional arrays) are very useful
for presenting tabular data
Questions?Questions?
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}.
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.
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}
Exercises (4)
11. Write a program that fills and prints a matrix of size
(n, n) as shown below: (examples for n = 4)
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
7 11 14 16
4 8 12 15
2 5 9 13
1 3 6 10
1 8 9 16
2 7 10 15
3 6 11 14
4 5 12 13
1 12 11 10
2 13 16 9
3 14 15 8
4 5 6 7
a) b)
c) d)
Exercises (5)
12. Write a program that reads a rectangular matrix of
size N x M and finds in it the square 3 x 3 that has
maximal sum of its elements.
13. We are given a matrix of strings of size N x M.
Sequences in the matrix we define as sets of several
neighbor elements located on the same line, column
or diagonal. Write a program that finds the longest
sequence of equal strings in the matrix. Examples:
ha fifi ho hi
fo ha hi xx
xxx ho ha xx
s qq s
pp pp s
pp qq s
ha, ha, ha s, s, s
Exercises (6)
14. Write a program that finds the index of given
element in a sorted array of integers by using the
binary search algorithm (find it in Wikipedia).
15. 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.
16. Write a program that sorts an array of integers using
the merge sort algorithm (find it in Wikipedia).
17. Write a program that sorts an array of strings using
the quick sort algorithm (find it in Wikipedia).
Exercises (7)
18. 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).
19. *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)
20. *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 (8)
21. *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}
22. *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}
Exercises (9)
23. 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}
24. 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}
Exercises (10)
25. Write a program that fills a matrix of size (N, N) as
shown in the examples (for N=4):
16 15 13 10
14 12 9 6
11 8 5 3
7 4 2 1
7 11 14 16
4 8 12 15
2 5 9 13
1 3 6 10
10 11 12 13
9 2 3 14
8 1 4 15
7 6 5 16
1 12 11 10
2 13 16 9
3 14 15 8
4 5 6 7
a) b)
*c) *d)
Exercises (11)
26. *Write a program that finds the largest area of
equal neighbor elements in a rectangular matrix and
prints its size. Example:
Hint: you can use the algorithm "Depth-first search"
or "Breadth-first search" (find them in Wikipedia).
1 3 2 2 2 4
3 3 3 2 4 4
4 3 1 2 3 3
4 3 1 3 3 1
4 3 3 3 1 1
13

More Related Content

PPTX
arrays-120712074248-phpapp01
PPT
Arrays in C++
PPTX
Arrays in programming
PPTX
Data structures in c#
PPTX
C# Arrays
PDF
Arrays and strings in c++
PPTX
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
PPT
Array in Java
arrays-120712074248-phpapp01
Arrays in C++
Arrays in programming
Data structures in c#
C# Arrays
Arrays and strings in c++
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Array in Java

What's hot (20)

PPTX
16. Arrays Lists Stacks Queues
PPTX
Module 7 : Arrays
PPT
Java: Introduction to Arrays
PPT
Strings Functions in C Programming
PPT
C++ Arrays
PPT
2 arrays
PPTX
Data structure array
PPTX
Unit 6. Arrays
PPTX
Passing an Array to a Function (ICT Programming)
PPTX
07. Arrays
PPTX
Net (f#) array
PPTX
Array and string
PDF
Java Arrays
PPTX
Arrays in java
PPTX
6 arrays injava
PPTX
Arrays in Java
PPTX
Arrays in Data Structure and Algorithm
PPTX
Programming in c Arrays
PPTX
Arrays & Strings
PPTX
Arrays basics
16. Arrays Lists Stacks Queues
Module 7 : Arrays
Java: Introduction to Arrays
Strings Functions in C Programming
C++ Arrays
2 arrays
Data structure array
Unit 6. Arrays
Passing an Array to a Function (ICT Programming)
07. Arrays
Net (f#) array
Array and string
Java Arrays
Arrays in java
6 arrays injava
Arrays in Java
Arrays in Data Structure and Algorithm
Programming in c Arrays
Arrays & Strings
Arrays basics
Ad

Viewers also liked (7)

PPT
Chapter 6 arrays part-1
PDF
Iterators must-go(ja)
PPTX
Chapter 7.0
PDF
iterators-must-go
PDF
Lecture05(control structure part ii)
PPTX
Loop control structure
PPT
Lecture 8
Chapter 6 arrays part-1
Iterators must-go(ja)
Chapter 7.0
iterators-must-go
Lecture05(control structure part ii)
Loop control structure
Lecture 8
Ad

Similar to 07 Arrays (20)

PPTX
arrays in c# including Classes handling arrays
PDF
C sharp chap6
DOC
Arrays In General
PDF
Learn C# Programming - Nullables & Arrays
PPTX
Visual Programing basic lectures 7.pptx
PDF
LectureNotes-05-DSA
PDF
Lecture06 computer applicationsie1_dratifshahzad
PDF
Array and Collections in c#
PPTX
Arrays.pptx
PPTX
C# Array.pptx
PDF
DSA-Lecture-05
PPTX
Arrays in .Net Programming Language.pptx
PDF
Intake 38 3
PPT
17-Arrays en java presentación documento
PPT
C# Tutorial MSM_Murach chapter-08-slides
PPT
Arrays Basicfundamentaldatastructure.ppt
PPTX
PPTX
Intro to C# - part 2.pptx emerging technology
PPTX
7array in c#
PPTX
C# Lesson 3
arrays in c# including Classes handling arrays
C sharp chap6
Arrays In General
Learn C# Programming - Nullables & Arrays
Visual Programing basic lectures 7.pptx
LectureNotes-05-DSA
Lecture06 computer applicationsie1_dratifshahzad
Array and Collections in c#
Arrays.pptx
C# Array.pptx
DSA-Lecture-05
Arrays in .Net Programming Language.pptx
Intake 38 3
17-Arrays en java presentación documento
C# Tutorial MSM_Murach chapter-08-slides
Arrays Basicfundamentaldatastructure.ppt
Intro to C# - part 2.pptx emerging technology
7array in c#
C# Lesson 3

More from maznabili (20)

PPT
22 Methodology of problem solving
PPT
21 High-quality programming code construction part-ii
PPT
21 high-quality programming code construction part-i
PPT
20 Object-oriented programming principles
PPT
19 Algorithms and complexity
PPT
18 Hash tables and sets
PPT
17 Trees and graphs
PPT
16 Linear data structures
PPT
15 Text files
PPT
14 Defining classes
PPT
13 Strings and text processing
PPT
12 Exceptions handling
PPT
11 Using classes and objects
PPT
10 Recursion
PPT
09 Methods
PPT
08 Numeral systems
PPT
06 Loops
PPT
05 Conditional statements
PPT
04 Console input output-
PPT
03 Operators and expressions
22 Methodology of problem solving
21 High-quality programming code construction part-ii
21 high-quality programming code construction part-i
20 Object-oriented programming principles
19 Algorithms and complexity
18 Hash tables and sets
17 Trees and graphs
16 Linear data structures
15 Text files
14 Defining classes
13 Strings and text processing
12 Exceptions handling
11 Using classes and objects
10 Recursion
09 Methods
08 Numeral systems
06 Loops
05 Conditional statements
04 Console input output-
03 Operators and expressions

Recently uploaded (20)

PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
Getting Started with Data Integration: FME Form 101
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
August Patch Tuesday
PPTX
TLE Review Electricity (Electricity).pptx
PDF
Encapsulation theory and applications.pdf
PDF
Enhancing emotion recognition model for a student engagement use case through...
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PPTX
A Presentation on Artificial Intelligence
PPTX
Tartificialntelligence_presentation.pptx
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
Encapsulation_ Review paper, used for researhc scholars
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Building Integrated photovoltaic BIPV_UPV.pdf
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Getting Started with Data Integration: FME Form 101
Agricultural_Statistics_at_a_Glance_2022_0.pdf
August Patch Tuesday
TLE Review Electricity (Electricity).pptx
Encapsulation theory and applications.pdf
Enhancing emotion recognition model for a student engagement use case through...
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
A Presentation on Artificial Intelligence
Tartificialntelligence_presentation.pptx
Hindi spoken digit analysis for native and non-native speakers
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Web App vs Mobile App What Should You Build First.pdf
MIND Revenue Release Quarter 2 2025 Press Release

07 Arrays

  • 1. Arrays Processing Sequences of Elements Svetlin Nakov Telerik Corporation www.telerik.com
  • 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. Matrices and Multidimensional Arrays 6. Dynamic Arrays  Lists<T>  Copying Arrays
  • 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 … … … … …
  • 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;
  • 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 … … … … …
  • 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 … … … … …
  • 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" };
  • 10. Accessing Array Elements Read and Modify Elements by Index
  • 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
  • 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]; }
  • 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()); }
  • 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+1)/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
  • 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]); }
  • 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]; }
  • 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-1; index++) { array[index] = index; }
  • 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)
  • 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); }
  • 26. Multidimensional Arrays Using Array of Arrays, Matrices and Cubes
  • 27. What is Multidimensional Array? Multidimensional arrays have more than one dimension (2, 3, …) The most important multidimensional arrays are the 2-dimensional  Known as matrices or tables Example of matrix of integers with 2 rows and 4 columns: 5 0 -2 4 5 6 7 8 0 1 2 3 0 1
  • 28. Declaring and Creating Multidimensional Arrays Declaring multidimensional arrays: Creating a multidimensional array Use new keyword Must specify the size of each dimension int[,] intMatrix; float[,] floatMatrix; string[,,] strCube; int[,] intMatrix = new int[3, 4]; float[,] floatMatrix = new float[8, 2]; string[,,] stringCube = new string[5, 5, 5];
  • 29. Initializing Multidimensional Arrays withValues Creating and initializing with values multidimensional array: Matrices are represented by a list of rows  Rows consist of list of values The first dimension comes first, the second comes next (inside the first) int[,] matrix = { {1, 2, 3, 4}, // row 0 values {5, 6, 7, 8}, // row 1 values }; // The matrix size is 2 x 4 (2 rows, 4 cols)
  • 30. AccessingThe Elements of Multidimensional Arrays Accessing N-dimensional array element: Getting element value example: Setting element value example: nDimensionalArray[index1, … , indexn] int[,] array = {{1, 2}, {3, 4}} int element11 = array[1, 1]; //element11 = 4 int[,] array = new int[3, 4]; for (int row=0; row<array.GetLength(0); row++) for (int col=0; col<array.GetLength(1); col++) array[row, col] = row + col; Number of rows Number of columns
  • 31. Reading Matrix – Example Reading a matrix from the console int rows = int.Parse(Console.ReadLine()); int columns = int.Parse(Console.ReadLine()); int[,] matrix = new int[rows, columns]; String inputNumber; for (int row=0; row<rows; row++) { for (int column=0; column<cols; column++) { Console.Write("matrix[{0},{1}] = ", row, column); inputNumber = Console.ReadLine(); matrix[row, column] = int.Parse(inputNumber); } }
  • 32. Printing Matrix – Example Printing a matrix on the console: for (int row=0; row<matrix.GetLength(0); row++) { for (int col=0; col<matrix.GetLength(1); col++) { Console.Write("{0} ", matrix[row, col]); } Console.WriteLine(); }
  • 34. Finding a 2 x 2 platform in a matrix with a maximal sum of its elements int[,] matrix = { {7, 1, 3, 3, 2, 1}, {1, 3, 9, 8, 5, 6}, {4, 6, 7, 9, 1, 0} }; int bestSum = int.MinValue; for (int row=0; row<matrix.GetLength(0)-1; row++) for (int col=0; col<matrix.GetLength(1)-1; col++) { int sum = matrix[row, col] + matrix[row, col+1] + matrix[row+1, col] + matrix[row+1, col+1]; if (sum > bestSum) bestSum = sum; } Maximal Platform – Example
  • 37. Lists Lists are arrays that resize dynamically When adding or removing elements Also have indexers ( like Array) 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
  • 38. List Example List<int> intList=new List<int>(); for( int i=0; i<5; i++) { intList.Add(i); } 38 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
  • 39. 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 do With List we simply do 39 int[] intArray=new int[5]; int[] copyArray = intArray; intArray = new int[6]; for (int i = 0; i < 5; i++) { intArray[i] = copyArray[i]; } intArray[5]=newValue; list.Add(newValue);
  • 42. 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 Array.Copy()  This way only the values will be copied but not the reference Array.Copy(sourceArray, copyArray); int[] copyArray=array;
  • 43. 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 Matrices (2-dimensional arrays) are very useful for presenting tabular data
  • 45. 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}.
  • 46. 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.
  • 47. 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}
  • 48. Exercises (4) 11. Write a program that fills and prints a matrix of size (n, n) as shown below: (examples for n = 4) 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 7 11 14 16 4 8 12 15 2 5 9 13 1 3 6 10 1 8 9 16 2 7 10 15 3 6 11 14 4 5 12 13 1 12 11 10 2 13 16 9 3 14 15 8 4 5 6 7 a) b) c) d)
  • 49. Exercises (5) 12. Write a program that reads a rectangular matrix of size N x M and finds in it the square 3 x 3 that has maximal sum of its elements. 13. We are given a matrix of strings of size N x M. Sequences in the matrix we define as sets of several neighbor elements located on the same line, column or diagonal. Write a program that finds the longest sequence of equal strings in the matrix. Examples: ha fifi ho hi fo ha hi xx xxx ho ha xx s qq s pp pp s pp qq s ha, ha, ha s, s, s
  • 50. Exercises (6) 14. Write a program that finds the index of given element in a sorted array of integers by using the binary search algorithm (find it in Wikipedia). 15. 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. 16. Write a program that sorts an array of integers using the merge sort algorithm (find it in Wikipedia). 17. Write a program that sorts an array of strings using the quick sort algorithm (find it in Wikipedia).
  • 51. Exercises (7) 18. 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). 19. *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) 20. *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.
  • 52. Exercises (8) 21. *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} 22. *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}
  • 53. Exercises (9) 23. 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} 24. 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}
  • 54. Exercises (10) 25. Write a program that fills a matrix of size (N, N) as shown in the examples (for N=4): 16 15 13 10 14 12 9 6 11 8 5 3 7 4 2 1 7 11 14 16 4 8 12 15 2 5 9 13 1 3 6 10 10 11 12 13 9 2 3 14 8 1 4 15 7 6 5 16 1 12 11 10 2 13 16 9 3 14 15 8 4 5 6 7 a) b) *c) *d)
  • 55. Exercises (11) 26. *Write a program that finds the largest area of equal neighbor elements in a rectangular matrix and prints its size. Example: Hint: you can use the algorithm "Depth-first search" or "Breadth-first search" (find them in Wikipedia). 1 3 2 2 2 4 3 3 3 2 4 4 4 3 1 2 3 3 4 3 1 3 3 1 4 3 3 3 1 1 13

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.*
  • #27: (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.*
  • #46: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #47: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #48: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #49: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #50: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #51: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #52: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #53: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #54: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #55: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #56: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*