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

More Related Content

What's hot (20)

20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
Expression trees
Expression treesExpression trees
Expression trees
Salman Vadsarya
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
DPS Ranipur Haridwar UK
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
Edureka!
 
Elementary data structure
Elementary data structureElementary data structure
Elementary data structure
Biswajit Mandal
 
Introduction to Data Structures Sorting and searching
Introduction to Data Structures Sorting and searchingIntroduction to Data Structures Sorting and searching
Introduction to Data Structures Sorting and searching
Mvenkatarao
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
Ashim Lamichhane
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
Python tuples and Dictionary
Python   tuples and DictionaryPython   tuples and Dictionary
Python tuples and Dictionary
Aswini Dharmaraj
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
maamir farooq
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
bhavesh prakash
 
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String MethodsPython Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
P3 InfoTech Solutions Pvt. Ltd.
 
Stack and queue
Stack and queueStack and queue
Stack and queue
Katang Isip
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2
Rajendran
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
Aswini Dharmaraj
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
PTCL
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
Apurbo Datta
 
Unit 2 linked list
Unit 2   linked listUnit 2   linked list
Unit 2 linked list
DrkhanchanaR
 
Python array
Python arrayPython array
Python array
Arnab Chakraborty
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
Sunil OS
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
Edureka!
 
Elementary data structure
Elementary data structureElementary data structure
Elementary data structure
Biswajit Mandal
 
Introduction to Data Structures Sorting and searching
Introduction to Data Structures Sorting and searchingIntroduction to Data Structures Sorting and searching
Introduction to Data Structures Sorting and searching
Mvenkatarao
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
Python tuples and Dictionary
Python   tuples and DictionaryPython   tuples and Dictionary
Python tuples and Dictionary
Aswini Dharmaraj
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
maamir farooq
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2
Rajendran
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
PTCL
 
Unit 2 linked list
Unit 2   linked listUnit 2   linked list
Unit 2 linked list
DrkhanchanaR
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
Sunil OS
 

Similar to 07. Arrays (20)

Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
Svetlin Nakov
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
Abdul Samee
 
05_Arrays C plus Programming language22.pdf
05_Arrays C plus Programming language22.pdf05_Arrays C plus Programming language22.pdf
05_Arrays C plus Programming language22.pdf
bodzzaa21
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
ch07-arrays.ppt
ch07-arrays.pptch07-arrays.ppt
ch07-arrays.ppt
Mahyuddin8
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
Venkateswarlu Vuggam
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
Venkateswarlu Vuggam
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 
R Programming Intro
R Programming IntroR Programming Intro
R Programming Intro
062MayankSinghal
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
maznabili
 
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
Arnaud Joly
 
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docxArraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
BG Java EE Course
 
array: An object that stores many values of the same type.
array: An object that stores many values of the same type.array: An object that stores many values of the same type.
array: An object that stores many values of the same type.
KurniawanZaini1
 
Arrays (Lists) in Python................
Arrays (Lists) in Python................Arrays (Lists) in Python................
Arrays (Lists) in Python................
saulHS1
 
Unit 3
Unit 3 Unit 3
Unit 3
GOWSIKRAJAP
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
SHASHIKANT346021
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
ShashikantSathe3
 
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
rohinitalekar1
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
UmarMustafa13
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
Svetlin Nakov
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
Abdul Samee
 
05_Arrays C plus Programming language22.pdf
05_Arrays C plus Programming language22.pdf05_Arrays C plus Programming language22.pdf
05_Arrays C plus Programming language22.pdf
bodzzaa21
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
ch07-arrays.ppt
ch07-arrays.pptch07-arrays.ppt
ch07-arrays.ppt
Mahyuddin8
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 
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
Arnaud Joly
 
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docxArraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
BG Java EE Course
 
array: An object that stores many values of the same type.
array: An object that stores many values of the same type.array: An object that stores many values of the same type.
array: An object that stores many values of the same type.
KurniawanZaini1
 
Arrays (Lists) in Python................
Arrays (Lists) in Python................Arrays (Lists) in Python................
Arrays (Lists) in Python................
saulHS1
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
SHASHIKANT346021
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
ShashikantSathe3
 
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
rohinitalekar1
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
UmarMustafa13
 
Ad

More from Intro C# Book (20)

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 Code
Intro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro 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 complexity
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro 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 variables
Intro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
Intro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
Intro 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 Code
Intro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro 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 complexity
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro 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 variables
Intro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
Intro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
Intro C# Book
 
Ad

Recently uploaded (19)

Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx
andani26
 
OSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description fOSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description f
cbr49917
 
Perguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolhaPerguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolha
socaslev
 
Best web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you businessBest web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you business
steve198109
 
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHostingTop Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
steve198109
 
Understanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep WebUnderstanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep Web
nabilajabin35
 
DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)
APNIC
 
highend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptxhighend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptx
elhadjcheikhdiop
 
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
DataProvider1
 
IT Services Workflow From Request to Resolution
IT Services Workflow From Request to ResolutionIT Services Workflow From Request to Resolution
IT Services Workflow From Request to Resolution
mzmziiskd
 
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry SweetserAPNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC
 
(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security
aluacharya169
 
White and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptxWhite and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptx
canumatown
 
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation TemplateSmart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
yojeari421237
 
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 SupportReliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
steve198109
 
project_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptxproject_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptx
redzuriel13
 
Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx
andani26
 
OSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description fOSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description f
cbr49917
 
Perguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolhaPerguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolha
socaslev
 
Best web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you businessBest web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you business
steve198109
 
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHostingTop Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
steve198109
 
Understanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep WebUnderstanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep Web
nabilajabin35
 
DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)
APNIC
 
highend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptxhighend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptx
elhadjcheikhdiop
 
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
DataProvider1
 
IT Services Workflow From Request to Resolution
IT Services Workflow From Request to ResolutionIT Services Workflow From Request to Resolution
IT Services Workflow From Request to Resolution
mzmziiskd
 
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry SweetserAPNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC
 
(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security
aluacharya169
 
White and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptxWhite and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptx
canumatown
 
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation TemplateSmart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
yojeari421237
 
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 SupportReliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
steve198109
 
project_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptxproject_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptx
redzuriel13
 

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