SlideShare une entreprise Scribd logo
1  sur  44
Arrays
Processing Sequences of Elements
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
1. Defining, Initializing and Processing Arrays
2. Reading Arrays from the Console
 Using for Loop to Read Arrays
 Using String.Split(…)
3. Printing Arrays at the Console
 Using the foreach Loop
 Using String.Join(…)
4. Arrays – Exercises
2
Arrays
Working with Arrays of Elements
What are Arrays?
 In programming array is a sequence of elements
 Elements are numbered from 0 to Length-1
 Elements are of the same type (e.g. integers)
 Arrays have fixed size (Array.Length) – cannot be resized
4
0 1 2 3 4
Array of 5 elements
Element index
… … … … …
Element
of an array
5
 The days of week can be stored in array of strings:
Days of Week – Example
string[] days = {
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
};
Expression Value
days[0] Monday
days[1] Tuesday
days[2] Wednesday
days[3] Thursday
days[4] Friday
days[5] Saturday
days[6] Sunday
6
 Enter a day number [1…7] and print the day name (in English) or
"Invalid day!"
Problem: Day of Week
string[] days = { "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday" };
int day = int.Parse(Console.ReadLine());
if (day >= 1 && day <= 7)
Console.WriteLine(days[day - 1]);
else
Console.WriteLine("Invalid day!");
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#0
7
 Allocating an array of 10 integers:
 Assigning values to the array elements:
 Accessing array elements by index:
Working with Arrays
int[] numbers = new int[10];
for (int i = 0; i < numbers.Length; i++)
numbers[i] = 1;
numbers[5] = numbers[2] + numbers[7];
numbers[10] = 1; // IndexOutOfRangeException
All elements are
initially == 0
The Length holds
the number of
array elements
The [] operator accesses
elements by index
8
 Write a program to find all prime numbers in range [0…n]
 Sieve of Eratosthenes algorithm:
1. primes[0…n] = true
2. primes[0] = primes[1] = false
3. Find the smallest p, which
holds primes[p] = true
4. primes[2*p] = primes[3*p] =
primes[4*p] = … = false
5. Repeat for the next smallest p
Problem: Sieve of Eratosthenes
9
Solution: Sieve of Eratosthenes
var n = int.Parse(Console.ReadLine());
bool[] primes = new bool[n + 1];
for (int i = 0; i <= n; i++) primes[i] = true;
primes[0] = primes[1] = false;
for (int p = 2; p <= n; p++)
if (primes[p]) FillPrimes(primes, p);
static void FillPrimes(bool[] primes, int step)
{
for (int i = 2 * step; i < primes.Length; i += step)
primes[i] = false;
}
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#1
TODO: print the
calculated prime
numbers at the end
10
 Enter two integers n and k
 Generate and print the
following sequence:
 The first element is: 1
 All other elements = sum of
the previous k elements
 Example: n = 9, k = 5
 120 = 4 + 8 + 16 + 31 + 61
Problem: Last K Numbers Sums
6
3
Sequence:
1 1 2 4 7 13
8
2
Sequence:
1 1 2 3 5 8 13 21
9
5
Sequence:
1 1 2 4 8 16 31 61 120
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#2
1 1 2 4 8 16 31 61 120
+
11
Solution: Last K Numbers Sums
var n = int.Parse(Console.ReadLine());
var k = int.Parse(Console.ReadLine());
var seq = new long[n];
seq[0] = 1;
for (int current = 1; current < n; current++)
{
var start = Math.Max(0, current - k);
var end = current - 1;
long sum = // TODO: sum the values of seq[start … end]
seq[current] = sum;
}
// TODO: print the sequence seq[]
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#2
Working with Arrays
Live Exercises in Class (Lab)
Reading Arrays from the Console
Using String.Split() and Select()
14
 First, read from the console the length of the array:
 Next, create the array of given size n and read its elements:
Reading Arrays From the Console
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = int.Parse(Console.ReadLine());
}
15
 Write a program to read n integers and print their sum, min,
