Lesson #18. String type and regular expressions

Theory

Lecture in pdf format

Char type

c: char;
...
c:='a';
begin
var c: char;
c:='a';
Println(c.IsDigit); // False 
Println(c.IsLetter); // True 
Println(c.IsLower); // True
Println(c.IsUpper); // False 
Println(c.IsPunctuation); // знак препинания, boolean
 
с := char.ToLower(с) ;
с := char.ToUpper(с); 
end.
Операции для типа char
c1 < c2;// сравнение по коду
c1 > c2;
с in ['a','e','i','o','u',’y’]; // c принадлежит гласным
с in ['a'..'z','A'..'Z’]; // c принадлежит английским буквам
Задание:
Запросите ввести два символа. Определите, принадлежат ли символы английским буквам, и если да, то гласные ли это буквы. Преобразуйте в верхний регистр ту букву, код которой меньше.

Пример вывода:

Введите два символа:
u z
u - английская буква, гласная
z - английская буква, не гласная
Буква u в верхнем регистре U

String type

s: string;
...
s:='abc';
begin
var s: string;
s:='Abc';
Println(s.ToLower); // abc 
Println(s.ToUpper); // ABC 
end.

Slices of the strings:

begin
var s: string;
s:='12345678';
Println(s[3:6]); // 345 
Println(s[::-1]); // 87654321 
end.

String methods:
Сonversion string <-> number:

begin
var s: string;
s:='12345678';
var i:=1;
Println(i.ToString); // string '1'
Println(s.ToInteger); // number 12345678 
Println(s.ToReal); // number 12345678 
end.

or

begin
var s: string;
s:='12345678';
var i:=1;
Println(integer.TryParse(s,i)); // is it possible to convert s to a number - True 
end.

Сonversion of a string to an array of words:

begin
var s:='it is a piece of cake';
var ss:=s.ToWords.Println('_'); // it_is_a_piece_of_cake
ss.Sorted.Println // a cake of piece is it
end.

Sample: remove all «i» letters:

begin
var s:='it is a piece of cake';
s:=s.Where(c -> c<>'i').JoinIntoString;
print(s); // t s a pece of cake 
end.

While working with strings we can use any sequence method

Reguglar expressions

Язык регулярных выражений — это язык шаблонов, расширенные операции поиска и замены для строк.

Основной цикл:

s := 'red  green  gray blue';
foreach var m in s.Matches('\w+') do
  Print(m.Value, m.Index);

Т.е. m: Match включает m.Value, m.Index
Опции регулярных выражений:

s := 'AБракадабРА';
s.Matches('бра', RegexOptions.IgnoreCase)

Примеры регулярных выражений:
‘кот|кит’ ‘к[ио]т’ ‘к[а-я]т’ ‘ко+т’ ‘кор?т’ ‘к.т’ ‘к\.т’ ‘к.*т’
‘ко{3}т’ ‘ко{2,4}т’ ‘ко[^ъыь]т’ ‘\b кот\b’

Управляющие символы и их запись в регулярных выражениях:
\ * + ? | { [ ( ) ^ $ . #
Они экранируются дополнительным \

Квантификаторы:
* — 0 или более повторений
+ — 1 или более повторений
? — 0 или 1 повторение
{N} — ровно N повторений
{N,} — не менее N повторений
{N,M} — от N до M повторений

Директивы нулевой длины:
^ — начало строки
$ — конец строки
\b — позиция на границе слова

Классы символов:
[abcd] — один из символов, указанных в списке
[^abcd] — любой из символов, кроме тех, которые указаны в списке
[a-d] — один из символов, лежащих в указанном диапазоне
[^a-d] — любой из символов, кроме тех, которые лежат в указанном диапазоне
\d — десятичная цифра: [0-9]
\D — любой символ, кроме десятичной цифры
\w — буква, цифра или символ подчеркивания
\W — любой символ, не являющийся словообразующим;
\s — пробельный символ, т. е. [ \t\r\n];
\S — любой непробельный символ;
. — любой символ

Группы:

s := ' prepod@sfedu.ru   prepod2@sfedu.ru ';
foreach var m in s.Matches('(\w+)@(\w+).(\w+)') do
  Println(m.Groups[0], m.Groups[1], m.Groups[2], m.Groups[3]); 
s.Matches('(т[оае])\1*')

Замена с помощью регулярного выражения:

s.Replace('\b\w+\b', '<$0>')
s := s.Replace('\w+',m->m.Value.ToUpper);
s := s.Replace('\w+',m->m.Value+'('+m.Length+')')
s := '10+2=12';
s.Replace('\d+', '<$0>') // <10>+<2>=<12>
s.Replace('\d+', m -> (m.Value.ToInteger*2).ToString) // 20+4=24
 
s := ' prepod@sfedu.ru   prepod2@sfedu.ru ';
s.Replace('(\w+)@(\w+).(\w+)', '$1-$2-$3')

Lesson #14. Lambda expressions

lambda expression Theory

  • A lambda expression is some unnamed expression representing a functional dependency.
  • Based on lambda expression, the compiler builds a function, identifies it in some way and replaces this lambda expression with this identifier.
  • A lambda expression can be stored in procedural variables, or passed as parameters of a procedural type.
  • Sample 1: An example of a lambda expression that returns, first, the square of the parameter, and then returns the parameter to the third power. The lambda expression is stored in the procedural variable x.
    1. Declaring of a procedural variable, and then binding it to a lambda expression:

    begin
     var x: integer-> integer;
     x:= t -> t * t;
     Print(x(7)); // 49
     x := t -> t * t * t;
     Print(x(7)); // 343
    end.

    2. Declaring and initialization of a procedural variable at the same time:

    begin
     var x: integer-> integer:= t -> t * t;
     Print(x(7)); // 49
     x := t -> t * t * t;
     Print(x(7)); // 343
    end.
    IDE PascalABC.NET allows you to use a beautiful arrow instead of -> (on the keyboard: with the Alt key pressed, we type 26 on the small numeric keypad).
    Sample 2: An example of a procedural variable with two parameters that returns the maximum of the parameters using a lambda expression.
    begin
      var f: (integer,integer)integer :=(x, y) -> if x > y then result:=x else result:=y;
      print(f(5,13))
    end.
    If a procedural variable is intended to store procedures (and not functions), then when declaring it, empty brackets must be specified after the arrow -> ().
    Sample 3: An example of a procedural variable with two parameters that outputs the maximum of the parameters using a lambda expression.
    begin
      var f: (integer,integer)() :=(x, y) -> if x > y then print(x) else print(y);
      f(5,13)
    end.
    Sample 4: An example of a lambda expression that outputs the squared parameter.
    begin
    var x: integer-> () := t -> (t * t).Print();
    x(5) // 25
    end.
    Sample 5: Example of a procedural variable with tuple assignment: the variable is associated with a lambda expression that takes two integers and returns their sum and product:
    1. A classic solution using the procedure:

    procedure Pr(a,b:integer; var sum,mult:integer);
    begin
      sum:=a+b;
      mult:=(a*b);
    end;
    begin
      var sum,mult:integer;
      Pr(2,4,sum,mult);
      print(sum,mult) // (6,8) 
    end.

    2. Solution using a procedural variable with tuple assignment and a lambda expression:

    begin
      var f: (integer,integer) -> (integer, integer);
      f := (a, b) -> (a + b, a * b);
      print(f(2, 4)) // (6,8) 
    end.
    Lambda function as a parameter
    Sample: Create a procedure that outputs a list of values of an arbitrary function of one argument on the range [a;b].

    The results when a=-5, b=-1 and function x -> x * x:

    -5 25 
    -4 16 
    -3 9 
    -2 4 
    -1 1 
    

    ✍ Solution:

      procedure Lamb(a, b: integer; f: real-> real);
      begin
        for var x := a to b do 
        begin
          Println(x, f(x));
        end
      end;
       
      begin
        Lamb(-5, 3, x -> x * x);
        Writeln;
      end.

    Labs and tasks

    {0.5 points} Task 1:

    To do: Create a procedural variable with one parameter — a two-digit number that returns a number in which the digits are swapped. Associate the variable with a lambda expression to perform the task. Do the task twice: the procedural variable returns the value and the procedural variable outputs the value. (see samples 2, 3, 4)

    expected output:

    enter two-digit number please: 
    >> 72
    27 
    

    [Program name: 14task-01.pas]

    {0.5 points} Task 2:

    To do: Calculate the value of the variable y by one of the two branches:

    To solve this, create a procedural variable with two parameters — a and b, and associate it with a lambda expression. Complete the task twice: the procedural variable returns the value and the procedural variable outputs the value. (see samples 2, 3, 4)

    expected output:

    enter two numbers 
    >>2
    >>5
    result: 3  
    

    [Program name: 14task-02.pas]

    {0.5 points} Task 3:

    To do: Create a Triangle(a,h) function that calculates the perimeter of an isosceles triangle using its base a and the height h drawn to the base. (see sample 5 solution 2)

    1. Declare the procedural variable TriangleP, defining its type as a function that takes two real parameters and returns a real result:

    var TriangleP: (real, real) -> real;

    2. Then, assign a lambda expression to this variable, which, using two parameters a and h — the base and height of an isosceles triangle — calculates the perimeter of this triangle (P = 2b+a; the side formula: b2 = (a/2)2 + h2)

    expected output:

    enter two numbers 
    >>4
    >>6
    result: 16.6491106406735  
    

    [Program name: 14task-03.pas]

    {0.5 points} Task 4:

    To do: Declase a TrianglePS(a, P, S) procedure that calculates an equilateral triangle’s perimeter P = 3·a and area S = a2·(3)1/2/4 (a — input triangle side, P and S — output parameters; all parameters are real). Using this procedure, output the perimeters and areas of three equilateral triangles with these sides. Solve this problem twice: a classical procedure and a procedural variable associated with a lambda expression. (see sample 5 solutions 1 and 2)

    expected output:

    >>2
    61.73205080756888
    >>5
    1510.8253175473055
    >>6
    1815.5884572681199
    

    [Program name: 14task-04.pas]


    Standard functions and procedures and Transformation of an array elements

    Lab 1:

    To do: Create the function to search x in the array. The function returns -1 if it is not found and index of the element otherwise.

    ✍ Algorithm:

      function IndexOfW<T>(a: array of T; x: T): integer;
      begin
        var n := a.Length;
        var i := 0;
        while (i < n) and (a[i] <> x) do
          i += 1;
        Result := i = n ? -1 : i;
      end;
       
      begin
        var a := new integer[10];
        a := arrRandomInteger(10, 0, 10);
        print(a);
        print(indexOfW(a, 2))
      end.
    Lab 2:

    To do: Print out how many odd elements are in the array.

    Expected output:

    [18,10,91,47,35] 
    3 
    

    ✍ Algorithm:

      begin
        var a := new integer[5];
        a := arrRandomInteger(5); // [18,10,91,47,35] 
        print(a);
        print(a.Count(a->odd(a))) // 3 
      end.
    Lab 3:

    To do: Transform the array elements using the rule: if element is even then substruct it by 1, if it is odd then add 1 to it.

    ✍ Algorithm:

        begin
          var a := new integer[5];
          a := arrRandomInteger(5); // [4,36,93,36,29] 
          a.Transform(a,a -> a mod 2 = 0 ? a-1 : a + 1);
          print(a) // [3,35,94,35,30] 
        end.
    {0.5 points} Task 5:

    To do: Create a randomly generated array. Use the standard functions and procedures to implement the following goals. Print out:

    1. reversed array (Reverse())
    2. the index of x number (x is entered)
    3. the last index of x number (x is entered) (LastIndexOf())
    4. true if x exists in the array, false if it doesn’t (Contains())
    5. index of the first even element (IndexOf())
    6. the number of positive elements in the array (Count()). You should create your own function that returns true if the checked number is positive.
    7. maximum element and it’s index (Max(), IndexMax()).
    8. transformed array with a rule: if element is positive then square it, if it is negative then set it to 0 (Transform()).

    Expected output:

    1. [1,6,6,4,9,9,1,3,3,10] result: 10 3 3 1 9 9 4 6 6 1
    2. [8,10,0,5,10,7,2,9,8,2]  enter x: >>10  the result: 1 
    3. [8,10,0,5,10,7,2,9,8,2]  enter x: >>10  the result: 4
    4. [8,10,0,5,10,7,2,9,8,2]  enter x: >>3  the result: false
    5. [7,1,0,3,2,4,2,10,9,4] result: 2 
    6. [7,-1,0,3,-2,4,2,-10,9,4] result: 7
    7. [7,1,0,3,2,4,2,10,9,4] result: max = 10 indexMax= 7
    8. [-8,5,1,-5,-8,10,-9,-7,-7,1] result: 0 25 1 0 0 100 0 0 0 1
    

    [Program name: 14task-05.pas]

    Extra tasks:

    1. Open taskBook of pascalAbc.net IDE:
    2. Choose ArrTransF group in the dropdown menu and click html-page button:
    3. Complete the tasks giving the files the proper names (ArrTransf1.pas etc.)
    Lab 4, Loop over some indices:

    To do: Create an array of integer elements. Pint out the array values in the interval [10,19] and increase by one it’s positive values with even indexes.

    Expected output:

    array: [41,90,100,12,16,7,69,23,59,37] 
    array values in the interval [10,19]: 12 16 
    

    ✍ Algorithm:

      begin
        var a:=arrRandomInteger(10);
        print(a);
        // values in the interval [10,19]
        foreach var i in a.Indices(x -> x.InRange(10,20)) do 
          print(a[i]);
       
        // positive values with even indexes
        foreach var i in a.Indices((x,i) -> (i mod 2 = 0) and (x > 0)) do 
          a[i] += 1;
      end.
    {0.4 points} Task 6:

    To do: Create a randomly generated array. Use indeces method to print out:

    • The values of the array with odd indexes.
    • The second half of the array elements.

    Expected output:

    array: [8,41,56,82,8,93,44,70,6,54] 
    The second half of the array elements: 8 41 56 82 8 
    The values of the array with odd indexes: 41 82 93 70 54 
    

    [Program name: 14task-06.pas]

    Lab 5:

    To do: Create the procedure to shift circularly the elements to the left

    ✍ Algorithm:

      procedure CircularShiftLeft<T>(a: array of T);
      begin
        var v := a[0];
        for var i:=0 to a.Length-2 do
          a[i] := a[i+1];
        a[a.Length-1] := v;
      end;
       
      begin
        var a := new integer[5];
        a := arrRandomInteger(5); // [56,28,33,57,25] 
        CircularShiftLeft(a);
        print(a)// [28,33,57,25,56] 
      end.
    Lab 6:

    To do: Create the procedure to shift circularly the elements to the right

    ✍ Algorithm:

      procedure CircularShiftRight<T>(a: array of T);
      begin
        var v := a[a.Length-1];
        for var i:=a.Length-1 downto 1 do
          a[i] := a[i-1];
        a[0] := v;  
      end;
       
      begin
        var a := new integer[5];
        a := arrRandomInteger(5); // [25,23,74,17,31] 
        CircularShiftRight(a);
        print(a)// [31,25,23,74,17] 
      end.
    {0.3 points} Task 7:

    To do: Create a randomly generated array. At first, transform its elements using the rule: a-1, and after, reverse it’s elements and after, make a circular shift it’s elements to the right and to the left.

    Expected output:

    array:  [93,25,52,74,76,40,54,13,29,65] 
    transformed:  [92,24,51,73,75,39,53,12,28,64] 
    Shift left:  [24,51,73,75,39,53,12,28,64,92] 
    Shift right:  [92,24,51,73,75,39,53,12,28,64] 
    

    [Program name: 14task-7.pas]

    Video of all the lessons. Pascal

    Все видео:

    Lesson # 1. Introduction to PascalABC.NET

    0. 24 11 2021 первое занятие lesson 1 variables
    0. Мое занятие 11 09 2020 beginning

    Lesson #2. Working with digits of a number

    Мое 2021 г.

    Lesson #3. Conditions

    Lesson #6. Loops. Simple tasks

    Lesson #7. Loops. Arbitrary step

    2021 г.

    Lesson #8. Sum, Accumulators, Product and Counter. Minimum and maximum value

    Lesson #9. Nested loops

    2021 г. Nested loops, break, task 7

    Lesson #10. Procedures and functions

    Lesson # 11. Function and procedures + tuples and wrappers

    task 10

    Lesson # 12. Enumerations. Arrays

    1) перекрутить на 2:20
    на RuTube, начать с 2:20
    начать с 2:20

    2)
    arrays continuation

    Lesson # 13. Arrays (Continuation). Lesson # 14. Arrays (Slices, Sorting algorithms, Lists)

    1) 24.11 фиит 1 курс Revision: enumeration type, arrays, generic type 00:24:55. Multi-file layout
    На RuTube

    2) 27.11 фиит 1 курс (массивы, заполнение и методы массивов L#12): filling the array, lambda expressions, SetLength, reassinment, standart methods to work with arrays
    На RuTube

    Exam

    https://youtu.be/kDz6fJGcurI

    Lesson #17. Sequence

    Theory

    Standard sequence generators

      Range(a,b: integer): sequence of integer

      print(Range(1,10)); // [1,2,3,4,5,6,7,8,9,10]

      Range(a,b,step: integer): sequence of integer

      print(Range(1,10,2)); // [1,3,5,7,9]

      Range(c1,c2: char): sequence of char

      print(Range('a','k')); // [a,b,c,d,e,f,g,h,i,j,k]

      Partition(a,b: real; n: integer): sequence of real

      print(Partition(0.0, 6.0, 4)); // divide into 4 equal parts [0, 1.5, 3, 4.5, 6]

      SeqRandomInteger(n: integer[; a,b: integer]): sequence of integer;

      var q:=SeqRandomInteger(5,10,20);
      print(q); // [12,18,16,14,16]

      SeqRandomReal(n: integer[; a,b: real]): sequence of real;

      var q:=SeqRandomReal(3, 1.0, 5.0);
      print(q); // [4.98996168374548,2.22339218166815,2.81110574389394]

      Seq(params a: array of T): sequence of T;

      foreach var x in Seq (1,3,8) do
          print(x*x); // 1 9 64

      SeqFill(count: integer; x: T): sequence of T;

      begin
      var q:=SeqFill(7,5);
      print(q); // [5,5,5,5,5,5,5] 
      end.
    {0.1 points} Task 1:

    To do: Create sequence of integers from -20 to 30 with a step of 3 (Range function).

    Expected output:

    [-20,-17,-14,-11,-8,-5,-2,1,4,7,10,13,16,19,22,25,28] 
    

    [Program name: 17task-01.pas]

    {0.1 points} Task 2:

    To do: Create N random numbers of a sequence from -50 to 100 (SeqRandom function).

    Expected output:

    enter n 
    >>15
    [-23,13,-27,2,46,-26,10,92,60,-9,75,28,85,7,18] 
    

    [Program name: 17task-02.pas]

    Sequence generators with lambda-expressions

    The following functions are used to generate sequences using lambda expressions:

    • SeqGen(count: integer; f: integer -> T): sequence of T;
    • begin
      var sq:=SeqGen(5,x->x+1);
      sq.println; // 1 2 3 4 5
      end.
    • SeqGen(count: integer; first: T; next: T -> T): sequence of T;
    • begin
      var sq:=SeqGen(5, 4, x->x+1);
      sq.println; // 4 5 6 7 8
      end.
    • SeqGen(count: integer; first,second: T; next: (T,T) -> T): sequence of T;
    • begin
      var sq:=SeqGen(5, 1,3, (x,y)->x+y);
      sq.println; // 1 3 4 7 11
      end.
      Lab: Create a sequence of N Fibonacci elements

      Algorithm:

      var n:=readInteger;
      var sq3:=SeqGen(n,1,1,(x,y)->x+y);
      sq3.println();
    • SeqWhile(first: T; next: T -> T; pred: T -> boolean): sequence of T;
    • Condition is added:

      begin
      var sq:=seqWhile(2,x->x*2,x->x<=1024);
      sq.println; // 2 4 8 16 32 64 128 256 512 1024
      end.
    • SeqWhile(first,second: T; next: (T,T) -> T; pred: T -> boolean): sequence of T;
    • SeqGen(count: integer; f: integer -> T): sequence of T;
    {0.1 points} Task 3:

    To do: Using lambda expression, create a sequence of N even numbers starting at 10 (SeqGen should be used)

    Expected output:

    Enter n 
    >> 7
    10 12 14 16 18 20 22
    

    [Program name: 17task-03.pas]

    {0.1 points} Task 4:

    To do: Create the following sequence: 1 3 9 27 81 243 729 2187 6561 19683 (SeqGen should be used)

    Expected output:

    1 3 9 27 81 243 729 2187 6561 19683
    

    [Program name: 17task-04.pas]

    {0.1 points} Task 5:

    To do: Create a sequence of 15 numbers: 2 1 0.5 0.25 0.125 0.0625 0.03125 0.015625 ... (specifying the first element and the function to get the next one) (SeqGen should be used)

    Expected output:

    2  1  0.5  0.25  0.125  0.0625  0.03125  0.015625 0.0078125 0.00390625 
    0.001953125 0.0009765625 0.00048828125 0.000244140625 0.0001220703125 
    

    [Program name: 17task-05.pas]

    {0.1 points} Task 6:

    To do: Create the following sequence: 2017 2012 2007 2002 1997 1992 1987 1982 1977 1972 (SeqGen should be used)

    Expected output:

    2017 2012 2007 2002 1997 1992 1987 1982 1977 1972
    

    [Program name: 17task-06.pas]

    Lab:

    To do: Create a sequence of N numbers generated by the iterative process: а1=2, аk=(аk-1+1)*аk-1, k = 2,3,… (SeqGen should be used)

    Expected output:

    Enter n 7
    2 6 42 1806 3263442 -1461943274 -757910022
    

    ✍ Algorithm:

      begin
      var n:=readInteger('Enter n');
      var sq:=SeqGen(n,2,x->(x+1)*x);
      sq.println();
      end.
    {0.2 points} Task 7:

    To do: Create a sequence of N numbers generated by the iterative process: a1 = 5, ak = ak-1 / 2-1, k = 2,3, … (SeqGen should be used)

    Expected output:

    Enter n 
    >> 9
    5  1.5  -0.25  -1.125  -1.5625 -1.78125 -1.890625 -1.9453125 -1.97265625
    

    [Program name: 17task-7.pas]

    {0.2 points} Task 8:

    To do: Create a sequence of N numbers generated by the iterative process: а1=1, а2=2, аkk-1+2аk-2, k=3,… (SeqGen should be used)

    Expected output:

    Enter n 
    >>7
    1 2 4 8 16 32 64
    

    [Program name: 17task-8.pas]

    {0.2 points} Task 9:

    To do: Create a sequence of N numbers generated by the iterative process: а1=1, а2=2, аk=(аk-1k-2)/2, k=3,… (SeqGen should be used)

    Expected output:

    Enter n 
    >> 7
    1 2 1.5 1.75 1.625 1.6875 1.65625
    

    [Program name: 17task-9.pas]

    Cutting off a seq

    • Take(count)
    • begin
      var s:=seqGen(10,x->x+1); // 1 2 3 4 5 6 7 8 9 10
      var s1:=s.Take(2); // 1 2
      s1.Println;
      end.
    • TakeLast(count)
    • Skip(count)
    • begin
      var s:=seqGen(10,x->x+1); // 1 2 3 4 5 6 7 8 9 10
      var s1:=s.Skip(2); // 3 4 5 6 7 8 9 10
      s1.Println;
      end.
      begin
      var s:=seqGen(10,x->x+1); // 1 2 3 4 5 6 7 8 9 10
      var s1:=s.Skip(3)+s.Take(3); // 4 5 6 7 8 9 10 1 2 3
      s1.Println;
      end.
    • SkipLast(count)
    • TakeWhile(T -> boolean)
    • TakeWhile((T, integer) -> boolean)
    • SkipWhile(T -> boolean)
    • SkipWhile((T, integer) -> boolean)
    • Slice(from,step[,count]: integer): sequence of T;
    • Distinct
    • Only unique elements:

      var a:=Seq(1,3,1,4,1,5);
      a.Distinct.Print; // 1 3 4 5

      Infinite sequence generators

      • Cycle()
      • Repeating a sequence block

        Seq(1,2,10,5).Cycle().Take(15).Println; // 1 2 10 5 1 2 10 5 1 2 10 5 1 2 10

        Take is used to restrict

      • Repeat
      • Infinite sequence of numbers

        var q:=55.Repeat.Take(10).Println; // 55 55 55 55 55 55 55 55 55 55
      • Step
      • Generating an infinite sequence with a step

        var q:=5.Step(2).Take(10).Println; // 5 7 9 11 13 15 17 19 21 23
      • Iterate
      • Generating an infinite sequence using a lambda-function

        var q:=10.Iterate(x->x-2).Take(10).Println; // 10 8 6 4 2 0 -2 -4 -6 -8
      • Distinct — only unique elements
      • var a:=Seq(1,3,1,4,1,5);
        a.Distinct.Print; // 1 3 4 5
      {0.1 points} Task 10:

      To do: Create 3 infinite sequences:
      1) the elements equaled 5,
      2) the elements equaled numbers 2 5 8 11 …;
      3) iterate function with a rule to output 1 2 4 8 16 32 64 128 256 512
      4) the elements equaled to repetitions of the numbers 1 2 10 5 (Seq(1,2,10,5).Cycle()).

      Output 100 elements of each.

      Expected output:

      5 5 5 5 ...
      2 5 8 11 ...
      1 2 4 8 16 32 64 128 256 512 ...
      1 2 10 5 1 2 10 5 1 2 10 5 ...
      

      [Program name: 17task-10.pas]

      Where method (queries)

      • Where(T -> boolean)
      • Lab:

        To do: Create a query to filter out even elements of the sequence.

        The result examples:

        Sequence: 1 2 3 4 5 6 7 8 9 10
        Result: 2 4 6 8 10
        

        ✍ Algorithm:

        begin
         var s:=seqGen(10,x->x+1); // 1 2 3 4 5 6 7 8 9 10
         var s1:=s.Where(x->x mod 2=0); 
        end.
      • Where((T, integer) -> boolean)
      • begin
        var s:=seqGen(10,x->x+1); // 1 2 3 4 5 6 7 8 9 10
        var s1:=s.Where((x,i)->i mod 2=0); // 1 3 5 7 9
        s1.Println;
        end.

        x — an element, and i — an index of the element.

      {0.1 points} Task 11:

      To do: A sequence of positive and negative integers is given. Create a query to filter out:
      1) the positives from that sequence
      2) the elements divisible by 5
      3) odd elements

      Expected output:

      sequence: 
      -4 25 -7 -12 16
      result 1:
      25 16
      result 2:
      25
      result 3:
      25 -7 
      

      [Program name: 17task-11.pas]

      Select method (queries)

      When projection is used each element will be modified (despite when where is used)

    • Select(T -> TRes)
    • Lab:

      To do: Create a query to square each element of the sequence.

      The result examples:

      Sequence: 1 2 3 4 5 6 7 8 9 10
      Result: 1 4 9 16 25 36 49 64 81 100
      

      ✍ Algorithm:

        begin
         var s:=seqGen(10,x->x+1); // 1 2 3 4 5 6 7 8 9 10
         var s1:=s.Select(x->x*x); // 1 4 9 16 25 36 49 64 81 100
         s1.Println;
        end.
      {0.1 points} Task 12:

      To do: A sequence of integers is given. Create a query to get a sequence in which each element is the square root of the corresponding element of the original sequence.

      Expected output:

      sequence: 
      4 25 7 12 16
      result:
      2 5 2.64575131106459 3.46410161513775 4
      

      [Program name: 17task-12.pas]

      Projection and filtering combination:

      begin
      var s:=seqGen(10,x->x+1); // 1 2 3 4 5 6 7 8 9 10
      var s1:=s.Where(x -> x mod 2 = 0).Select(x->x*x); // 4 16 36 64 100
      s1.Println;
      end.

      Sorting or ordering sequences

      • Sorted
      • SortedDescending
      • OrderBy(T -> TKey)
      • var s:=Seq(('Ivanov',20,1),('Petrov',19,2),('Popov',21,1));
        s.OrderBy(x->x[0]).Println; // (Ivanov,20,1) (Petrov,19,2) (Popov,21,1)
        s.OrderBy(x->x[1]).Println; // (Petrov,19,2) (Ivanov,20,1) (Popov,21,1)
      • OrderByDescending(T -> TKey)
      • To do: This function can be used, for example, to find k maximums in an array:

        ✍ Algorithm:

          begin
          var a:=Arr(1,3,5,2,7,9,0);
          var k:=3;
          a.OrderByDescending(x->x).Distinct.Take(k).Print; // 9 7 5
          end.

        Scalar Computation

      • Count([T -> boolean]): integer
      • var a:=Arr(1,2,3,4,5);
        var b:=a.Count(x->x mod 2 <> 0); // 3 odd elements
        NB: In the example Count is a filter(like Where), which calculates the number of odd elements.
        Lab.

        To do: Define a sequence using Seq method. Calculate a quantity of x (entered number) within the sequence. You should use count (condition) method.

        The result examples:

        -1 2 3 -5 2 -7 8 2 11
        enter x: 2
        there is 2 within the seq 3 times 
        

        ✍ Algorithm:

          begin
            var c:=Seq(-1,2,3,-5,2,-7,8,2,11);
            c.Println();
            var x:=readinteger('enter x:');
            var n:=c.count(c->c=x);
            println($'there is {x} within the seq {n} times ');
          end.
        {0.1 points} Task 13:

        To do: Define a sequence using Seq method. Calculate a number of negative elements in a sequence. You should use count (condition) method.

        Expected output:

        -1 2 3 -5 6 -7 8 9 11
        number of negative elements is 3
        

        [Program name: 17task-13.pas]

      • Average: double
      • Average(T -> числовой_тип): double
      • Sum: числовой_тип
      • Sum(T -> числовой_тип): числовой_тип
      • Lab.

        To do: The sequence of 10 integer elements is given. Calculate a sum of the seq elements.

        The result examples:

        0 1 2 3 4 5 6 7 8 9
        sum = 45
        

        ✍ Algorithm:

          1. Traditional approach:

          begin
          var q:=SeqGen(10,x->x).Println; 
          var s:=0.0;
          foreach var x in q do
            s+=x;
          print('sum = ', s)
          end.

          2. LINQ approach:

          begin
          var q:=SeqGen(10,x->x).Println; 
          q.Sum.Print
          end.
        {0.1 points} Task 14:

        To do: Calculate a product (multiplication) of 5 sequence elements.

        Expected output:

        1.2  3.1  6.7  2.8  3.4
        product:  237.27648 
        

        [Program name: 17task-14.pas]

        NB: Average, Sum, Max and Min — are not the filters, they are projections (like Select)
        Lab: Calculate the average of Fibonacci elements, which are even and have three-digits

        Algorithm:

        println(seqWhile(1,1,(x,y)->x+y,x->x div 1000=0)
          .where (x-> (x>100)and(x<=999)and (x mod 2 =0)).average);
        {0.1 points} Task 15:

        To do: Find the sum of the first Fibonacci numbers that are one- or two- digits. SeqWhile and sum methods must be used.

        Expected output:

        sequence: 1 1 2 3 5 8 13 21 34 55 89
        sum: 232 
        

        [Program name: 17task-15.pas]

        Lab:

        To do: Calculate the quantity of maximum elements within a sequence.

        Expected output:

        1 5 2 10 1 10
        number of max elements is 2 
        

        ✍ Algorithm:

          1. Traditional approach:

          begin
            var c := Seq(1, 5, 2, 10, 1, 10);
            c.Println();
            var k := c.Max();
            var res := 0;
            foreach var i in c do
              if i = k then res += 1;
            println('number of max elements is ', res);
          end.

          2. LINQ approach:

          begin
            var c := Seq(1, 5, 2, 10, 1, 10);
            c.Println();
            println('number of max elements is ', c.Count(x->x=c.Max));
          end.
        {0.2 points} Task 16:

        To do: Calculate a sum of odd elements in a sequence.

        Expected output:

        1 5 2 10 1 10
        sum of odd elements  7 
        

        [Program name: 17task-16.pas]

        {0.2 points} Task 17:
        The sequence is given: 1, 4, 5, 2, 7, 10, 1. Print out the elements with even indexes and count their quantity. You have to use where and count functions with conditions.

        Expected output:

        1 5 7 1
        4 
        

        [Program name: 17task-16.pas]

        {0.2 points} Task 18:
        The seq is given. Find a minimum element of the soubled elements of the seq

        Expected output:

        6 2 3 4
        4 
        

        [Program name: 17task-18.pas]

        {0.2 points} Task 19:
        There is a sequence of reals: 1.2, 3.5, 5.1, 2.2, 7.0, 9.6, 0.7. Output the rounded numbers in the same order (round()), as well as the sum of all rounded numbers. To display the final sequence, use the projection Select, and to calculate the sum — projection Sum must be used,and two variables to store the results.

        Expected output:

        1 4 5 2 7 10 1
        30 
        

        [Program name: 17task-19.pas]

      Lesson #16. Matrices

      Theory: Two-dimensional arrays

      Lecture in pdf format

      • Definition
      • A matrix or two-dimensional array is a rectangular table of numbers (or other elements of the same type). Each element of the matrix has two indices (row number and column number).

      • Matrix declaration
      • var a2: array [,] of integer;
        a2 := new integer[3,4];
        // or:
        var a := new integer[3,4];
      • Loop over the elements and pronting out:
      • for var i:=0 to a2.RowCount-1 do
          	for var j:=0 to a2.ColCount-1 do
            		a2[i,j] := i + j;  
         
        a2.Println;
        Println(a2); // [[0,1,2,3],[1,2,3,4],[2,3,4,5]]

      Matrix filling

        begin
          var a := Matr(3,4,1,2,3,4,5,6,7,8,9,10,11,12);  
          a.Println(3);
         
          var a1 := MatrGen(3,4,(i,j)->i+j+0.5); // using arrow operator
          a1.Println(5,1);
        end.
      • Filling with random numbers
      • begin
          var a := MatrRandomInteger(3,4);  
          a.Println(4);
         
          var a1 := MatrRandomReal(3,4,1,9);  
          a1.Println(6,2);
        end.

      Operations by rows and columns

      begin
        var a := MatrRandomInteger(3,4);  
        a.Println;
       
        a.Row(0).Sum.Println;
        a.Row(1).Average.Println;
        a.Row(2).Product.Println;
       
        a.Col(0).Min.Println;
        a.Col(1).Max.Println;
      end.

      Labs and tasks

      Lab 0. Two-dimensional array

      To do: Initialize a two-dimensional array named arr2d with given integer values, they are [[1, 2], [3, 4], [5, 6]].
      1) First, output all the elements of the array.
      2) After, output the following elements to the Output window (the elements to output are marked in red color):

      (1, 2)
      (3, 4) 
      (5, 6)
      

      Expected output:

      The array:
      1  2
      3  4
      5  6
      1-st element = 3, 2-nd element = 5
      

      ✍ Algorithm:

        begin
          var a := new integer[3,2];
         
          for var i:=0 to a.RowCount-1 do
          	for var j:=0 to a.ColCount-1 do
                  a[i,j]:=readinteger;  
         
          println('The array:');
          a.Println();
          Println(a[1,0], a[2,0]); 
        end.
      {0.6 points} Task 1:

      To do: The air temperature values for 4 days are given, they are taken from three weather stations located in different regions of the country:

      Station number 1-st day 2-nd day 3-d day 4-th day
      1 -8 -14 -19 -18
      2 25 28 26 20
      3 11 18 20 25

      That is, in a two-dimensional array it would look like this:

      t[0,0]=-8; t[0,1]=-14; t[0,2]=-19; t[0,3]=-18;
      t[1,0]=25; t[1,1]=28; t[1,2]=26; t[1,3]=20;
      t[2,0]=11; t[2,1]=18; t[2,2]=20; t[2,3]=25;

      or it is better to use matr function:

      var t := matr(3,4,-8,-14,-19,-18,25,28,26,20,11,18,20,25);

      To do:

      1. Output value of the temperature at the 2nd weather station during the 4th day and at the 3rd weather station during the 1st day (your result must be 20 and 11).
      2. Output the values of the temperature of all weather stations during the 2nd day (for loop is needed).
      3. Output the values of the temperature of all weather stations during all days.
      4. Calculate the average temperature at the 3rd weather station (for loop is needed).
      5. Output the days and the weather stations’ numbers where the temperature was in the range of 2426 degrees Celsius.

      Expected output:

      1-st task: 20  and  11
      2-nd task: -14 28 18
      3-d task:
      -8  -14  -19  -18
      25   28   26   20
      11   18   20   25
      
      4-th task: 18.5
      5-th task:
      station number 1  day 0
      station number 1  day 2
      station number 2  day  
      

      [Program name: 15task-01.pas]

      {0.2 points} Task 2:

      To do: Create a two-dimensional array 4-by-3 ([4,3]) with randomized integer values. Count positive elements within the array.

      Expected output:

      The array:
      2   5  -1
      6   7   8
      1   8   6
      -3  1  -6
      number of positive = 9
      

      [Program name: 15task-02.pas]

      {0.5 points} Task 3:

      To do: Create a two-dimensional array 4-by-5 ([4,5]) with randomized integer values. Create a function to find minimum and maximum elements of the array (FindMinMaxArr).

      Note: the signature (header) of the function should be as follows:

      function FindMinMaxArr(a: array [,] of integer): (integer, integer);

      Expected output:

      The array:
      10   2   9  3  4
      -3 -10 -14 -4  2
       2  -9  11  3 -10
      -1 -13  -5 -2  3
      min and max:
      -14  11
      

      [Program name: 15task-03.pas]

      Lab 1

      To do: Create a two-dimensional array 3-by-4 ([3,4]) using the rule:
      each element equals to i-th row * j-th column + 0.5
      Expected output:

      0.5  1.5  2.5  3.5
      1.5  2.5  3.5  4.5
      2.5  3.5  4.5  5.5
      

      ✍ Algorithm:

        begin
          var a1 := MatrGen(3,4,(i,j)->i+j+0.5);
          a1.Println(5,1);
        end.
      {0.2 points} Task 4:

      To do: Create a two-dimensional array 4-by-5 ([4,5]) using the rule: all elements of the i-th row have the value 10 ∗ i. To comlete the task you should use MatrGen standard function.

      Expected output:

          0    0    0    0    0
         10   10   10   10   10
         20   20   20   20   20
         30   30   30   30   30
      

      [Program name: 15task-04.pas]

      Extra tasks:

      1. Open taskBook of pascalAbc.net IDE:
      2. Choose ZMatrix group in the dropdown menu and click html-page button:
      3. Complete the tasks giving the files the proper names (ZMatrix1.pas etc.). Tasks #: 1, 2, 7, 8, 9, 10, 11, 12, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 18, 29, 30
      4. Or you can open pdf-file with all the tasks to translate them.
      Lab 2

      To do: Calculate sum in each row.

      The result examples:

        15  21   9  78
        54  61   2  19
        19  28  50  61
      123 136 158
      

      ✍ Algorithm:

        begin
          var a := MatrRandomInteger(3,4);  
          a.Println;
         
          var Sums := ArrGen(a.RowCount,r -> a.Row(r).Sum);
          Sums.Println;
        end.
      {0.2 points} Task 5:

      To do: Create a two-dimensional array 4-by-5 ([4,5]) with randomized integer values. Find maximum element in each row.

      Expected output:

        91   9  82  71  99
        59  30  36  35  26
        56  66  76   7  23
        25  46  92  39  77
      99 59 76 92
      

      [Program name: 15task-05.pas]

      {0.3 points} Task 6:

      To do: Create a two-dimensional array 4-by-5 ([4,5]) with randomized integer values in the [0,10] range. Create a function to return the array of the products (multiplications) in each column.

      Expected output:

         6   4   6   8   0
         6   4   5   3   7
         0   3   5   2   8
         6   4   6   3   8
      result:  [0,192,900,144,0] 
      

      [Program name: 15task-06.pas]

      Lab 3

      To do: Calculate a number of evens in each row.

      The result examples:

        49  98  78  27
        44  65  50  74
        68   1  75  59
      2 1 2 1
      

      ✍ Algorithm:

        begin
          var a := MatrRandomInteger(3,4);  
          a.Println;
         
          var EvensCount := ArrGen(a.ColCount,c -> a.Col(c).Count(x->x.IsEven));
          EvensCount.Println;
        end.
      {0.3 points} Task 7:

      To do: Create a two-dimensional array 4-by-5 ([4,5]) with randomized integer values. Create a procedure to print out the array of the quantities of elements in the range [0,10] in each row.

      Note: the signature of the procedure must be as follows:

      procedure arrCount(a:array[,] of integer);

      Expected output:

        59   6  34  70
        11  28  10  31
         8   0   9  80
      1 1 3
      

      [Program name: 15task-07.pas]

      Lab 4

      To do: The matrix is given. Does the matrix contain the element equaled to x? x is entered. You should output boolean value.

      The result examples:

         3   8   5   7
         1   7   6   1
         1   1   5   9
      enter x, please: 
      >> 6
      True 
      

      ✍ Algorithm:

        function Contains<T>(a: array [,] of T; x: T): boolean;
        begin
          Result := False;
          for var i:=0 to a.RowCount-1 do
           for var j:=0 to a.ColCount-1 do
             if a[i,j]=x then
             begin 
              Result := True;      
              exit;
            end;
        end;
         
        begin
          var a := MatrRandomInteger(3,4,1,10);  
          a.Println;
         
          var x:=readinteger('enter x, please:');
          var found := Contains(a,x);
          Println(found);
        end.
      {0.3 points} Task 8:

      To do: Create a two-dimensional array 3-by-4 ([3,4]) with randomized integer values. Create a function to print out the indices (row and column) of the array element equaled to entered x value. If x is not found, the function must return -1,-1.

      Note: the signature of the function must be as follows:

      function indicesArr<T>(a: array [,] of T; x: T): (integer,integer);

      Expected output:

         1   2   2  10
         3   4   7   5
         3   5   5  10
      enter x, please: 6
      (-1,-1) 
      ---
         3   6   7   1
         7   1   8   5
        10   2   4   6
      enter x, please: 7
      (0,2) 
      

      [Program name: 15task-08.pas]

      {0.8 points} Task 9:

      To do: M-by-N integer matrix is given (it is filled with randomized numbers). Find the number of its first row, which contains an equal quantity of positive and negative elements (zero matrix elements are not taken into account). If there are no such rows, then output 0.

      Note: you can do the task using one of the following ways: 1) iterating over the elements of the array; 2) using mass operations by rows and columns (.Row)

      Expected output:

      N: 
      >>3
      M: 
      >>4
        -5  -5   5  -1
         1  -1   0   0
         3  -3  -4   1
       
      result: 2
      

      [Program name: 15task-09.pas]

      Lesson #15. Arrays (slices, Sorting algorithms, Lists)

      Theory: slices, Sorting algorithms

      Lection in pdf format

      + and * operations for arrays
    • a + b – concatenation of two arrays into result array
    • a * N – concatenation of N copies of a into result array
    • Slices

      • Array slice is a subarray of original array
      • Slices are read-only and cannot be assigned values.
      • The slice type is the same as the array.
      • Slices work with arrays, strings, and lists.
      • It has one of two forms: a[x:y] or a[x:y:step]. Expressions x and y can be omitted.
      • Examples:

        begin
        var a := Arr(0,1,2,3,4,5,6,7,8,9);
        println(a[:4]); // 0 1 2 3
        println(a[4:]); // 4 5 6 7 8 9
        println(a[:a.Length-1]); // 0 1 2 3 4 5 6 7 8
        println(a[:]);      // 0 1 2 3 4 5 6 7 8 9  (copy of a)
        println(a[::2]);   // 0 2 4 6 8
        println(a[1::2]);  // 1 3 5 7 9
        println(a[4:1:-1]); // 4 3 2
        println(a[::-1]);   // 9 8 7 6 5 4 3 2 1 0  (reverse of a)
        end.

      Array sorting algorithms

        Selection sort
      • this algorithm iterates over the array over and over, moving one value to the correct position
      • it selects the smallest unsorted value
      • so, at the next iteration, we will find the minimum in the array after the current element and change it with it, if necessary. Thus, after the i-th iteration, the first i elements will stay in their places.
      • the sorted portion of the array is at the beginning
      • 1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        
        procedure SelectionSort(a: array of integer);
        begin
          for var i := 0 to a.High-1 do
          begin
            var (min,imin) := (a[i],i);
            for var j := i + 1 to a.High do
              if a[j] < min then
                (min,imin) := (a[j],j);
            Swap(a[imin],a[i]);
          end;
        end;

        Bubble sort
      • Let’s iterate over the array from left to right.
      • If the current element is greater than the next one, we swap them.
      • We do this until the array is sorted.
      • Note that after the first iteration, the largest element will be at the end of the array, in the correct place.
      • After two iterations, the two largest items will be in the correct place, and so on.
      • 1
        2
        3
        4
        5
        6
        7
        
        procedure BubbleSort(a: array of integer);
        begin
          for var i := 0 to a.High-1 do
            for var j := a.High downto i+1 do
              if a[j] < a[j-1] then
                Swap(a[j], a[j-1]);
        end;
        Insertion sort

        The Insertion sort algorithm iterates through the elements of the array one at a time, and places each new taken element in a suitable place among the previously ordered elements.

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        
        procedure SortByInsert(a: array of integer);
        begin
          for var i:=1 to a.High do
          begin
            var x := a[i];
            var j := i - 1;
            while (j >= 0) and (x < a[j]) do
            begin
              a[j+1] := a[j];
              j -= 1;
            end;
            a[j+1] := x;
          end;
        end;
        Standard sort
        Sort(a);
        SortByDescending(a);

      List type

      List definition

      var l := new List<integer>; // l.Count = 0

      To add an element to the end of a list:

      l.Add(8);
      // or:
      l += 8;

      Loop over the list:

      for var i:=0 to l.Count-1 do
        Print(l[i]);
      foreach var x in l do
        Print(x);

      List fill:

      var l := Lst(5,2,3);

      Methods

      l.Insert(ind,x); // insert x by index ind
      l.RemoveAt(ind); // delete element by index ind
      l.RemoveRange(ind,count) // delete a range of elements
      l.RemoveAll(x -> x.IsOdd); // delete elements by condition
      l.IndexOf(3); // index of first element or -1
      l.FindIndex(x -> x > 4); // index of first element or -1
      l.Clear;  
      l.Reverse; 
      l.Sort;

      Labs and tasks

      Slices

      Lab 1:
      To do: an array A of size N and an integer K (1 <= K <= N) are given. Print its elements with ordinal numbers (i.e. indexes) that are multiples of K (i.e. devisable by K):

      Ak, A2 * k, A3 * k ...

      Do not use the if statement.

      ✍ Algorithm:

        begin
        var n:=ReadInteger('how many elements');
        var a:=ReadArrReal(n);
        var k:=ReadInteger('K=');
        a[k-1 : : k].Print;
        end.
      {0.2 points} Task 1:

      To do: An array of size N is given. Print its elements in reverse order.

      The expected output:

      how many elements 
      >> 10
      array:
      25 5 68 42 48 32 100 77 50 47
      result:
      47 50 77 100 32 48 42 68 5 25
      

      [Program name: 14task-01.pas]

      {0.3 points} Task 2:

      To do: An array A of size N is given (N is an even number). Display its elements with even ordinal numbers in ascending order of ordinal numbers:

      а2, а4, а6, ... аn

      Do not use the conditional operator.

      The expected output:

      >>10
      64 64 21 72 22 82 62 50 30 25
      64 72 82 50 25
      

      [Program name: 14task-02.pas]

      {0.3 points} Task 3:

      To do: An array A of size N is given (N is an odd number). Display its elements with odd ordinal numbers, i.e. in descending order of ordinal numbers:

      аn, аn-2, аn-4, ... а1

      Do not use the conditional operator.

      The expected output:

      >>9
      array: 89 67 32 43 49 67 93 75 31
      result: 31 93 49 32 89
      

      [Program name: 14task-03.pas]

      Lab 2:

      To do: An array A of size N is given. Using slices operations and the + operation for arrays, get an array containing first the elements with even ordinal numbers(in ascending order of ordinal numbers), and then — elements with odd ordinal numbers (also in ascending order of ordinal numbers):

      a2, a4, a6, ... a1, a3, a5 ...

      Do not use conditional operator.

      The expected output:

      how many elements 
      >> 9
      4 96 8 94 14 80 93 49 6
      96 94 80 49 4 8 14 93 6
      

      ✍ Algorithm:

        begin
        var n:=ReadInteger('how many elements');
        var a:=arrRandomInteger(n);
        a.Println;
        var slice:=a[1::2]+a[::2];
        slice.Print
        end.
      {0.3 points} Task 4:

      To do: An array A of size N is given (N is odd number). Using slices operations and the + operation for arrays, get an array containing first its elements with odd indexes (in ascending order of their ordinal numbers), and then — elements with even indexes (in descending order of ordinal numbers). Create a slice to store a concatenation of those two slices:

      a2, a4, a6, ..., a7, a5, a3, a1

      Do not use conditional operator.

      The expected output:

      >>9
      array: 80 81 71 37 55 78 26 33 53
      result: 81 37 78 33 53 26 55 71 80
      

      [Program name: 14task-04.pas]

      Lab 3:

      To do: An array of size N and integers K and L (1 <= K <= L <= N) are given. Find the arithmetic mean (average) of the elements of an array with ordinal numbers from K to L inclusive.

      The expected output:

      >>10
      29 2 97 35 55 52 67 97 4 96
      k= >>2
      l= >>5
      resulting slice:  [2,97,35,55] 
      average = 47.25 
      

      ✍ Algorithm:

        begin
          var n := ReadInteger;
          var a := arrRandomInteger(n);
          a.Println;
          var k := ReadInteger('k=');
          var l := ReadInteger('l=');
          var slice := a[k - 1:l];
          println('resulting slice: ', slice);
          print($'average = {slice.Average}');
        end.
      Lab 4:

      To do: An array of size N is given. Find the minimum element of its even-numbered elements:

      a2, a4, a6, .....

      The expected output:

      >> 10
      96 79 71 87 61 21 51 74 67 89
      slice: [79,87,21,74,89] 
      21 
      

      ✍ Algorithm:

        begin
        var n:=ReadInteger;
        var a:=arrRandomInteger(n);
        a.Println;
        println('slice: ',a[1::2]);
        print(a[1::2].min);
        end.
      {0.3 points} Task 5:

      To do: An array of size N and integers K and L (1 <= K <= L <= N) are given. Calculate the sum of array elements except for elements with indexes from K to L inclusive.

      Note: you should use here the sum method:

      print(a[?:?:?].sum);
      // or
      slice.sum.print;

      The expected output:

      >> 10
      35 26 82 63 54 47 37 95 26 88
      K =  >> 4
      L =  >> 8
      257 
      

      [Program name: 14task-05.pas]

      {0.4 points} Task 6:

      To do: An array of size N (N is even) is given. Change the first half in it with the second (assume that the length of the array is an even number). Do not change the order of the elements in the halves.

      The expected output:

      >> 10
      68 57 63 91 52 56 78 51 33 83
      result: [56,78,51,33,83,68,57,63,91,52] 
      

      [Program name: 14task-06.pas]

      Lab 5: Insertion and deletion in an array

      To do 1: An array of N integers is given. It’s necessary to insert an element x on k-th index, k<=N.

      To do 2: An array of N integers is given. It’s necessary to delete an element with index k, k<N.

      The expected output:

      // to do 1:
      array: [5, 12, 1, 3, 11, 19]
      enter a number to insert 2
      enter an order number 3
      result:  [5,12,1,2,3,11,19] 
      
      // to do 2:
      array: [5, 12, 1, 3, 11, 19]
      enter an order number 
      >> 2
      result: [5,12,3,11,19] 
      

      ✍ Algorithm:

        // to do 1:
        begin
          var a := arr(5, 12, 1, 3, 11, 19);
          var x := ReadInteger ('enter a number to insert');
          var k := ReadInteger ('enter an order number');
          a := a[:k] + Arr(x) + a[k:]; 
          print('result: ', a)
        end.
        // to do 2:
        begin
          var a := arr(5, 12, 1, 3, 11, 19);
          var k := ReadInteger ('enter an order number');
          a := a[:k] + a[k+1:]; 
          print('result: ', a)
        end.
      {0.4 points} Task 7:

      To do: An array of integers is given. Find maximum element of the array and delete it. You should use slice to implement the task.

      Note 1: To find an index of the maximum element it is better to use a.IndexMax method.
      Note 2: Don’t forget to check if maximum is the last element of the array. In this case you should complete the task another way (use if statemnet).

      The expected output:

      array:  [5, 12, 1, 3, 11, 19] 
      result:  [5, 12, 1, 3, 11]  
      

      [Program name: 14task-07.pas]

      {0.4 points} Task 8:

      To do: An array of integers and N number are given (N is entered). Find minimum element of the array and insert N number before this element. You should use slice to implement the task.

      Note 1: To find an index of the minimum element it is better to use a.IndexMin method.
      Note 2: Don’t forget to check if minimum is the last element of the array. In this case you should complete the task another way (use if statemnet).

      The expected output:

      array:  [20,3,18,33,93,58,30,56,15,3] 
      enter N number please:  
      >> 20
      result:  [20,20,3,18,33,93,58,30,56,15,3]  
      

      [Program name: 14task-08.pas]

      Extra tasks:

      1. Open taskBook of pascalAbc.net IDE:
      2. Choose ArrSlice group in the dropdown menu and click html-page button:
      3. Complete the tasks giving the files the proper names (ArrSlice1.pas etc.)

      Array sorting algorithms

      Lab 6:

      To do: calculate a time to execute the algorithm of Bubble sort

      ✍ Algorithm:

        procedure MySort(a: array of integer);
          begin
        // bubble sort
            for var i := 1 to arr.High - 1 do
            for var j := 0 to arr.High - i do
              if arr[j] > arr[j + 1] then 
                Swap(arr[j], arr[j + 1]);
        end;
        begin
        var a:=arrRandomInteger(20000);
        // note the time
        var t:=System.DateTime.Now;
        // run the algorithm
        MySort(a);
        // note the time of algorithm end
        var t1:=System.DateTime.Now;
        println('The time to execute the algorithm: ',t1-t);
        //t:=System.DateTime.Now;
        end.
      {0.5 points} Task 9:

      To do: Calculate a time to execute the algorithm of Selection sort and Insertion sort. Compare the time and output the result

      Note: You should create two procedures with sorting algorithms (copy those algorithms from the Theory materials). And you’ll need to note a current time four times (before starting each algorithm and before finishing it).

      The expected output:

      The time to execute the Insertion algorithm:  00:00:00.5804751 
      The time to execute the selection algorithm:  00:00:00.9035547 
      

      [Program name: 14task-09.pas]

      Merging of two sorted arrays

      Lab 7:

      To do: Two sorted arrays a and b are given. Merge them into third sorted array.

      Resulting example:

      array 1: [1,3,11,19] 
      array 2: [1,13,21] 
      result: [1,1,3,11,13,19,21] 
      

      ✍ Algorithm:

        function Merge(a, b: array of integer; n, m: integer): array of real;
        begin
          Assert((0 < n) and (n < a.Length));
          Assert((0 < m) and (m < b.Length));
          a[n] := integer.MaxValue; // barrier
          b[m] := integer.MaxValue; // barrier
          SetLength(Result, m + n);
          var (ia, ib) := (0, 0);
          for var:= 0 to n + m - 1 do
            if a[ia] < b[ib] then
            begin
              Result[] := a[ia]; 
              ia += 1;
            end
            else
            begin
              Result[] := b[ib]; 
              ib += 1;
            end;
        end;
        begin
          var a := arr(1, 3, 11, 19);
          var b := arr(1, 13, 21);
          println('array 1:',a);
          println('array 2:',b);
          setLength(a, 5); // for extra element
          setLength(b, 4); // for extra element
          print('result: ', Merge(a, b, 4, 3)) // [1,1,3,11,13,19,21] 
        end.
      {0.5 points} Task 10:

      To do: Calculate a time to execute the algorithm of the lab before this task (with the function to Merge two arrays). Compare the time with a time, needed to complete the merging using standard sort algorithm:

      var c:=a+b;
      sort(c);

      The expected output:

      array 1: [1,3,11,19] 
      array 2: [1,13,21] 
      result array c: [1,1,3,11,13,19,21] 
      the time with standard sort method 00:00:00.0009962 
      result:  [1,1,3,11,13,19,21] 
      the time with function to merge 00:00:00.0009984  
      

      [Program name: 14task-10.pas]

      Lab 8:

      To do: An array of integers and n number is given (n is entered). You should output the index of the n number in the array, or ‘there is no n’ message if n is not in the array.

      The expected output:

      array:  [3,3,24,41,57,59,84,88,89,95] 
      enter n to find it:  
      >> 41
      index of n is:  3

      ✍ Algorithm:

        begin
          var a := arrrandominteger(10);
          sort(a);
          println('array: ', a);
          var n := readinteger('enter n to find it: ');
          var index := a.BinarySearch(n);
          if (n > 0) then
            print('index of n is: ', index)
          else
           print('there is no n ')
        end.
      {0.5 points} Task 11:

      To do: An array of integers and n number are given (n is entered). You should use a.BinarySearch(n) standard method to delete that n from the array. Also, you should use slices to do it.

      Note: to use BinarySearch() method you need the array to be sorted first. So, use Sort() method before searching.

      The expected output:

      array:  [6,71,85,33,41,75,75,84,38,57] 
      sorted array:  [6,33,38,41,57,71,75,75,84,85] 
      enter n to delete it:  
      >> 38
      result:  [6,33,41,57,71,75,75,84,85]  
      

      [Program name: 14task-11.pas]

      Lists

      Lab 9:

      To do: An array of N integers is given. Insert all even elements of the array into L1, and all odd elements into L2.

      The expected output:

      array: [17,25,8,17,21,9,19,22,19,24] 
      L1: 8 22 24
      L2: 17 25 17 21 9 19 19
      

      ✍ Algorithm:

        begin
          var a := arrrandominteger(10, 5, 25);
          println(a);
          var L1 := new List<integer>;
          var L2 := new List<integer>;
         
          foreach var x in a do
            if x.IsEven then
              L1 += x
            else L2 += x;
          L1.println;
          L2.println;
        end.
      {0.2 points} Task 12:

      To do: An array of integers is given (fill it with random generated numbers in the range [-5,20]). Insert all positive elements of the array into L1 list, and all negative elements into L2 list.

      The expected output:

      array:  [17,16,15,5,-2,2,-3,-5,16,-5] 
      L1: 17 16 15 5 2 16
      L2: -2 -3 -5 -5
      

      [Program name: 14task-12.pas]

      {0.4 points} Task 13:

      To do: A list of integers is given. Find maximum element of the list and delete it. You should use L.RemoveAt(k); standard list method.

      Note: To find an index of the maximum element it is better to use L.IndexMax method.

      The expected output:

      List: 0 93 71 88 99 44 50 36 72 1
      result:  [0,93,71,88,44,50,36,72,1]   
      

      [Program name: 14task-13.pas]

      {0.4 points} Task 14:

      To do: A list of integers and N number are given (N is entered). Find minimum element of the list and insert N number before this element. You should use L.Insert(ind,n); standard method.

      Note: To find an index of the minimum element it is better to use L.IndexMin method.

      The expected output:

      76 45 84 47 85 27 12 74 21 47
      enter n:  
      >> 20
      result:  [76,45,84,47,85,27,20,12,74,21,47]   
      

      [Program name: 14task-14.pas]

      Lesson #13. Arrays (continuation)

      Theory

      Lection in pdf format

      Filling an array with generated sequence. lambda expressions

      var a := Arr(1,3,5,7,9);   // [1,3,5,7,9] 
      var a := ArrFill(5,555);  // [555,555,555,555,555] 
      var a := Arr(55) * 4 + Arr(77) * 6;  // [55,55,55,55,77,77,77,77,77,77] 
      var a := ArrGen(10,i->i);   // [0,1,2,3,4,5,6,7,8,9]
      var a := ArrGen(10,i->i,1);  // [1,2,3,4,5,6,7,8,9,10] 
      var a := ArrGen(10,1,x->x+2);  // [1,3,5,7,9,11,13,15,17,19] 
      var a := ArrGen(10,1,x->x*2);  // [1,2,4,8,16,32,64,128,256,512]
      var a := ArrGen(10,1,1,(x,y)->x+y);  // [1,1,2,3,5,8,13,21,34,55]

      Array input and Randomly generated array

      var a:=ReadArrInteger(5); 
      var a:=ReadArrReal(5);
       
      var a:=new integer[10];
      a:=arrRandomInteger(10); // array of 10 generated integers from 0 to 99

      Params keyword to pass a varying number of parameters

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      
      function Sum(params a: array of integer): integer;
      begin
        Result := 0;
        foreach var x in a do
          Result += x;
      end;
       
      begin
        Print(Sum(1,3,5));
        Print(Sum(1,4,10,22,44));
      end.
    • In the case of more than one parameter, params should be the last one in the list
    • SetLength procedure

    • Standard SetLength function allocates the necessary memory to contain the array elements
    • 1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      
      function MakeArr (params a: array of integer): array of integer;
      begin
        var b := new integer[a.length];
        var j := 0;
        for var i := 0 to a.length - 1 do 
          if a[i] > 0 then
          begin
            b[j] := a[i];
            j += 1;
          end;
        SetLength(b, j); // to specify a particular value of b array size
        result := b;
      end;
       
      begin
        var a := arrRandomInteger(5, -5, 10); // array a [-1,9,9,7,-3,0,-2,1,1,-1] 
        println('array a', a);
        println('result of function, array b ', MakeArr(a)); // array b  [9,9,7,1,1] 
      end.

      Reassignment and copy function

      var a: array of integer := (1,3,5,7); 
      var b:=a; // [1,3,5,7]

      But!

    • If we now reassign the values of the elements of the array b, then the array a will also change:
    • var a: array of integer := (1,3,5,7); 
      var b:=a; b[2]:=1; 
      print(a); //[1,3,1,7]
    • To avoid this situation, you need to create array b as a copy of array a:
    • var a: array of integer := (1,3,5,7); 
      var b:=Copy(a); 
      b[2]:=1; 
      print(a); //[1,3,5,7]

      Standard functions and procedures

      • Reverse(a)
      • Reverses elements in a array

      • a.IndexOf(x)
      • Finds the position (index) of x in a array

      • a.LastIndexOf(x)
      • Finds the last position (index) of x in a array

      • a.Contains(x)
      • Checks if the a array contains x

      Labs and tasks

      Filling an array with generated sequence

      {0.2 points} Task 1:

      To do: Generate an array of integers from -20 to 30. You should use ArrGen() function.

      Expected output:

      [-20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3,
       -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
       22, 23, 24, 25, 26, 27, 28, 29, 30]
      

      [Program name: 13task-01.pas]

      {0.2 points} Task 2:

      To do: Generate an array of integers from -10 to 10 in increments of 2 (step = 2). You should use ArrGen() function.

      Expected output:

      [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10]
      

      [Program name: 13task-02.pas]

      {0.2 points} Task 3:

      To do: Generate an array of 20 numbers 5. You should use ArrFill() function.

      Expected output:

      [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
      

      [Program name: 13task-03.pas]

      {0.2 points} Task 4:

      To do: Generate an array of the products of twos of numbers beginning with 1: i.e. 1 * 2, 2 * 2, 2 * 4, …). You should use ArrGen() function with two variables (x & y).

      Expected output:

      [1,2,2,4,8,32,256,8192] 
      

      [Program name: 13task-04.pas]

      Params keyword. SetLength procedure

      Lab 1: Params keyword

      To do: Create a function to add any number of integers.

      ✍ Algorithm:

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        
        function Sum(params a: array of integer): integer;
        begin
          Result := 0;
          foreach var x in a do
            Result += x;
        end;
         
        begin
          Print(Sum(1,3,5));
          Print(Sum(1,4,10,22,44));
        end.
      • params keyword is used to make it able to pass a varying number of parameters.
      • In the case of more than one parameter, params should be the last one in the list
      {0.4 points} Task 5:

      To do: Create a PrintArr procedure that prints out any number of numbers, delimited by some character (the numbers must be understood as an array parameter, and there must be also a delim parameter, the value of which is a character). Inside the main program, call the procedure several times with different number of parameters.

      Note: Procedure call example:

      var a:=new integer[10];
      a:=arrRandomInteger(10);
      PrintArr(';',a);
      PrintArr('~',1,2,3);
      // some more procedure call

      Extra task: * Correct the PrintArr procedure so that there is no delimeter after the last element.

      Expected output:

      76 ; 22 ; 71 ; 92 ; 51 ; 68 ; 70 ; 47 ; 15 ; 37 ; 
      1 ~ 2 ~ 3 ~ 
      5 / 2 / 3 / 5 / 
      

      [Program name: 13task-05.pas]

      {0.4 points} Task 6:

      To do: Three integer array of different sizes are generated randomly. Write a procedure EvenDouble with one parameter: an integer array of any size. Procedure must double all the elements of the array with even values and print out the resulting array.

      Note: Inside the main program, call the procedure several times with the arrays of different sizes:

      var a := new integer[10];
      a := arrRandomInteger(5,-5,5);
      EvenDouble(a);
      var a1 := new integer[5];
      ...
      // some more procedure calls

      Expected output:

      the array before the task is done: [33,0,52,35,70,56,83,12,68,78] 
      result: 33 0 104 35 140 112 83 24 136 156 
      ---
      the array before the task is done: [5,-1,4,1,1] 
      result: 5 -1 8 1 1  
      

      [Program name: 13task-06.pas]

      Lab 2: SetLength

      To do: create a function to fill array b with positive numbers of array a

      ✍ Algorithm:

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        
        function MakeOddArrFunc(params a: array of integer): array of integer;
        begin
          var b := new integer[a.length];
          var j := 0;
          for var i := 0 to a.length - 1 do 
            if a[i] > 0 then
            begin
              b[j] := a[i];
              j += 1;
            end;
          SetLength(b, j);
          result := b;
        end;
         
        begin
          var a := arrRandomInteger(10, -5, 10);
          println('array a', a);
          println('result of function, array b ', MakeOddArrFunc(a));
        end.
      {0.4 points} Task 7:

      To do: Create a function to fill array b with local minimums of array a. The local minimum is the element that is less than each of its neighbours. The first and last element should not be considered as local minima.

      Expected output:

      array a [6,-2,3,-4,6] 
      result of function, array b  [-2,-4] 
      

      [Program name: 13task-07.pas]

      Lesson #12. Enumeration type. Arrays

      Theory: Enumeration type

      Lection in pdf format

      • An enumeration type, or enum, is a structure that enables you to create a variable with a fixed set of possible values. The most common example is to use an enum to define the day of the week. There are only seven possible values for days of the week, and you can be reasonably certain that these values will never change.
      • Creating and Using Enums

        • To create an enum, you declare it in your code before the main program with the following syntax, which demonstrates creating an enum called DayOfWeek, that contains short names of the days of the week:
        • type DayOfWeek = (Mon,Tue,Wed,Thu,Fri,Sat,Sun);
          begin
          //...
          end.
        • We can use for loop and case statement with an Enumeration type:
        • for var d:= Mon to Fri do
              case d of
            	Mon: Print('Monday');
            	Tue: Print('Tuesday');
            	Wed: Print('Wednesday');
            	Thu: Print('Thursday');
            	Fri: Print('Friday');
              end;
        • It’s more correct to use the variable of the created Enumeration type:
        • type Season = (Spring, Summer, Autumn, Winter);
           
          begin
            var d: Season; // the variable of enum type
            d := Season.Spring; // Set an enum variable using the typeName.value notation
            print(d); // Spring
            d:=Autumn; // Set an enum variable by name
            if d = Season.Summer then  // false
              print(d) 
          end.
        • An enumerated constant can be accessed directly by name, or you can use the typeName.value notation.
        • Enumerated values can be compared (<) :
        • DayOfWeek.Wed < DayOfWeek.Sat
        • For values of an enumerated type you can use the functions Ord, Pred and Succ, and the procedures Inc and Dec. The function Ord returns the ordinal value in the list of constants corresponding enumerated type, the numbering starts at the zero.
        • An instance function ToString is defined for an enumerated type, which returns a string representation of an enumerated variable.
        • type Season = (Winter,Spring,Summer,Autumn);
          var s: Season;
          begin
            s := Summer;
            writeln(s.ToString); // Summer
            writeln(s); // Summer  
          end.

        Theory: Arrays

        • Array is a set of elements of the same type sequentially located in memory. Each element has its own index.
        • We will use so called dynamic arrays. This means that they allocate memory dynamically - during program execution
        • Creating and using single-dimensional arrays
          begin
            var a: array of integer;
            a := new integer[3];
            a[0] := 5;
            a[1] := 2;
            a[2] := 3;
          end.

          or inside the same line of code:

          begin
            var a: array of integer;
            a := new integer[3](5,2,3);
            print(a)
          end.
        • The memory allocation and the size of such an array are set already during the program:
        • 1.

          var a: array of integer;
          var n:=readInteger;
          a:=new integer[n];

          2.

          var a: array of integer;
          a:=new integer[readInteger];

          3.

          var a: array of integer;
          var n:=readInteger;
          SetLength(a,n); // set the size
        • To return memory allocated by array we can assign a special nil value to an array variable:
        • var a := nil;
        • To iterate through the array elements by their indexes we can use for loop:
        • for var i:=0 to a.Length-1 do
            a[i] += 1;
        • For read-only access (without changing the values) we can use foreach loop:
        • foreach var x in a do
            Print(x)

        Labs and tasks

        Enumerations

        {0.5 points} Task 1:

        To do: Request user to input a number - a mark ('1', '2', '3', '4', '5'). Check the inputted number to print out the explanation of the mark (very_bad - '1', bad — '2', satisfactory - '3', good - '4', excellent - '5'). Provide also an answer for incorrect input. You should use an enumeration type.

        Note 1: entered mark must be stored at the variable of char type. Also, you should use a variable of enum type to output the explanation.

        Note 2: it is better to use case statement to check the entered value.

        Expected output:

        enter your mark, please (1..5) 
        >>>2
        The explanation for 2 is bad
        ---
        enter your mark, please (1..5) 
        >>>6
        The explanation for 6 is noSuchMark
        

        [Program name: 12task-01.pas]

        Lab 1, Generic functions:

        To do: Create a generic IsitDigit (D) function that returns true if entered integer D is a digit (a one-digit number, that is, D is in the range [0-9]). In the main program, output the value of this function for N (N ≥ 0) given numbers.

        Resulting example:

        enter how many numbers 2
        enter number  > 0 45
        False enter number  > 0 8
        True 
        

        ✍ Algorithm:

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          
          function IsitDigit<T>(d: T): boolean;
          begin
            var ch := [0..9];
            if d in ch then result := true 
            else result := false;
          end;
           
          begin
            var k := readInteger('enter how many numbers');
            assert(k > 0, 'entered number must be > 0');
            loop k do
            begin
              var n := readInteger('enter number  > 0');
              assert(n > 0, 'entered number must be > 0');
              print(IsitDigit(n));
            end;
          end.

        Arrays

        {0.3 points} Task 2:

        To do: Create two arrays. One is with integer elements, the other is for working with real numbers. Initialize each array with three values. Create procedure to display array elements. Call this procedure for both arrays.

        Note 1: To make the procedure generic, <T> is required (<T> means any type).

        procedure printArray<T>(a: array of T);

        Expected output:

        first array: 5  2  3 
        second array: 5.1  1.2  3 
        

        [Program name: 12task-02.pas]

        Lab 2, Array search:

        To do: search for a specified value in an array (display the index of an element).

        ✍ Algorithm:

          1. Without using generic function:

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          
          function IndexOf(a:array of integer;x:integer):integer;
          begin
            result:=-1;
            for var i:=0 to High(a) do
              if a[i]=x then
              begin
                result:=i;
                break
               end
          end;
          begin
          var a:=Arr(1,2,3,4,5);
          print(IndexOf(a,5))
          end.

          2. Using generic function:

          1
          2
          3
          4
          5
          6
          7
          8
          
          function IndexOf<T>(a:array of T;x:T):integer;
          begin
           // the same as in the previous example 
          end;
          begin
          var a:=Arr(1,2,3,4,5);
          print(IndexOf(a,5))
          end.

          When calling a generic function, compilation will be in two stages:

          1. Auto deduction of type T, comparison with real numbers, etc. numbers are integers, then T is defined as an integer.
          2. The body of the function is taken and replaced by T with integer (instantiation of a function with a specific type).

        {0.3 points} Task 3:

        To do: Create an array of 10 randomly generated integer elements. Create a procedure to output the elements of the array with even indexes.

        Note: The signature of a procedure must be as follows:

        procedure printEven(a:array of integer);

        Expected output:

        Array: 2 6 4 1 8 6 5 3 7 8 
        Elements with even indexes: 2 4 8 5 7 
        

        [Program name: 12task-03.pas]

        {0.4 points} Task 4:

        To do: Create a procedure to generate n elements of array, the values should be generated in the interval[minBound,maxBound]. The array must be output parameter. You should call the procedure in the main program twice with different arrays, after each calling print the array.

        Note 1: The random function must be as follows (minBound and maxBound are entered numbers, minBound < maxBound ):

        a[i]:=random(minBound, maxBound);

        Note 2: The signature of a procedure must be as follows:

        procedure generateArray(n: integer;var a:array of integer;minBound,maxBound:integer);

        Note 3: Don't forget to make input validation (n>0), use assert() function.

        Expected output:

        Array 1: [-2,3,5,-3,-1,-1,0,1,-3,2] 
        Array 2: [8,4,9,8,9]   
        

        [Program name: 12task-04.pas]

        {0.3 points} Task 5:

        To do: Create a procedure to find minimum and maximum of 10 real numbers of an array (10 element of the array should be generated and printed inside the main protgram). To search the minimum and maximum foreach loop must be used.

        Note 1: The signature of a procedure must be as follows:

        procedure printMinMax (a: array of real);

        Note 2: To display the reals it is better to use writelnFormat function, with specified number of digits after floating point, e.g.:

        writeFormat('{0:f2}', a); // f2 means 2 digits after floating point

        Expected output:

        array: 
        3.05 3.47 -0.53 3.84 -0.51 2.67 4.07 4.48 2.21 3.64 
        min = -0.53, max = 4.48  
        

        [Program name: 12task-05.pas]

        {0.2 points} Task 6_1:

        To do: Create a ArraySum function that returns the sum of the elements of a dynamic array. Pay attention to checking the input array.

        Note: Demonstrate the use of ArraySum function in the main program: create an array, print its length and sum of its elements.

        Expected output:

        array: 
        -94 -4 -30 -79 15 42 -83 -44 -74 0 
        sum = -351 
        

        [Program name: 12task-06.pas]

        {0.3 points} Task 6_2:

        To do: Create a ArraySum function that returns the sum of the elements of a dynamic array. Pay attention to checking the input array.

        Note 1: Create the TestArraySum procedure to test the correctness of the ArraySum fuction. Add some tests there. Make sure all tests from TestArraySum works well.

        function ArraySum(a: array of integer): integer;
        begin
        // TODO calculate the sum
        end;
        procedure TestArraySum;
        begin
          // array of one element:
          var a := new integer[1](0);
          Assert(ArraySum(a) = 0, 'arr-sum: [0] must be 0');
          a := new integer[1](-5);
          Assert(ArraySum(a) = -5,    'arr-sum: [-5]  must be  -5');
          // array of some elements:
          // TODO: type your tests here
        end;
        // --- main program ---
        begin
          TestArraySum;
          // all the rest code
        end.

        Note 2: Demonstrate the use of ArraySum function in the main program: create an array, print its length and sum of its elements.

        Expected output:

        array: 
        -94 -4 -30 -79 15 42 -83 -44 -74 0 
        sum = -351 
        

        [Program name: 12task-06_2.pas]

        Multi-file layout

        {0.5 points} Task 7:

        To do: Create a multi-file layout for the task #2 of current lesson.

        [Program name: 12task-07.pas]

        ✍ Algorithm:

        1. Create a file with a name DynArrs.pas. Add the code to give a name of the unit (unit DynArrs;) and add two sections - the interface section and implementation.

        unit DynArrs;
        // ======================================== interface section
        interface
        
        // ======================================== implementation section 
        implementation
        end.
        

        2. Find your solution of the task #2. Copy the header of the printArray procedure and paste it inside the interface section of your unit-file. Add the summary before the pasted code.

        ...
        
        interface
        
        /// <summary>
        /// prints array of any type
        /// </summary>
        procedure printArray<T>(a: array of T);
        
        ...
        

        3. Copy the body of the printArray procedure and paste it inside the implementation section of your unit-file. Add the comments before the pasted code.

        ...
        
        implementation
        
        // prints array of any type
        procedure printArray<T>(a: array of T);
        begin
          for var i := 0 to a.Length - 1 do
          begin
            print(a[i]);
          end;
          println
        end;
        
        ...
        

        4.Create a new main file with a name 12task-07.pas. Add the code to include the unit. In the main program create an array and call the printArray procedure.

        uses DynArrs;
        
        begin
          var a := new integer[3](1, 2, 3);
          printArray(a);
        end.
        
        {0.3 points} Task 8_1:

        To do: Create a PrintArrDelim procedure to display the array elements, separating them with some simbol (delim is a parameter of string type).

        Note: ThePrintArrDelim procedure must accept an array and a separator string. Use the default value for delim which is '; '.

        procedure PrintArrDelim(a: array of integer; delim: string := '; ');

        Expected output:

        The array with , as a separator: 
        1,  2,  3,
        The array with ~ as a separator:   
        1~  2~  3~  
        

        [Program name: 12task-08.pas]

        {0.5 points} Task 8_2:

        To do: Create a multi-file layout for the following task: create a PrintArrDelim procedure to display the array elements, separating them with some simbol (delim is a parameter of string type). To do the task, open the DynArrs.pas unit-file (of task #7) and add there all needed code. In the main file call the procedure several times with different separators.

        Note 1. ThePrintArrDelim procedure must accept an array and a separator string. Use the default value for delim which is '; '.

        procedure PrintArrDelim(a: array of integer; delim: string := '; ');

        Note 2. When you add the implementation code, you don't need to have a default value for the delim:

        procedure PrintArrDelim(a: array of integer; delim: string);

        Expected output:

        1,  2,  3,  
        1~  2~  3~  
        

        [Program name: 12task-08_2.pas]

        {0.5 points} Task 9:

        To do: Create a multi-file layout for the Task #4 of the current lesson. To do the task, open the DynArrs.pas unit-file and add there all needed code (the code of generateArray procedure).

        Expected output:

        Array 1: [-2,3,5,-3,-1,-1,0,1,-3,2] 
        Array 2: [8,4,9,8,9]
        

        [Program name: 12task-09.pas]

        {0.5 point} Task 10_1:

        To do: Print the number of positive elements of given array. You need to write two different subroutines for this problem:
        1) Create a positiveArr function with the array as a parameter, returning a number of positives.
        2) Create a printPositiveArr procedure with two parameters: the input parameter that is an array of integers and output counter of the positives.

        Expected output:

        array:
        1  -5  2  -9  8
        result with function: 3
        result with procedure: 3
        

        [Program name: 12task-10.pas]

        {1.0 point} Task 10_2:

        To do: Create a multi-file layout for the following task: Print the number of positive numbers of the given array. You need to write two different solutions to this problem:
        1) positiveArr function with the array as a parameter, returning a number of positives.
        2) printPositiveArr procedure with two parameters: the input parameter that is an array of integers and output counter of the positives.
        To do the task, open the DynArrs.pas unit-file and add there all needed code. In the main file create an array and call the procedure and function.

        Note. Create test procedures for positiveArr function. Add the code to the unit-file.
        Expected output:

        array:
        1  -5  2  -9  8
        result with function: 3
        result with procedure: 3
        

        [Program name: 12task-10_2.pas]

      Lesson #11. Procedures and functions: tuples, algorithm wrappers, Local and global variables

      Theory: Procedures and Functions

      Lection in pdf format

      Input validation: Assert statement

      Task Example:

      To do: Create the Mean (X, Y, AMean, GMean) procedure that calculates the arithmetic mean AMean = (X + Y) / 2 and the geometric mean GMean = (X Y) 1/2 of two positive numbers X and Y (X and Y are entered, AMean and GMean are real output parameters).

      ✍ Решение:

      • The programmer must «secure» the program against incorrect input data.
      • The positivity of the parameters X and Y is necessary for calculating the geometric mean, which occurs inside the Mean procedure. So, the check must be inside the Mean procedure:
      • /// calculates aMean and gMean
        procedure Mean(...);
        begin
          Assert(x > 0);
          Assert(y > 0);
          // calculating AMean, GMean
          // ...
        end;
        
      • Mean procedure has two input and two output parameters. This means that each test case must check that for the given X and Y values, both output parameters have the expected values. I.e:
      • you need to set the values of the input parameters (X, Y);
      • call the Mean procedure by passing these input values to it;
      • check that the values of the output parameters (AMean, GMean) are the same as expected.
      • /// returnes true, if the reals x and y are equaled with precision eps
        function AreEquals(x, y: real; eps: real): boolean;
        begin
          Result := Abs(x - y) < eps;
        end;
         
        /// Tests the Mean procedure
        procedure TestMean(eps: real);
        begin
          var x, y: real;
          var am, gm: real;
          // test 1: equal values
          x := 2;
          y := x;
          Mean(x, y, am, gm);
          Assert(AreEquals(am, x, eps) 
            and AreEquals(gm, x, eps));
          // test 2: different values
          Mean(3, 27, am, gm);
          Assert(AreEquals(am, 15, Eps) 
            and AreEquals(gm, 9, Eps));
          // test 3: different values
          Mean(6.05, 5, am, gm);
          Assert(AreEquals(am, 5.525, Eps) 
            and AreEquals(gm, 5.5, Eps));
        end;
         
        const Eps = 0.00000001;
         
        begin
          // call of the test procedure
          TestMean(Eps);
         
          // main program
          // ...
        end.

      Labs and tasks

      Function and tuples

      Lab, Functions that return tuples:

      To do: Create a function to print sum and product of two numbers.

      ✍ Algorithm:

        function PrintSumMult(x, y: real): (real, real);
        begin
          Result := (x + y, x * y);
        end;
         
        begin
          var (a, b) := PrintSumMult(2, 4);
          Print(a, b); // 6  8
        end.
      {0.4 points} Task 1:

      To do: Find a minimum and maximum among 3 numbers. Create a function to do the task. The function return type is a tuple (min and max).

      Note: to print correct results you must unpack them.

      The expected output:

      enter three numbers:
      >>>3 >>>5 >>>1  
      min = 1, max = 5
      ---
      enter three numbers:
      >>>7 >>>0 >>>6  
      min = 0, max = 7
      

      [Program name: 11task-01.pas]

      Lab, Short definitions + tuples:

      To do: Create a procedure and function to print sum and product of two numbers. Use short definition.

      ✍ Algorithm:

        Fucntion:

        function PrintSumMult(x, y: real) := (x + y, x * y);
        begin
          var (a, b) := PrintSumMult(2, 4);
          Print(a, b); // 6 8
        end.

        Procedure:

        procedure PrintSumMult(x, y: real; var add, mult: real);
        begin
          add := x + y;
          mult := x * y;
        end;
        begin
          var (x, y) := ReadReal2; 
          var a, b: real;
          PrintSumMult(x, y, a, b);
          Print(a, b); 
        end.
      {0.5 points} Task 2:

      To do: Create procedure and function inside the same program to print a left digit and right digit of two-digit number (the number is entered and passed in as a parameter).

      Note 1: You must use short definitions.

      Note 2: Procedure and function must be defined one by one before the main program.

      The expected output:

      please, enter two-digit number: 37
      results with function: 
      3 7 
      results with procedure: 
      3 7 
      

      [Program name: 11task-02.pas]

      Functions as algorithm wrappers

      {0.3 points} Task 3:

      To do: Create a function to output the day of the week by it’s sequence number.

      The expected output:

      please, enter a number 1 - 7:
      >>>3  
      Tuesday
      ---
      please, enter a number 1 - 7:
      >>>1  
      Sunday
      

      [Program name: 11task-03.pas]

      {0.4 points} Task 4:

      To do: Create a function to calculate the quantity of positive numbers among n generated numbers (random() function must be used).

      The expected output:

      How many numbers?
      >>> 5 
      2   4  -3   5  -4 
      3 positive numbers
      

      [Program name: 11task-04.pas]

      {0.5 points} Task 5:

      To do: Create a function to calculate an addition of digits of entered integer number (entered number is a parameter of the function).

      The expected output:

      please, enter an integer:
      >>>173
      sum = 11
      

      [Program name: 11task-05.pas]

      {0.4 points} Task 6:

      To do: Create IsDigit(A) function, which returns true if entered integer A represents a digit (that is A is in the range [0,9]). In the main program call this function for 4 given numbers (the function call has to be inside a loop).

      The expected output:

      Please, enter the number:
      >>>35 
      false
      
      Please, enter the number:
      >>>3 
      true
      
      Please, enter the number:
      >>>9 
      true
      
      Please, enter the number:
      >>>10 
      false
      

      [Program name: 11task-06.pas]

      Assert statement

      Lab, assert:

      To do: Create an IsDigit(D) function, which returns true if entered integer D is a digit (that is D is in the range [0,9]). In the main program output the results of this function for N entered numbers.

      ✍ Algorithm:

        function IsDigit(d : integer):= (d >= 0) and (d <= 9);
         
        procedure TestIsDigit;
        begin
          for var i := 0 to 9 do
            Assert(IsDigit(i)=true,'incorrect function algorithm');
        end;
        begin
          TestIsDigit;
         
          var N := ReadInteger();
          Assert(n >= 0);
         
          for var i:=1 to n do
          begin
            var a := ReadInteger();
            Print(IsDigit(a));
          end;
        end.
      {0.3 points} Task 7:

      To do: Open the code of solution of Task 1 (about minimum and maximum). Add to your code the procedure to test the correctness of the function (look at the note below). Call this procedure inside the main program. Check the output.

      Note: This code must be added to your solution. Fulfil TODO places:

       
      procedure TestFindMinMax; // procedure to test the correctness of the function
      begin
        Assert(findMinMax(4, 1, 5) = (1,5), 'algorithm of findMinMax function is not correct');
        Assert(findMinMax(-5, 500, 5) = (-5,500), 'algorithm of findMinMax function is not correct');
        // TODO: add 3 or 4 your own tests
      end;
       
      begin // main program
        TestFindMinMax;
        //...
      end.

      The expected output:

      enter three numbers:
      >>>3 >>>5 >>>1  
      min = 1, max = 5
      ---
      enter three numbers:
      >>>7 >>>0 >>>6  
      min = 0, max = 7
      

      [Program name: 11task-07.pas]

      {0.6 points} Task 8:

      To do: Open the code of solution of Task 2. Create the procedure to test the correctness of your function. Call this procedure inside the main program. Check the output.

      Note: Look at the example of the Lab (Assert) to check: 1) if entered number is two-digit number; 2) and if the test procedure returns the correct results (create 2 or 3 tests must be done):

      function IsTwoDigit(...):= ...;
      procedure Test...; // procedure to test the correctness of the function
      begin
        Assert(..., 'error: the function is incorrect'); // test #1
        Assert(..., 'error: the function is incorrect'); // test #2
       
      end;
       
      begin // main program
        Test...;
        var numb:=readinteger('please, enter two-digit number:');
        Assert(IsTwoDigit(numb), 'error: number must be of two digits');
        //...
      end.

      The expected output:

      please, enter two-digit number: 37
      results with function: 
      3 7 
      

      [Program name: 11task-08.pas]

      {0.5 points} Task 9:

      To do: Open the code of solution of Task 3. Create the procedure to test the correctness of your function (3 or 4 tests must be done). Call this procedure inside the main program. Also, you must check the correctness of the input (the quantity of generated numbers must be greater than zero).

      The expected output:

      please, enter a number 1 - 7:
      >>>3  
      Tuesday
      ---
      please, enter a number 1 - 7:
      >>>1  
      Sunday
      ---
      please, enter a number 1 - 7:
      >>>0
      ! exception: entered number must be in the interval 1 - 7
      

      [Program name: 11task-09.pas]

      {0.5 points} Task 10:

      To do: Open the code of solution of Task 5. Create the procedure to test the correctness of your function (3 or 4 tests must be done). Call this procedure inside the main program.

      The expected output:

      please, enter an integer:
      >>>173
      sum = 11
      

      [Program name: 11task-10.pas]

      Lesson #10. Procedures and functions

      Theory: Procedures and Functions

      Lection in pdf format

      Labs and tasks

      Procedures

      Parameterless procedure and with parameters

      Lab 1, procedures:

      To do: Print 60 asterisks (star *), each on a new line. Use parameterless procedure.

      ✍ Решение:

        procedure pr(a:char); {a is a formal parameter}
        begin
        loop 60 do begin
          println(a);
        end;
        end;
        begin
        writeln('enter character:');
        var s:= readchar;
          pr(s); {s is an actual parameter}
        end.
      {0.3 points} Task 1, procedures:

      To do: Create a procedure that sums any two entered integers (two parameters).

      Note: the signature or header of the procedure must be as follows:

      procedure PrintSum(a, b: integer);

      The expected output:

      enter two numbers:
      >>> 2  >>> 7
      result: 2 + 7 = 9
      

      [Program name: task-01-proc.pas]

      {0.3 points} Task 2, procedures:

      To do: Create a procedure that displays in a column all the integers between N going down to 0 (starting with N).

      Note: the signature or header of the procedure must be as follows:

      procedure PrintIntegers(n: integer);

      The expected output:

      please, enter value of N: 
      >>> 8
      8 
      7 
      6 
      5 
      4 
      3 
      2 
      1 
      0 
      

      [Program name: task-02-proc.pas]

      {0.4 points} Task 3, procedures:

      To do: Create a procedure PrintSeq(A,B,C) (A<B) that prints the sequence of numbers from A to B with a step C (A, B and C are input parameters).

      Note: the signature or header of the procedure must be as follows:

      procedure PrintSeq(A,B,C: integer);

      The expected output:

      please, enter numbers A, B, C: 
      >>> 2  >>> 9  >>> 2
      2 4 6 8 
      

      [Program name: task-03-proc.pas]

      {0.5 points} Task 4, procedures:

      To do: Create a procedure that prints all the divisors of the number passed to it (the numer is entered in the main program and passed in to the procedure as a parameter).

      Note: the signature or header of the procedure must be as follows:

      procedure PrintDivisors(numb: integer);

      The expected output:

      please, enter number: 
      >>>18
      1 2 3 6 9 18 
      

      [Program name: task-04-proc.pas]

      Input and Output parameters

      Lab 2, procedures:

      To do: Let’s create a subroutine for calculating the arithmetic mean (average) of two entered integer values.

      ✍ Algorithm:

        procedure CalcAMean(a, b: integer; var Mean: real); // Mean is an output parameter
        begin
          Mean := (a + b) / 2;
        end;
         
        begin
          var (x, y) := (3, 5);
          var Mean: real;
          CalcAMean(x, y, Mean);
          Print(Mean);
          CalcAMean(2 * 2, 8, Mean);
          Print(Mean);
        end.
      Lab 3, procedures:

      To do: Create a procedure to swap the values of two variables.

      The expected output:

      a = 10
      b = 12
      Result:  a=12,  b=10

      ✍ Algorithm:

        Solution 1:

        procedure Swap(var a, b: integer);
        begin
          var t := a;
          a := b;
          b := t;
        end;
         
        begin
          var (x, y) := (3, 5);
          Swap(x, y); 
          println(x,y);
        end.

        Solution 2:

        procedure Swap(var a, b: integer);
        begin
          (a, b) := (b, a);
        end;
         
        begin
          var (x, y) := (3, 5);
          Swap(x, y); 
          println(x, y);
        end.
      {0.3 points} Task 5, procedures:

      To do: Create a procedure PlusN(N, result) that calculates N + N and passes the result in the result parameter (N is input parameter, result is output parameter).

      Note: the signature or header of the procedure must be as follows:

       procedure PlusN(N : integer; var result: integer);

      The expected output:

      please enter an integer n
      >>>5
      result: 10 
      

      [Program name: task-05-proc.pas]

      {0.4 points} Task 6, procedures:

      To do: Create a procedure Power2N(N, powerN) that calculates the power of a number (N^powerN) and passes the result in the result parameter (N and powerN are input parameters, result is an output parameter).

      Note: the signature or header of the procedure must be as follows:

      procedure PowerN(n, powerN: real; var result: real);

      The expected output:

      please enter number and exponent
      >>>3  >>>4
      3^4 = 81 
      

      [Program name: task-06-proc.pas]

      {0.4 points} Task 7, procedures:

      To do: Create a procedure FindMin(a,b, min) that finds the minimum of two entered numbers a and b and passes the result in min parameter (a and b are input parameters, min is an output parameter).

      The expected output:

      enter two integers for a and b: 
      >>>2 >>>6
      min is 2 
      

      [Program name: task-07-proc.pas]

      {0.4 points} Task 8, procedures:

      To do: Create a procedure AddLeftDigit(D, K, res) that appends entered digit K (0<=K<=9) on the left to entered digit D (0<=D<=9) (D and K are input parameters, res is output parameter). Pass the result to the main program in the res parameter.

      The expected output:

      enter values for D (0<=D<=9) and K(0<=K<=9):
      >>>2  >>>4  
      result: 42
      

      [Program name: task-08-proc.pas]

      {0.5 points} Task 9, procedures:

      To do: Create a procedure FindSum(N, sum) that calculates the addition (sum) of N generated numbers. Result is passed to the main program in sum parameter (N is an input parameter, sum is an output parameter).

      The expected output:

      Please, input how many numbers to add:
      >>>5
      generated numbers:
      7 3 2 8 12
      sum is 32
      

      [Program name: task-09-proc.pas]

      {1.5 points} * ExtraTask 10, procedures:

      To do: Create a procedure AddLeftDigits(D, K1,K2, res1, res2) that first appends entered digit K1 (0<=K1<=9) to entered positive integer D and passes the result in res1 parameter, and, afterwards, appends digit K2 to it and passes the result in res2.

      The expected output:

      Please, input  D,  K1 and K2 (0<=K<=9):
      20   4   5  
      >>> 204   2045 
      ---
      342  7  1
      >>> 3427   34271
      

      [Program name: task-10-proc.pas]

      Functions

      Lab 1, functions:
      To do: Find the maximum among two numbers using the function.

      The expected output:

      ✍ Algorithm:

        function max(a, b: integer): integer;
        begin
          if a > b then Result := a
          else Result := b;
        end;
         
        begin
          var (x, y) := readinteger2;
          println('maximum = ', max(x, y))
        end.
      {0.3 points} Task 1, functions:

      To do: Create a function to find a minimum among three numbers (three parameters of the function).

      The expected output:

      please, input three numbers
      >>>2  >>>5  >>>9
      minimum = 2 
      

      [Program name: task-01-func.pas]

      {0.3 points} Task 2, functions:

      To do: Create a function to find an average value (the arithmetic mean) of three entered numbers (three parameters).

      The expected output:

      please, input three numbers
      >>>2  >>>5  >>>2
      average = 3 
      

      [Program name: task-02-func.pas]

      {0.3 points} Task 3, functions:

      To do: Create an IsDigit(D) function, which returns true if entered integer D is a digit (that is D is in the range [0,9]). In the main program output the results of this function for 3 entered numbers.

      The expected output:

      please, input number #1
      42
      false
      ---
      please, input number #2
      4
      true
      ---
      please, input number #3
      -5
      true
      

      [Program name: task-03-func.pas]

      Lab 2, functions:
      To do: Create a function to calculate a factorial of entered number.

      The expected output:

      Enter number:
      >>>5
      5! = 120

      ✍ Algorithm:

        function Fact(n: integer): integer;
        begin
          Result := 1;
          for var i := 1 to n do
            Result *= i
        end;
         
        begin
          var x:=readinteger('enter number:');
          println($'{x}! = {Fact(5)}' )
        end.
      {0.4 points} Task 4, functions:

      To do: Create a function that calculates the sum of all numbers from 1 to N. N is a function parameter.

      The expected output:

      Enter the number N:
      100
      the sum = 5050
      

      [Program name: task-04-func.pas]

      Lab 3, short function definition:
      To do: Create a function to calculate a hypotenuse of triangle (the sides of triangles are entered). Use this function to calculate the hypotenuse of 5 triangles.

      ✍ Algorithm:

        function Hypot(a, b: real) := Sqrt(a * a + b * b); 
         
        begin
          loop 5 do
          begin
            var (a, b) := ReadlnReal2('Enter sides a,b:');
            Println(Hypot(a, b))
          end;
        end.
      {0.4 points} Task 5, functions:

      To do: Create a CircleS(R) function of real type that returns the area of a circle with radius R (R is entered real). Use this function to find the area of three circles with these radii. The area of a circle of radius R is calculated by the formula S=π*R2. As the value of PI (π), use 3.14. Use short function definition.

      The expected output:

      Enter radius 
      >>>5
      S = 
      ---
      Enter radius
      >>>7.8
      S = 
      

      [Program name: task-05-func.pas]

      {0.4 points} Task 6, functions:

      To do: Create a function that calculates a power of a number. A base number and exponent are the parameters of the function. Use short function definition.

      Note: To use the power() function, remember that parameters of this function are reals.

      The expected output:

      Enter number and exponent: 
      >>>5  >>>2
      5 ^ 2 = 25
      

      [Program name: task-06-func.pas]

      {0.5 points} Task 7, functions:

      To do: Create a the Triangle(a, h) function that calculates a perimeter of an isosceles triangle by its base a and height h drawn to the base (a and h are entered integers). By calling this function output the perimeters of the three triangles (perimeter = sum of the lengths of all the sides). To find the side b of a triangle, use the Pythagorean theorem: b2=(a/2)2+h2.

      The expected output:

      Enter a and h 
      >>>5  >>>2
      perimeter = 11.40
      

      [Program name: task-07-func.pas]

      {0.3 points} Task 8, functions:

      To do: Complete the previous task (# 7) by adding an overloading function to calculate a perimeter of an isosceles triangle for real values of a and h. Call this function twice — for integer arguments and real arguments.

      The expected output:

      Enter a and h 
      >>>5  >>>2
      perimeter = 11.40
      ---
      Enter a and h 
      >>>2.5  >>>6.8
      perimeter = 16.33
      ---
      Enter a and h 
      >>>15.2  >>>18.3
      perimeter = 54.83
      

      [Program name: task-08-func.pas]

      Вставить формулу как
      Блок
      Строка
      Дополнительные настройки
      Цвет формулы
      Цвет текста
      #333333
      Используйте LaTeX для набора формулы
      Предпросмотр
      \({}\)
      Формула не набрана
      Вставить