max, first, last and average values:
Problem: Sum, Min, Max, First, Last, Average
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#3
5
12
20
-5
37
8
Sum = 72
Min = -5
Max = 37
First = 12
Last = 8
Average = 14.4
4
50
20
25
40
Sum = 135
Min = 20
Max = 50
First = 50
Last = 40
Average = 33.75
16
Solution: Sum, Min, Max, First, Last, Average
using System.Linq;
…
var n = int.Parse(Console.ReadLine());
var nums = new int[n];
for (int i = 0; i < n; i++)
nums[i] = int.Parse(Console.ReadLine());
Console.WriteLine("Sum = {0}", nums.Sum());
Console.WriteLine("Min = {0}", nums.Min());
// TODO: print also max, first, last and average values
Use System.Linq to enable aggregate
functions like .Max() and .Sum()
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#3
17
 Arrays can be read from a single line of space separated values:
 Or even write the above as a single line of code:
Reading Array Values from a Single Line
string values = Console.ReadLine();
string[] items = values.Split(' ');
int[] arr = new int[items.Length];
for (int i = 0; i < items.Length; i++)
arr[i] = int.Parse(items[i]);
int[] arr = Console.ReadLine().Split(' ')
.Select(int.Parse).ToArray();
2 8 30 25 40 72 -2 44 56
string.Split(' ')
splits string by space
and produces string[]
Use System.Linq to
enable .Select()
18
 Write a program to read an array of integers and find all triples of
elements a, b and c, such that a + b == c (a stays left from b)
Problem: Triple Sum (a + b == c)
1 1 1 1
No
4 2 8 6
4 + 2 == 6
2 + 6 == 8
3 1 5 6 1 2
3 + 2 == 5
1 + 5 == 6
1 + 1 == 2
1 + 2 == 3
5 + 1 == 6
1 + 2 == 3
Check your solution here:
https://judge.softuni.bg/Contests/Practice/Index/172#4
2 7 5 0
2 + 5 == 7
2 + 0 == 2
7 + 0 == 7
5 + 0 == 5
19
Solution: Triple Sum (a + b == c)
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#4
int[] nums = Console.ReadLine().Split(' ')
.Select(int.Parse).ToArray();
for (int i = 0; i < nums.Length; i++)
for (int j = i + 1; j < nums.Length; j++)
{
int a = nums[i];
int b = nums[j];
int sum = a + b;
if (nums.Contains(sum))
Console.WriteLine($"{a} + {b} == {sum}");
}
TODO: print "No"
when no triples
are found
Printing Arrays at the Console
Using foreach and String.Join()
Printing Arrays on the Console
 To print all array elements, a for-loop can be used
 Separate elements with white space or a new line
 Example:
string[] arr = {"one", "two", "three", "four", "five"};
// Process all array elements
for (int index = 0; index < arr.Length; index++)
{
// Print each element on a separate line
Console.WriteLine("arr[{0}] = {1}", index, arr[index]);
}
21
22
Problem: Rounding Numbers
 Read an array of real numbers (space separated values), round them
in "away from 0" style and print the output as in the examples:
0.9 1.5 2.4 2.5 3.14
0.9 => 1
1.5 => 2
2.4 => 2
2.5 => 3
3.14 => 3
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#5
-5.01 -1.599 -2.5 -1.50 0
-5.01 => -5
-1.599 => -2
-2.5 => -3
-1.50 => -2
0 => 0
23
Solution: Rounding Numbers
 Rounding turns each value to the nearest integer
 What to do when the value is exactly between two integers?
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#5
double[] nums = Console.ReadLine()
.Split(' ').Select(double.Parse).ToArray();
int[] roundedNums = new int[nums.Length];
for (int i = 0; i < nums.Length; i++)
roundedNums[i] = (int) Math.Round(nums[i],
MidpointRounding.AwayFromZero);
for (int i = 0; i < nums.Length; i++)
Console.WriteLine($"{nums[i]} -> {roundedNums[i]}");
Printing with foreach / String.Join(…)
 Use foreach-loop:
 Use string.Join(separator, array):
int[] arr = { 1, 2, 3 };
Console.WriteLine(string.Join(", ", arr)); // 1, 2, 3
string[] strings = { "one", "two", "three", "four" };
Console.WriteLine(string.Join(" - ", strings));
// one - two - three - four
24
int[] arr = { 10, 20, 30, 40, 50};
foreach (var element in arr)
Console.WriteLine(element)
25
 Read an array of strings (space separated values), reverse it and
print its elements:
 Reversing array elements:
Problem: Reverse Array
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#6
1 2 3 4 5 5 4 3 2 1 -1 20 99 5 5 99 20 -1
1 2 3 4 5
exchange
26
Solution: Reverse Array
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#6
var nums = Console.ReadLine()
.Split(' ').Select(int.Parse).ToArray();
for (int i = 0; i < nums.Length / 2; i++)
SwapElements(nums, i, nums.Length - 1 - i);
Console.WriteLine(string.Join(" ", nums));
static void SwapElements(int[] arr, int i, int j)
{
var oldElement = arr[i];
arr[i] = arr[j];
arr[j] = oldElement;
}
27
 Another solution to the "reverse array" problem:
 Or even shorter (without parsing strings to numbers):
Solution: Reverse Array – Functional Style
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#6
Console.WriteLine(string.Join(" ",
Console.ReadLine().Split(' ').Select(int.Parse)
.Reverse().ToArray()));
Console.WriteLine(string.Join(" ",
Console.ReadLine().Split(' ').Reverse()));
Reading and Printing Arrays
Live Exercises in Class (Lab)
Arrays – Exercises
30
 Write a program that reads two arrays of integers and sums them
 When elements are less, duplicate the smaller array a few times
Problem: Sum Arrays
1 2 3 4
2 3 4 5
3 5 7 9
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#7
1 2 3 4 5
2 3
3 5 5 7 7
1 2 3 4 5
2 3 2 3 2
5 4 3
2 3 1 4
7 7 4 9
5 4 3 5
2 3 1 4
31
Solution: Sum Arrays
var arr1 = Console.ReadLine()
.Split(' ').Select(int.Parse).ToArray();
var arr2 = // TODO: read the second array of integers
var n = Math.Max(arr1.Length, arr2.Length);
var sumArr = new int[n];
for (int i = 0; i < n; i++)
sumArr[i] =
arr1[i % arr1.Length] +
arr2[i % arr2.Length];
Console.WriteLine(string.Join(" ", sumArr));
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#7
Loop the array: end  start
arr[len]  arr[0]
arr[len+1]  arr[1]
…
32
 Reads an array of integers and condense them by summing
adjacent couples of elements until a single integer is obtained:
Problem: Condense Array to Number
2 4 1 2
6 5 3
11 8
19
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#8
2 10 3
12 13
25
5 0 4 1 2
5 4 5 3
9 9 8
18 17
35
33
Solution: Condense Array to Number
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#8
int[] nums = Console.ReadLine()
.Split(' ').Select(int.Parse).ToArray();
while (nums.Length > 1)
{
int[] condensed = new int[nums.Length - 1];
for (int i = 0; i < nums.Length - 1; i++)
condensed[i] = // TODO: sum nums
nums = condensed;
}
Console.WriteLine(nums[0]);
2 10 3
12 13
0 1 2
nums[] :
condensed[] :
34
 Write a method to extract the middle 1, 2 or 3 elements from
array of n integers
 n = 1  1 element
 even n  2 elements
 odd n  3 elements
 Read n integers from the console and print the middle elements
Problem: Extract Middle 1, 2 or 3 Elements
1 2 3 4 5 6 7 { 3, 4, 5 }
2 3 8 1 7 4 { 8, 1 }
5 { 5 }
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#9
2 8 12 7 3 4 5 33 -2 8 22 4 { 4, 5 }
35
Solution: Extract Middle 1, 2 or 3 Elements
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#9
static int[] ExtractMiddleElements(int[] arr)
{
int start = arr.Length / 2 - 1;
int end = start + 2;
if (arr.Length == 1) start = end = 0;
else if (arr.Length % 2 == 0) end--;
int[] mid = new int[end - start + 1];
// Copy arr[start … end]  mid[]
return mid;
}
1 2 3 4 5 6 7
start end
36
 Read two arrays of words and find the length of the largest
common end (left or right)
Problem: Largest Common End
hi php java csharp sql html css js
hi php java js softuni nakov java learn
3
hi php java xml csharp sql html css js
nakov java sql html css js
4
I love programming
Learn Java or C#?
0
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#10
37
Solution: Largest Common End
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#10
static int LargestCommonEnd(
string[] words1, string[] words2)
{
var rightCount = 0;
while (rightCount < words1.Length &&
rightCount < words2.Length)
if (words1[words1.Length - rightCount - 1] ==
words2[words2.Length - rightCount - 1])
rightCount++;
else break;
return rightCount;
}
Arrays – Exercises
Live Exercises in Class (Lab)
39
 Read an array of 4*k integers, fold it like shown below, and print
the sum of the upper and lower rows (2*k integers):
Homework: Fold and Sum
1 2 3 4 5 6 7 8
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#11
2 1 8 7
3 4 5 6
5 5 13 13
4 3 -1 2 5 0 1 9 8 6 7 -2
-1 3 4 -2 7 6
2 5 0 1 9 8
1 8 4 -1 16 14
5 2 3 6
5 6
2 3
7 9
3 4 5 6
3 4 5 6
40
 Read an array of n integers and an integer k. Rotate the array
right k times and sum the obtained arrays as shown below:
Homework: Rotate and Sum
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#12
3 2 4 -1
2
-1 3 2 4
4 -1 3 2
3 2 5 6
1 2 3
1
3 1 2 3 1 2
1 2 3 4 5
3
5 1 2 3 4
4 5 1 2 3
3 4 5 1 2
12 10 8 6 9
41
 Arrays hold sequence of elements
 Elements are numbered from 0 to length-1
 Creating (allocating) an array:
 Accessing array elements by index:
 Printing array elements:
Summary
int[] numbers = new int[10];
numbers[5] = 10;
Console.Write(string.Join(" ", arr));
?
Arrays
https://softuni.bg/courses/programming-basics/
License
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
 Attribution: this work may contain portions from
 "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license
43
Free Trainings @ Software University
 Software University Foundation – softuni.org
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University @ YouTube
 youtube.com/SoftwareUniversity
 Software University Forums – forum.softuni.bg

Contenu connexe

Tendances

FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEVenugopalavarma Raja
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpprajshreemuthiah
 
Infix to postfix expression in ds
Infix to postfix expression in dsInfix to postfix expression in ds
Infix to postfix expression in dsRohini Mahajan
 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 
Operator overloading C++
Operator overloading C++Operator overloading C++
Operator overloading C++Lahiru Dilshan
 
Enumerated data types in C
Enumerated data types in CEnumerated data types in C
Enumerated data types in CArpana shree
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Majid Saeed
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arraysNeeru Mittal
 
Tokens expressionsin C++
Tokens expressionsin C++Tokens expressionsin C++
Tokens expressionsin C++HalaiHansaika
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and PointersPrabu U
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Kamlesh Makvana
 
Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structureVardhil Patel
 

Tendances (20)

Python Programming
Python Programming Python Programming
Python Programming
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpp
 
Infix to postfix expression in ds
Infix to postfix expression in dsInfix to postfix expression in ds
Infix to postfix expression in ds
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Operator overloading C++
Operator overloading C++Operator overloading C++
Operator overloading C++
 
Enumerated data types in C
Enumerated data types in CEnumerated data types in C
Enumerated data types in C
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Standard data-types-in-py
Standard data-types-in-pyStandard data-types-in-py
Standard data-types-in-py
 
Structure and union
Structure and unionStructure and union
Structure and union
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Tokens expressionsin C++
Tokens expressionsin C++Tokens expressionsin C++
Tokens expressionsin C++
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
Python list
Python listPython list
Python list
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structure
 

Similaire à 07. Arrays

Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: ArraysSvetlin Nakov
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01Abdul Samee
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQIntro C# Book
 
ch07-arrays.ppt
ch07-arrays.pptch07-arrays.ppt
ch07-arrays.pptMahyuddin8
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnArnaud Joly
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0BG Java EE Course
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfSHASHIKANT346021
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfShashikantSathe3
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxrohinitalekar1
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfUmarMustafa13
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3Abdul Haseeb
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptxMrhaider4
 

Similaire à 07. Arrays (20)

Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
ch07-arrays.ppt
ch07-arrays.pptch07-arrays.ppt
ch07-arrays.ppt
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
R Programming Intro
R Programming IntroR Programming Intro
R Programming Intro
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
Unit 3
Unit 3 Unit 3
Unit 3
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPy
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 

Plus de Intro C# Book

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversalIntro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming CodeIntro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexityIntro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 

Plus de Intro C# Book (20)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 

Dernier

Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersDamian Radcliffe
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girladitipandeya
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...tanu pandey
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Servicesexy call girls service in goa
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirtrahman018755
 
SEO Growth Program-Digital optimization Specialist
SEO Growth Program-Digital optimization SpecialistSEO Growth Program-Digital optimization Specialist
SEO Growth Program-Digital optimization SpecialistKHM Anwar
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663Call Girls Mumbai
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...APNIC
 
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445ruhi
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
Networking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOGNetworking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOGAPNIC
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)Damian Radcliffe
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Standkumarajju5765
 
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsstephieert
 

Dernier (20)

Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
 
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICECall Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girls
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
 
SEO Growth Program-Digital optimization Specialist
SEO Growth Program-Digital optimization SpecialistSEO Growth Program-Digital optimization Specialist
SEO Growth Program-Digital optimization Specialist
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
 
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
 
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
 
Networking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOGNetworking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOG
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
 
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girls
 

07. Arrays

  • 1. Arrays Processing Sequences of Elements SoftUni Team Technical Trainers Software University http://softuni.bg
  • 2. Table of Contents 1. Defining, Initializing and Processing Arrays 2. Reading Arrays from the Console  Using for Loop to Read Arrays  Using String.Split(…) 3. Printing Arrays at the Console  Using the foreach Loop  Using String.Join(…) 4. Arrays – Exercises 2
  • 4. What are Arrays?  In programming array is a sequence of elements  Elements are numbered from 0 to Length-1  Elements are of the same type (e.g. integers)  Arrays have fixed size (Array.Length) – cannot be resized 4 0 1 2 3 4 Array of 5 elements Element index … … … … … Element of an array
  • 5. 5  The days of week can be stored in array of strings: Days of Week – Example string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; Expression Value days[0] Monday days[1] Tuesday days[2] Wednesday days[3] Thursday days[4] Friday days[5] Saturday days[6] Sunday
  • 6. 6  Enter a day number [1…7] and print the day name (in English) or "Invalid day!" Problem: Day of Week string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; int day = int.Parse(Console.ReadLine()); if (day >= 1 && day <= 7) Console.WriteLine(days[day - 1]); else Console.WriteLine("Invalid day!"); Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#0
  • 7. 7  Allocating an array of 10 integers:  Assigning values to the array elements:  Accessing array elements by index: Working with Arrays int[] numbers = new int[10]; for (int i = 0; i < numbers.Length; i++) numbers[i] = 1; numbers[5] = numbers[2] + numbers[7]; numbers[10] = 1; // IndexOutOfRangeException All elements are initially == 0 The Length holds the number of array elements The [] operator accesses elements by index
  • 8. 8  Write a program to find all prime numbers in range [0…n]  Sieve of Eratosthenes algorithm: 1. primes[0…n] = true 2. primes[0] = primes[1] = false 3. Find the smallest p, which holds primes[p] = true 4. primes[2*p] = primes[3*p] = primes[4*p] = … = false 5. Repeat for the next smallest p Problem: Sieve of Eratosthenes
  • 9. 9 Solution: Sieve of Eratosthenes var n = int.Parse(Console.ReadLine()); bool[] primes = new bool[n + 1]; for (int i = 0; i <= n; i++) primes[i] = true; primes[0] = primes[1] = false; for (int p = 2; p <= n; p++) if (primes[p]) FillPrimes(primes, p); static void FillPrimes(bool[] primes, int step) { for (int i = 2 * step; i < primes.Length; i += step) primes[i] = false; } Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#1 TODO: print the calculated prime numbers at the end
  • 10. 10  Enter two integers n and k  Generate and print the following sequence:  The first element is: 1  All other elements = sum of the previous k elements  Example: n = 9, k = 5  120 = 4 + 8 + 16 + 31 + 61 Problem: Last K Numbers Sums 6 3 Sequence: 1 1 2 4 7 13 8 2 Sequence: 1 1 2 3 5 8 13 21 9 5 Sequence: 1 1 2 4 8 16 31 61 120 Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#2 1 1 2 4 8 16 31 61 120 +
  • 11. 11 Solution: Last K Numbers Sums var n = int.Parse(Console.ReadLine()); var k = int.Parse(Console.ReadLine()); var seq = new long[n]; seq[0] = 1; for (int current = 1; current < n; current++) { var start = Math.Max(0, current - k); var end = current - 1; long sum = // TODO: sum the values of seq[start … end] seq[current] = sum; } // TODO: print the sequence seq[] Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#2
  • 12. Working with Arrays Live Exercises in Class (Lab)
  • 13. Reading Arrays from the Console Using String.Split() and Select()
  • 14. 14  First, read from the console the length of the array:  Next, create the array of given size n and read its elements: Reading Arrays From the Console int n = int.Parse(Console.ReadLine()); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = int.Parse(Console.ReadLine()); }
  • 15. 15  Write a program to read n integers and print their sum, min, max, first, last and average values: Problem: Sum, Min, Max, First, Last, Average Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#3 5 12 20 -5 37 8 Sum = 72 Min = -5 Max = 37 First = 12 Last = 8 Average = 14.4 4 50 20 25 40 Sum = 135 Min = 20 Max = 50 First = 50 Last = 40 Average = 33.75
  • 16. 16 Solution: Sum, Min, Max, First, Last, Average using System.Linq; … var n = int.Parse(Console.ReadLine()); var nums = new int[n]; for (int i = 0; i < n; i++) nums[i] = int.Parse(Console.ReadLine()); Console.WriteLine("Sum = {0}", nums.Sum()); Console.WriteLine("Min = {0}", nums.Min()); // TODO: print also max, first, last and average values Use System.Linq to enable aggregate functions like .Max() and .Sum() Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#3
  • 17. 17  Arrays can be read from a single line of space separated values:  Or even write the above as a single line of code: Reading Array Values from a Single Line string values = Console.ReadLine(); string[] items = values.Split(' '); int[] arr = new int[items.Length]; for (int i = 0; i < items.Length; i++) arr[i] = int.Parse(items[i]); int[] arr = Console.ReadLine().Split(' ') .Select(int.Parse).ToArray(); 2 8 30 25 40 72 -2 44 56 string.Split(' ') splits string by space and produces string[] Use System.Linq to enable .Select()
  • 18. 18  Write a program to read an array of integers and find all triples of elements a, b and c, such that a + b == c (a stays left from b) Problem: Triple Sum (a + b == c) 1 1 1 1 No 4 2 8 6 4 + 2 == 6 2 + 6 == 8 3 1 5 6 1 2 3 + 2 == 5 1 + 5 == 6 1 + 1 == 2 1 + 2 == 3 5 + 1 == 6 1 + 2 == 3 Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#4 2 7 5 0 2 + 5 == 7 2 + 0 == 2 7 + 0 == 7 5 + 0 == 5
  • 19. 19 Solution: Triple Sum (a + b == c) Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#4 int[] nums = Console.ReadLine().Split(' ') .Select(int.Parse).ToArray(); for (int i = 0; i < nums.Length; i++) for (int j = i + 1; j < nums.Length; j++) { int a = nums[i]; int b = nums[j]; int sum = a + b; if (nums.Contains(sum)) Console.WriteLine($"{a} + {b} == {sum}"); } TODO: print "No" when no triples are found
  • 20. Printing Arrays at the Console Using foreach and String.Join()
  • 21. Printing Arrays on the Console  To print all array elements, a for-loop can be used  Separate elements with white space or a new line  Example: string[] arr = {"one", "two", "three", "four", "five"}; // Process all array elements for (int index = 0; index < arr.Length; index++) { // Print each element on a separate line Console.WriteLine("arr[{0}] = {1}", index, arr[index]); } 21
  • 22. 22 Problem: Rounding Numbers  Read an array of real numbers (space separated values), round them in "away from 0" style and print the output as in the examples: 0.9 1.5 2.4 2.5 3.14 0.9 => 1 1.5 => 2 2.4 => 2 2.5 => 3 3.14 => 3 Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#5 -5.01 -1.599 -2.5 -1.50 0 -5.01 => -5 -1.599 => -2 -2.5 => -3 -1.50 => -2 0 => 0
  • 23. 23 Solution: Rounding Numbers  Rounding turns each value to the nearest integer  What to do when the value is exactly between two integers? Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#5 double[] nums = Console.ReadLine() .Split(' ').Select(double.Parse).ToArray(); int[] roundedNums = new int[nums.Length]; for (int i = 0; i < nums.Length; i++) roundedNums[i] = (int) Math.Round(nums[i], MidpointRounding.AwayFromZero); for (int i = 0; i < nums.Length; i++) Console.WriteLine($"{nums[i]} -> {roundedNums[i]}");
  • 24. Printing with foreach / String.Join(…)  Use foreach-loop:  Use string.Join(separator, array): int[] arr = { 1, 2, 3 }; Console.WriteLine(string.Join(", ", arr)); // 1, 2, 3 string[] strings = { "one", "two", "three", "four" }; Console.WriteLine(string.Join(" - ", strings)); // one - two - three - four 24 int[] arr = { 10, 20, 30, 40, 50}; foreach (var element in arr) Console.WriteLine(element)
  • 25. 25  Read an array of strings (space separated values), reverse it and print its elements:  Reversing array elements: Problem: Reverse Array Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#6 1 2 3 4 5 5 4 3 2 1 -1 20 99 5 5 99 20 -1 1 2 3 4 5 exchange
  • 26. 26 Solution: Reverse Array Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#6 var nums = Console.ReadLine() .Split(' ').Select(int.Parse).ToArray(); for (int i = 0; i < nums.Length / 2; i++) SwapElements(nums, i, nums.Length - 1 - i); Console.WriteLine(string.Join(" ", nums)); static void SwapElements(int[] arr, int i, int j) { var oldElement = arr[i]; arr[i] = arr[j]; arr[j] = oldElement; }
  • 27. 27  Another solution to the "reverse array" problem:  Or even shorter (without parsing strings to numbers): Solution: Reverse Array – Functional Style Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#6 Console.WriteLine(string.Join(" ", Console.ReadLine().Split(' ').Select(int.Parse) .Reverse().ToArray())); Console.WriteLine(string.Join(" ", Console.ReadLine().Split(' ').Reverse()));
  • 28. Reading and Printing Arrays Live Exercises in Class (Lab)
  • 30. 30  Write a program that reads two arrays of integers and sums them  When elements are less, duplicate the smaller array a few times Problem: Sum Arrays 1 2 3 4 2 3 4 5 3 5 7 9 Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#7 1 2 3 4 5 2 3 3 5 5 7 7 1 2 3 4 5 2 3 2 3 2 5 4 3 2 3 1 4 7 7 4 9 5 4 3 5 2 3 1 4
  • 31. 31 Solution: Sum Arrays var arr1 = Console.ReadLine() .Split(' ').Select(int.Parse).ToArray(); var arr2 = // TODO: read the second array of integers var n = Math.Max(arr1.Length, arr2.Length); var sumArr = new int[n]; for (int i = 0; i < n; i++) sumArr[i] = arr1[i % arr1.Length] + arr2[i % arr2.Length]; Console.WriteLine(string.Join(" ", sumArr)); Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#7 Loop the array: end  start arr[len]  arr[0] arr[len+1]  arr[1] …
  • 32. 32  Reads an array of integers and condense them by summing adjacent couples of elements until a single integer is obtained: Problem: Condense Array to Number 2 4 1 2 6 5 3 11 8 19 Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#8 2 10 3 12 13 25 5 0 4 1 2 5 4 5 3 9 9 8 18 17 35
  • 33. 33 Solution: Condense Array to Number Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#8 int[] nums = Console.ReadLine() .Split(' ').Select(int.Parse).ToArray(); while (nums.Length > 1) { int[] condensed = new int[nums.Length - 1]; for (int i = 0; i < nums.Length - 1; i++) condensed[i] = // TODO: sum nums nums = condensed; } Console.WriteLine(nums[0]); 2 10 3 12 13 0 1 2 nums[] : condensed[] :
  • 34. 34  Write a method to extract the middle 1, 2 or 3 elements from array of n integers  n = 1  1 element  even n  2 elements  odd n  3 elements  Read n integers from the console and print the middle elements Problem: Extract Middle 1, 2 or 3 Elements 1 2 3 4 5 6 7 { 3, 4, 5 } 2 3 8 1 7 4 { 8, 1 } 5 { 5 } Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#9 2 8 12 7 3 4 5 33 -2 8 22 4 { 4, 5 }
  • 35. 35 Solution: Extract Middle 1, 2 or 3 Elements Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#9 static int[] ExtractMiddleElements(int[] arr) { int start = arr.Length / 2 - 1; int end = start + 2; if (arr.Length == 1) start = end = 0; else if (arr.Length % 2 == 0) end--; int[] mid = new int[end - start + 1]; // Copy arr[start … end]  mid[] return mid; } 1 2 3 4 5 6 7 start end
  • 36. 36  Read two arrays of words and find the length of the largest common end (left or right) Problem: Largest Common End hi php java csharp sql html css js hi php java js softuni nakov java learn 3 hi php java xml csharp sql html css js nakov java sql html css js 4 I love programming Learn Java or C#? 0 Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#10
  • 37. 37 Solution: Largest Common End Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#10 static int LargestCommonEnd( string[] words1, string[] words2) { var rightCount = 0; while (rightCount < words1.Length && rightCount < words2.Length) if (words1[words1.Length - rightCount - 1] == words2[words2.Length - rightCount - 1]) rightCount++; else break; return rightCount; }
  • 38. Arrays – Exercises Live Exercises in Class (Lab)
  • 39. 39  Read an array of 4*k integers, fold it like shown below, and print the sum of the upper and lower rows (2*k integers): Homework: Fold and Sum 1 2 3 4 5 6 7 8 Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#11 2 1 8 7 3 4 5 6 5 5 13 13 4 3 -1 2 5 0 1 9 8 6 7 -2 -1 3 4 -2 7 6 2 5 0 1 9 8 1 8 4 -1 16 14 5 2 3 6 5 6 2 3 7 9 3 4 5 6 3 4 5 6
  • 40. 40  Read an array of n integers and an integer k. Rotate the array right k times and sum the obtained arrays as shown below: Homework: Rotate and Sum Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/172#12 3 2 4 -1 2 -1 3 2 4 4 -1 3 2 3 2 5 6 1 2 3 1 3 1 2 3 1 2 1 2 3 4 5 3 5 1 2 3 4 4 5 1 2 3 3 4 5 1 2 12 10 8 6 9
  • 41. 41  Arrays hold sequence of elements  Elements are numbered from 0 to length-1  Creating (allocating) an array:  Accessing array elements by index:  Printing array elements: Summary int[] numbers = new int[10]; numbers[5] = 10; Console.Write(string.Join(" ", arr));
  • 43. License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license 43
  • 44. Free Trainings @ Software University  Software University Foundation – softuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University @ YouTube  youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bg