Lesson #16. Sequence

Theory

Lection in pdf format

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)); // делим поровну на 4 части [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.

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.
  • 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;

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

Labs and tasks

Lab 1.

To do: Ask user to input 10 integer elements of the sequence. Calculate a sum of the seq elements.

The result examples:

1
2
3
4
1
6
7
2
5
6
sum = 37 

✍ Algorithm:

    begin
    var q:=ReadSeqReal(10); 
    var s:=0.0;
    foreach var x in q do
      s+=x;
    print('sum = ', s)
    end.
{0.3 points} Task 1:

To do: Create the function to calculate the product (multiplication) of 5 entered sequence elements.

Note: the signature of the function:

function Product(q: sequence of real):real;

The resulting example:

Please, enter 5 real numbers:
1.2
3.1
6.7
2.8
3.4
product:  237.27648 

[Program name: 16task-01.pas]

{0.2 points} Task 2:

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

The resulting example:

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

[Program name: 16task-02.pas]

{0.2 points} Task 3:

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

The resulting example:

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

[Program name: 16task-03.pas]

Lab 2: Methods

To do: Create a function that searches in a sequence for the quantity of maximum elements.

The resulting example:

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

✍ Algorithm:

    function findCountMax(a: sequence  of integer):integer;
    begin
    var k:=a.Max();
      foreach var i in a do
        if i=k then result+=1;
    end;
    begin
      var c:=Seq(1,5,2,10,1,10);
      c.Println();
      println('number of max elements is ',findCountMax(c));
    end.
{0.4 points} Task 4:

To do: Create a function that calculates a sum of odd elements in a sequence. You should use IsOdd method within the foreach loop.

The resulting example:

1 5 2 10 1 10
sum of odd elements  7 

[Program name: 16task-04.pas]

Lab 3.

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.3 points} Task 5:

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

The resulting example:

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

[Program name: 16task-05.pas]

Sequence generators with lambda-expressions

{0.2 points} Task 6:

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

The resulting example:

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

[Program name: 16task-06.pas]

{0.2 points} Task 7:

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

The resulting example:

3 9 27 81 243 729 2187 6561 19683

[Program name: 16task-07.pas]

{0.3 points} Task 8:

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)

The resulting example:

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: 16task-08.pas]

{0.2 points} Task 9:

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

The resulting example:

2017 2012 2007 2002 1997 1992 1987 1982 1977 1972

[Program name: 16task-09.pas]

Lab:

To do: Create a sequence of N Fibonacci numbers

The resulting example:

Enter n 
>>8
1 1 2 3 5 8 13 21

✍ Algorithm:

    begin
    var n:=readInteger('Enter n');
    var sq:=SeqGen(n,1,1,(x,y)->x+y);
    sq.println();
    end.
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)

The resulting example:

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.4 points} Task 10:

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)

The resulting example:

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

[Program name: 16task-10.pas]

{0.4 points} Task 11:

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)

The resulting example:

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

[Program name: 16task-11.pas]

{0.4 points} Task 12:

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)

The resulting example:

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

[Program name: 16task-12.pas]

Lesson #15. Matrices

Theory: Two-dimensional arrays

Lection 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)

The result examples:

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.

The resulting example:

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: Fill a two-dimensional array 4-by-3 ([4,3]) with random integer values. Count positive elements within the array.

The resulting example:

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: Fill a two-dimensional array 4-by-5 ([4,5]) with random integer values. Create a function to find a 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);

The resulting example:

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: Fill a two-dimensional array 3-by-4 ([3,4]) using the rule:
each element equals to i-th row * j-th column + 0.5
The result examples:

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: Fill a two-dimensional array 4-by-5 ([4,5]) using the rule: all elements of the i-th row have the value 10 ∗ i.

The resulting example:

    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]

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: Fill a two-dimensional array 4-by-5 ([4,5]) with random integer values. Calculate maximum element in each row.

The resulting example:

  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: Fill a two-dimensional array 4-by-5 ([4,5]) with random integer values in the range [0,10]. Create a function to return the array of the products (multiplications) in each column.

The resulting example:

   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: Fill a two-dimensional array 4-by-5 ([4,5]) with random integer values. Create a procedure to print out the array of the quantities of the matrix elements in the range [0,10] by rows.

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

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

The resulting example:

  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.

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: Fill a two-dimensional array 3-by-4 ([3,4]) with random 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);

The resulting example:

   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 generated random numbers). Find the number of the first of its rows containing 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)

The resulting example:

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

[Program name: 15task-09.pas]

Lesson #14. 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);

    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 resulting example:

    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 resulting example:

    >>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 resulting example:

    >>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. First, output its 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 resulting example:

    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). First, output 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 resulting example:

    >>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 numbers from K to L inclusive.

    The resulting example:

    >> 10
    59 87 0 37 57 69 79 19 100 5
    K=  >> 2
    L=  >> 4
    41.3333333333333 
    

    ✍ 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].Average;
      slice.Print;
      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 resulting example:

    >> 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
    print(slice.sum);

    The resulting example:

    >> 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 resulting example:

    >> 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 resulting example:

    // 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: To find an index of the maximum element it is better to use a.IndexMax method.

    The resulting example:

    array:  [66,46,26,64,73,62,37,57,46,9] 
    result:  [66,46,26,64,62,37,57,46,9]  
    

    [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: To find an index of the maximum element it is better to use a.IndexMin method.

    The resulting example:

    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]

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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.

    The resulting example:

    [-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.

    The resulting example:

    [-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.

    The resulting example:

    [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).

    The resulting example:

    [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 parameters, delimited by a semicolon (there must be two parameters: array and delim). Use the default value for delim = '; '. 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.

    The resulting example:

    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: An integer array is given. 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 number of such elements.

    Note: Inside the main program, call the procedure several times with different number of parameters. Generate random array of different number of elements:

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

    The resulting example:

    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 neighbors. The first and last element should not be considered as local minima.

    The resulting example:

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

    [Program name: 13task-07.pas]


    Standard functions and procedures and Transformation of an array elements

    Lab 3:

    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 4:

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

    The resulting example:

    [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 5:

    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 8:

    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 position of x number (x is entered)
    3. the last position 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()).

    The resulting example:

    
    

    [Program name: 13task-08.pas]

    Lab 6, 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.

    The resulting example:

    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 9:

    To do: Create a randomly generated array. Use loop over some indices to print out:

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

    The resulting example:

    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: 13task-09.pas]

    Lab 7:

    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 8:

    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 10:

    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.

    The resulting example:

    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: 13task-10.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.

      The resulting example:

      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 dynamic 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);

      The resulting example:

      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);

      The resulting example:

      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 signature of a procedure must be as follows:

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

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

      The resulting example:

      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

      The resulting example:

      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.3 points} Task 6:

      To do: Create a ArraySum function that returns the sum of the elements of a dynamic array. Pay attention to checking the input array: if the memory for the array is not allocated, the parameter value is nil, you cannot work with this value.

      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 the sum of its elements.

      The resulting example:

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

      [Program name: 12task-06.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 DynArr.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.5 points} Task 8:

      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 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);

      The resulting example:

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

      [Program name: 12task-08.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).

      The resulting example:

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

      [Program name: 12task-09.pas]

      {1.0 point} Task 10:

      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.
      The resulting example:

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

      [Program name: 12task-10.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 the minimum and maximum among 3 numbers. Create a function to do the task. The function type is a tuple (min and max).

    Note: to print correct results you must unpack them.

    The resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    ✍ 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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 resulting example:

    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 reals). 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 resulting example:

    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-07-func.pas]

    Lesson #9. Nested loops

    Theory

    Lection in pdf format

    Labs and tasks

    Nested Loops

    Lab 1:

    To do: Calculate the value of the function z(x,y) = xy for every x changing in the interval [2;8], and y changing in the interval [2;5].

    The resulting example:

    z(x,y) = 2^2 = 4
    z(x,y) = 2^3 = 8
    z(x,y) = 2^4 = 16
    z(x,y) = 3^2 = 9
    z(x,y) = 3^3 = 27
    z(x,y) = 3^4 = 81
    z(x,y) = 4^2 = 16
    z(x,y) = 4^3 = 64
    z(x,y) = 4^4 = 256
    z(x,y) = 5^2 = 25
    z(x,y) = 5^3 = 125
    z(x,y) = 5^4 = 625
    ... etc.
    

    ✍ Algorithm:

    • We must create two for loops (nested loop): one loop within the other. Variable x has to be modified in the outer loop; variable y has to be modified within the inner loop.
    {0.4 points} Task 1, nested loops:

    To do: Calculate a function z(x,y) = x+2y for every x varying in the interval [5;10] and y varying in the interval [1;5]. You should use nested for loops.

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

    The resulting example:

    z(x,y)= 5+2*1 = 7
    z(x,y)= 5+2*2 = 9
    z(x,y)= 5+2*3 = 11
    z(x,y)= 5+2*4 = 13
    z(x,y)= 5+2*5 = 15
    z(x,y)= 6+2*1 = 8
    z(x,y)= 6+2*2 = 10
    z(x,y)= 6+2*3 = 12
    z(x,y)= 6+2*4 = 14
    z(x,y)= 6+2*5 = 16
    z(x,y)= 7+2*1 = 9
    z(x,y)= 7+2*2 = 11
    z(x,y)= 7+2*3 = 13
    z(x,y)= 7+2*4 = 15
    z(x,y)= 7+2*5 = 17
    z(x,y)= 8+2*1 = 10
    z(x,y)= 8+2*2 = 12
    z(x,y)= 8+2*3 = 14
    z(x,y)= 8+2*4 = 16
    z(x,y)= 8+2*5 = 18
    z(x,y)= 9+2*1 = 11
    z(x,y)= 9+2*2 = 13
    z(x,y)= 9+2*3 = 15
    z(x,y)= 9+2*4 = 17
    z(x,y)= 9+2*5 = 19
    z(x,y)= 10+2*1 = 12
    z(x,y)= 10+2*2 = 14
    z(x,y)= 10+2*3 = 16
    z(x,y)= 10+2*4 = 18
    z(x,y)= 10+2*5 = 20
    
    {0.4 points} Task 2, nested loops:

    To do: Calculate a function z(x,y) = x-y for every x varying in the interval [30;33] and y varying in the interval [1;5]. For beautiful output use writelnFormat statement. You should use nested for loops.

    The resulting example:

    30-1=29
    30-2=28
    30-3=27
    30-4=26
    30-5=25
    31-1=30
    31-2=29
    31-3=28
    31-4=27
    31-5=26
    32-1=31
    32-2=30
    32-3=29
    32-4=28
    32-5=27
    33-1=32
    33-2=31
    33-3=30
    33-4=29
    33-5=28
    

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

    {0.4 points}Task 3_0, nested loops:
    To do: The program must display the rows with the following sequences as in the example below. Use nested loops: the outer for loop must iterate over the columns, the inner loop must iterate over the sequences within each row.

    The resulting example:

    9 9 9 9 9 
    8 8 8 8 8 
    7 7 7 7 7 
    6 6 6 6 6 
    5 5 5 5 5 
    

    [Program name: task-3_0-nested_loops.pas]

    {0.4 points} Task 3_1, nested loops:

    To do: The program must display the rows with the following sequences as in the example below. Use nested loops: the outer for loop must iterate over the columns, the inner loop must iterate over the sequences within each row.

    The resulting example:

    0 0 0 0 0 
    1 1 1 1 1 
    2 2 2 2 2 
    3 3 3 3 3 
    4 4 4 4 4 
    5 5 5 5 5 
    6 6 6 6 6 
    7 7 7 7 7 
    8 8 8 8 8 
    9 9 9 9 9 
    

    [Program name: task-3_1-nested_loops.pas]

    {0.4 points} Task 4, nested loops:

    To do: The program must display the rows with the following sequences as in the example below. Use nested loops and arbitrary step (=2).

    The resulting example:

    1 1 1 1 1 1
    3 3 3 3 3 3
    5 5 5 5 5 5
    7 7 7 7 7 7
    9 9 9 9 9 9
    

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

    {0.7 points} Task 5, nested loops:

    To do: Integers K > 0 and N ≥ 0 are given. K sequences of integers with N elements in each set are entered. The program has to output the number of odd elements in each sequence.

    Note: It is better to use random function to generate the numbers of sequences. But in this case don’t forget to print out the elements.

    var a:=random(10);

    The resulting example:

    please, enter the quantity of the sequences:  
    >>> 3
    enter the quantity of numbers within the sequences 
    >>> 5
    
    the sequence #1 
    4 9 3 3 7 result: 4 odd elements 
    the sequence #2 
    6 9 8 2 9 result: 2 odd elements 
    the sequence #3 
    5 1 7 3 6 result: 4 odd elements 
    

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

    {0.7 points} Task 6, nested loops:

    To do: Integers K > 0 and N ≥ 0 are given. K sequences of integers with N elements in each set are entered. The program has to output a minimum and maximum of the elements in each sequence.

    Note 1: It is better to use random function to generate the numbers of sequences. But in this case don’t forget to print out the elements.

    var a:=random(10);

    Note 2: It is better to use the following constants as the initial values of the minimum and maximum variables:

    min:=integer.MaxValue;
    max:=integer.MinValue;

    The resulting example:

    please, enter the quantity of the sequences:  
    >>>3
    enter the quantity of numbers within the sequences 
    >>>5
    
    the sequence #1 
    4 9 5 4 8 min =4, max=9
     
    the sequence #2 
    6 9 2 3 4 min =2, max=9 
    
    the sequence #3 
    9 1 4 8 7 min =1, max=9 
    

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

    Boolean type (logical)

    Lab 3, boolean type:

    To do: The values of n and k are entered. n numbers of the sequence are entered. The program should output if there is a number k among them?

    The resulting example:

    how many numbers?  
    >>>5
    what number must we find? 
    >>>3
    enter numbers, please 
    >>>1  >>>3  >>>6  >>>4  >>>7
    there is '3' number:  True
    

    ✍ Algorithm:

      begin
        var n := ReadInteger('how many numbers?');
        assert (n>0);
        var exists := false;
        var k := ReadInteger('what number must we find?');
        print('enter numbers, please');
        loop n do
        begin
          var x := ReadInteger;
          if x = k then
            exists := true;
        end;
        print ($'there is {k} number: ', exists)
      end.

    Break and continue

    Lab 4, break:

    To do: The values of n and k are entered. n numbers of the sequence are entered. The program should output if there is a number k among them?

    ✍ Algorithm:

      begin
        var n := ReadInteger('how many numbers?');
        assert (n>0);
        var exists := false;
        var k := ReadInteger('what number must we find?');
        print('enter numbers, please');
        loop n do
        begin
          var x := ReadInteger;
          if x = k then
            begin
              exists := true;
              break;
            end;
        end;
        print ($'there is {k} number: ', exists)
      end.
    Task 7, boolean type:

    To do: Integers K > 0 and N ≥ 0 are given. K sequences of integers with N elements in each set are entered. The program has to output if there is a number 2 among the numbers of sequences and output the total quantity of 2 number.

    The resulting example:

    please, enter the quantity of the sequences: 
    >>> 3
    enter the quantity of numbers within the sequences:
    >>> 2
    
    input the sequence #1:
    >>> 1 >>> 5 
    
    input the sequence #2:
    >>> 2 >>> 5 
    
    input the sequence #3:
    >>> 5 >>> 7 
    
    there is a number '2': true
    total quantity of '2': 1
    

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


    The Infinite Loop

    Examples:

    {# 1}
    while true do
      begin
      ...
      end;
    end.
    {# 2}
    repeat
      ...
    until false;
    {# 3}
    var x:=1;
    while x>0 do
      begin
       ...
      end;
    end.
    {# 4}
    var x:=1;
    repeat
      ...
    until x<=0;
    end.
    Lab 5, infinite loops:

    To do: A sequence of integers is given. The last number of the sequence is 0 (if 0 is entered the input of the numbers of the set is finished). The program must output the number of positive elements among the sequence.

    The resulting example:

    please, enter the sequence, print 0 if you want to stop: 
    >>>1 >>>-5 >>>9 >>>5 >>>0
    positive:  3
    +++++++++++++++++++++++++++++++++++++++++++++++++
    please, enter the sequence, print 0 if you want to stop: 
    >>>1 >>>-2 >>>-5 >>>-9 >>>11 >>>0
    positive:  2 
    

    ✍ Algorithm:

      Solution 1:

      begin
        print('please, enter the sequence, print 0 if you want to stop:');
        var count:=0;
        var x:=readinteger;
        while x<>0 do
        begin
          if x>0 then
            count+=1;
          x:=readinteger;
        end;
        print($'positive = {count}')
      end.

      Solution 2:

      begin
        print('please, enter the sequence, print 0 if you want to stop:');
        var count := 0;
        while true do
        begin
          var x := readinteger;
          if x = 0 then
            break
          else if x > 0 then
            count += 1;
        end;
        print($'positive = {count}')
      end.
    {0.4 points} Task 8, infinite loops:

    To do: A sequence of integers is given. The last number of the sequence is 0 (if 0 is entered the input of the numbers of the set is finished). The program must output the minimum and maximum of them. Use infinite loop.

    The resulting example:

    please, enter the sequence, print 0 if you want to stop: 
    >>>1 >>>-2 >>>-5 >>>-9 >>>11 >>>0
    min = -9  max = 11
    

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

    {0.7 points} Task 9, infinite loops:

    To do: Integer K is given (K > 0) and the set of K sequences. The last number of all the sequences is 0 (if 0 is entered the input of the numbers is finished). The program has to output the number of elements in each sequence, and also output the total number of the elements in all the sequences together.

    The resulting example:

    please, enter the quantity of the sequences 
    >>> 3
    input the sequence #1 
    >>>1  >>>5  >>>8  >>>0
    the seq has 3 elements 
    
    input the sequence #2 
    >>>7  >>>2  >>>0
    the seq has 2 elements 
    
    input the sequence #3 
    >>>6  >>>0
    the seq has 1 elements
     
    Total number of elements:  6 
    

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

    Working with digits of natural number

    Lab 6:

    To do: Natural number m is given. Calculate sum of its digits
    Solution: div / mod operations split the number on the series of its digits

    The resulting example:

    m:
    >>> 425
    result: 11

    ✍ Algorithm:

      begin
        var m := ReadInteger;
        Assert(m > 0);
        var s := 0;
        while m > 0 do
        begin
          s += m mod 10; // sum of digits
          m := m div 10; // discard the number to the right
        end;
      end.
    {0.7 points} Task 10, digits:

    To do: An integer is given (variable a). Find the number of its digits and their product.

    Note: since entered number can be a negative number, you can use the abs function, to have an absolute value of a number:

    abs(m)

    The resulting example:

    N:
    >>> 1205 
    Count = 4, product = 0
    --
    N:
    >>> -111 
    Count = 3, product = -1
    

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

    {0.7 points} Task 11, digits:

    To do: Natural number m is given. How many even digits in its decimal representation does it have?

    The resulting example:

    m:
    >>> 745
    even: 1
    

    [Program name: task-11-loops.pas]

    More about Sequences in while loop

    Lab 7, sequences:

    To do: A sequence of integers is given. The last number of all the sequences is 0 (if 0 is entered the input of the numbers is finished). The program has to print 0 in the case when the sequence forms a non-increasing sequence of numbers, otherwise the program has to print the number 1.

    The resulting example:

    please, enter the sequence, print 0 if you want to stop: 
    >>>1 >>>5 >>>9 >>>5 >>>0
    output: 0 (non-increasing sequence)
    +++++++++++++++++++++++++++++++++++++++++++++++++
    please, enter the sequence, print 0 if you want to stop: 
    >>>1 >>>2 >>>5 >>>9 >>>11 >>>0
    output: 1 (increasing sequence)
    

    ✍ Algorithm:

      Solution 1:

      Solution 2:
    {0.7 points} (complex) Task 12, loops:

    To do: Integer K is given (K > 0) and the set of K sequences. The last number of all the sequences is 0 (if 0 is entered the input of the numbers is finished). The program has to print true in the case when the sequence contains the element which is less than its neighbor on the left, otherwise the program has to print the number false.

    The resulting example:

    'please, enter the quantity of the sequences:' 3
    
    'input the sequence #1:'
    1 5 3 0
    >>> output: true 
    
    'input the sequence #2:'
    2 6 0
    >>> output: false
    
    'input the sequence #3:'
    5 7 4 0
    >>> output: true 
    

    [Program name: task-12-loops.pas]

    {1.0 points} (complex) Task 13, loops:

    To do: A sequence is called sawtoothed if each of its elements is either greater than each of its neighbors, or less than them. A sequence of integers containing at least two elements is given. The last number of the sequence is 0. Check if the given sequence is sawtoothed. Output true or false.

    Note 1: A sequence of two elements is considered a sawtoothed if these elements are different.

    Note 2: To specify if the sequence is either sawtoothed or not, you must use a variable of boolean type:

    var flag := true;

    Note 3: You do not need to check that the sequence contains at least two elements.

    The resulting example:

    enter the sequence:
    >>> 2  >>> 9  >>> 1  >>> 7  >>> 5  >>> 0
    sawtoothed: True 
    ---
    enter the sequence:
    >>> 1  >>> 2  >>> 3  >>> 2  >>> 5  >>> 0
    sawtoothed: False 
    

    [Program name: task-13-loops.pas]

    {0.4 points} Task 14:

    To do: An integer N is given and a set of N numbers (they are input). Find a serial number (position) of the first minimum among the numbers and serial number of the last maximum among the numbers.

    The resulting example:

    enter 10 numbers:
    >>>2  >>>15  >>>3  >>>8  >>>1  >>>2  >>>9  >>>1  >>>15  >>>11   
    serial numb of min is 5, serial numb of max is 9
    

    [Program name: task-14.pas]

    {0.3 points} Task 15, loops:

    To do: n is entered. Print the Fibonacci sequence of n elements.

    The resulting example:

    enter n:
    >>> 8
    result: 1 1 2 3 5 8 13 21 
    

    [Program name: task-15-fib.pas]

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

    Theory

    Lection # 8 in pdf format

    Sum (addition)

    Syntax:
    The sum in Pascal is calculated by the recurrent expression:

    S = S + Y
    where S is the accumulated amount
    Y – next summand
    

    Labs and tasks

    Sum (addition)

    Lab 1:

    To do: 10 numbers are given. It’s required to calculate their sum.

    ✍ Algorithm:


      The sum variable is initialized by 0 before loop. Every loop iteration the variable sum is incremented by a value of the next entered number.
    {0.3 points} Task 1, sum:

    To do: 5 integers are entered. After entering each number, the program should print their sum.

    The resulting example:

    'please, enter 5 numbers:'
    >>> 4
    entered number: 4  => sum = 4
    >>> 11
    entered number: 7 => sum = 11  
    >>> 14
    entered number: 3 => sum = 14  
    ... etc.
    

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

    {0.3 points} Task 2, sum:

    To do: 5 real numbers are entered. The program should output their sum only once, just before the end of the program.

    The resulting example:

    entered numbers: 
    >>> 4.2  >>> 7.1  >>> 3.1  >>> 2.5  >>> 8.6
    sum = 25.5  
    

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

    {0.3 points} Task 3, sum:

    To do: Count the sum of 10 numbers: 1 + 2 + 3 + … + 10. Better use for loop.

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

    {0.3 points} Task 4, sum:

    To do: Count the sum of 5 numbers: 1 + 3 + 5 + 7 + 9. Better use for loop with an arbitrary step.

    The resulting example:

    '1 + 3 + 5 + 7 + 9 ='
    25
    

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

    {0.4 points} Task 5, sum:

    To do: Calculate a sum of all odd integers up to 99 (1 + 3 + 5 + 7 + 9 + 11 + … + 99). Use for loop with an arbitrary step.

    The resulting example:

    '1 + 3 + 5 + 7 + 9 + ... + 99 ='
    2500
    

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

    {0.4 points} Task 6, sum:

    To do: Calculate a sum of all odd integers up to 99 (1 + 3 + 5 + 7 + 9 + 11 + … + 97 + 99). Use loop.

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

    Lab 2: Sum – short solution

    To do: 10 integers are given. It’s required to calculate their sum.

    ✍ Algorithm:

    {0.3 points} Task 7, sum:

    To do: 5 integers are entered. The program should output their sum only once, before the end of the program. Use short form as in the lab.

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


    Product (multiplication)

    Lab 3:

    To do: 10 reals are given. It’s required to calculate their product (multiplication).

    ✍ Algorithm:

    • The product variable is initialized by 1 value before loop. Every loop iteration the product is incremented by the value of the next number.
    {0.3 points} Task 1, product:

    To do: 5 integers are entered. After entering each number, the program should print their product.

    The resulting example:

    'please, enter 5 numbers:' 
    >>> 4
    entered number: 4  => product = 4
    >>> 3
    entered number: 3 => product = 12 
    >>> 5
    entered number: 5 => product = 60 
    
    ... etc.
    

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

    {0.3 points} Task 2, product:

    To do: 5 real numbers are entered. The program should output their product only once, just before the end of the program:

    The resulting example:

    entered numbers: 
    >>> 4.2  >>> 7.1  >>> 3.1  >>> 2.5  >>> 8.6
    product = 1987.503 
    

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

    {0.4 points} Task 3, product:

    To do: Calculate a product of 2-digit even integers in the interval [10;30] (10 * 12 * 14 * … * 28 * 30). Use for loop with an arbitrary step.

    The resulting example:

    product = 165412864

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

    Lab 4: Product (multiplication) — short solution

    To do: 10 real numbers are given. It’s required to calculate their product.

    ✍ Algorithm:

    {0.1 points} Task 4, product:

    To do: 5 real numbers are entered. The program should output their product only once, just before the end of the program:

    The resulting example:

    entered numbers: 
    >>> 4.2  >>> 7.1  >>> 3.1  >>> 2.5  >>> 8.6
    product = 1987.503 
    

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

    {0.3 points} Task 5, product:

    To do: 5 integers are entered. The program should output their product only once — just before the end of the program. Use short form as in the example.

    The resulting example:

    enter 5 integers, please:
    >>>2  >>>5  >>>1  >>>7  >>>3
    product is: 210

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

    Counters

    Lab:

    To do: n >= 0 is given. The program should ask to input n integer numbers and find a quantity of odd numbers among entered numbers.

    Solution: We’re going to use an if statement in a loop.

    The resulting example:

    how many numbers? 
    >>>4
    enter the numbers: 
    >>>1  >>>3  >>>8  >>>7
    the number of odd:  3 

    ✍ Algorithm:

      begin
        print('how many numbers?');
        var n := ReadInteger;
        print('enter the numbers:');
        var count := 0;
        loop n do
        begin
          var x := ReadInteger;
          if x mod 2 <> 0 then
            count += 1;
        end;
        print('the number of odd: ', count)
      end.
    {0.2 points} Task 1, counters:

    To do: Print the sequence: 1 2 3 4 . . . 99 100. Use loop and a variable counter:
    A piece of code:

    ...
    var counter:=0;
    loop 100 do
       begin
             ...
             print(counter);
       end;

    The resulting example:

    1 2 3 4 5 . . . 99 100
    

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

    {0.3 points} Task 2, counters:

    To do: Print the sequence: 1 2 3 4 . . . 99 100 99 . . . 3 2 1.

    Note: Create two loops: the first loop 1 2 3 4 . . . 99 100, the second loop 99 . . . 3 2 1.

    The resulting example:

    1 2 3 4 . . . 97 98 99 100 99 98 . . . 4 3 2 1
    

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

    {0.2 points} Task 3, counters:

    To do: 10 integers are given. You should use for loop and variable named counter to find the quantity of positive among the numbers.

    Note: to generate the sequence of numbers you should use random function:

    var genNumb: integer;
      genNumb:=random (a,b);

    Note: you can complete the following code:

    begin
      var genNumb, i: integer;
      var counter := 0;
      for i := 1 to 10 do
      begin
        genNumb := random(-5, 10);
        // to do ...
        // ...
      end;
      writeln;
      print('numbers of positive: ', counter)
    end.

    The resulting example:

    1 6 10 10 -2 1 -4 4 -4 2 
    numbers of positive:  7 
    

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


    Several counters

    Lab:

    To do: n grades (marks) on an exam (from 2 to 5) are given. Calculate the number of each grade (how many “2”, how many “3” …).

    Solution: We will use several counters, each counter for each grade.

    Expected results

    how many grades? 5
    enter grades, please
    4
    4
    4
    2
    3
    "2"= 1, "3"= 1, "4"= 3, "5"= 0 
    

    ✍ Algorithm:

      begin
        var n := ReadInteger('how many grades?');
        var (c2, c3, c4, c5) := (0, 0, 0, 0);
        writeln('enter grades, please');
        loop n do
        begin
          var Mark := ReadInteger;
          case Mark of
            2: c2 += 1;
            3: c3 += 1;
            4: c4 += 1;
            5: c5 += 1;
          end;
        end;
        Print($'"2"= {c2}, "3"= {c3}, "4"= {c4}, "5"= {c5}');
      end.
    {0.4 points} Task 4, counters:

    To do: 10 integers are given. Use loop and two counters to find the quantity of positive and negative among the numbers.

    Note: to generate the sequence of numbers you should use random function:

    var genNumb: integer;
      genNumb:=random(a,b);

    The resulting example:

    1  -5  -12   2   3   9   -1  9   5   -8   
    counter positive = 6, counter negative = 4
    

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

    {0.4 points} Task 5, counters:

    To do: 10 integers are given. Use loop and two counters to find the quantity of even and odd among the numbers.

    The resulting example:

    1  -5  -12   2   3   9   -1  9   5   -8  
    counter even = 3, counter odd = 7
    

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


    Minimum and maximum value

    Lab:

    To do: n numbers are given (n >= 0). Find minimum value of these numbers.

    ✍ Algorithm:

      Solution 1. Let’s assign the first entered number to min variable. Then, in a loop check if the next entered number is less than min. If it is, so reassign this value to min:

      begin
        var n:=readinteger('enter n');
        var x := ReadReal;
        var min := x;
        loop n - 1 do
        begin
          x := ReadReal;
          if x < min then
            min := x;
        end;
        print($'min = {min}')
      end.

      What is not good: The first value is handled separately.

    Solution 2. Let’s set the maximum value of real type (real.MaxValue) to min variable. Then, in a loop check if the first entered number is less than min. If it is, so reassign this value to min.

    The idea is that after the first iteration min will be reassigned in any case because x < real.MaxValue:

    begin
        var n:=readinteger('enter n');
        var x:real;
        var min := real.MaxValue;
        loop n do
        begin
          x := ReadReal;
          if x < min then
            min := x;
        end;
        print($'min = {min}')
    end.
    {0.2 points} Task 1, min & max:

    To do: 5 numbers are entered. Output the maximum and minimum of the entered numbers.

    Note: complete the folowing code:

    begin
      var // ...;
      var min := integer.MaxValue;
      var max := integer.MinValue;
      loop 5 do
      begin
        // ...
      end;
      print($'min = {min}, max = {max}')
    end.

    The resulting example:

    enter 5 integers:
    >>> 5  >>> 3  >>> 8  >>> 1  >>> 2  
    maximum is 8, minimum is 1
    

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

    {0.5 points} Task 2, min & max:

    To do: An integer N is given and a set of N rectangles defined by their sides (pairs of numbers a and b). Calculate the areas (S = a * b) of all the rectangles and minimum area of them.

    The resulting example:

    How many rectangles?
    >>> 3
    Please, enter the sides of the rectangles:
    >>> 2  >>> 3
    area is: 6
    >>> 1  >>> 5
    area is: 5
    >>> 4  >>> 2
    area is: 8
    The minimum area of all rectangles is 5
    

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

    {0.5 points} Task 3, min & max:

    To do: An integer N is given and a set of N rectangles defined by their sides (pairs of numbers a and b). Find the perimeters of all the rectangles and maximum perimeter of them.

    The resulting example:

    How many rectangles?
    >>> 3
    Please, enter the sides of the rectangles:
    >>> 2  >>> 3
    perimeter: 10
    >>> 1  >>> 5
    perimeter: 12
    >>> 4  >>> 2
    perimeter: 12
    The maximum perimeter of all rectangles is 12
    

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

    {0.3 points} Task 4, min & max:

    To do: Find the minimum of 5 numbers and print its position (order number). To store the position you must use extra variable.

    Note: to generate the sequence of numbers you should use random function:

    var genNumb: integer;
      genNumb:=random (a,b);

    The resulting example:

    5 generated numbers:
    5   3   8   1   2 
    minimum is 1, its position is 4
    

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

    {0.5 points} Task 5, min & max:

    To do: Calculate the minimum and maximum of 10 generated numbers and print the sum of their serial numbers.

    Note: to generate the sequence of numbers you should use random function:

    var genNumb: integer;
      genNumb:=random (a,b);

    The resulting example:

    10 generated numbers:
    2  15  3  8  1  2  9  1  7  11   
    max is 15 position is 2, min is 1 position is 8, 2 + 8 = 10 
    

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

    Sums and products in the while and repeat loops

    Lab:

    To do: Calculate the sum of the sequence: 11 + 13 + 15 + ... + 99.

    Expected results:

    sum = 2475
    

    ✍ Algorythm:

      While loop:

      begin
        var x:=11;
        var s:=0;
        while x<=99 do
        begin
          s+=x;
          write(x);
          x+=2;
        end;
        Print($'sum = {s}');
      end.

      Loop:

    {0.3 points} Task 1, sum and while:

    To do: Calculate a sum of all odd 2-digit integers (11+ 13 + 15 + 17 + 19 + 21 + ... + 99). Make the task two times - using while and repeat loops.

    The resulting example:

    while loop. sum = 2475 
    repeat loop. sum = 2475 
    

    [Program name: task-01-sum-while.pas]

    {0.3 points} Task 2, sum and while:

    To do: Calculate a product of 2-digit even integers in the range [10;30] (10 * 12 * 14 * ... * 28 * 30). Make the task two times - using while and repeat loops.

    The resulting example:

    while loop. product = 667418624  
    repeat loop. product = 667418624 
    

    [Program name: task-02-sum-while.pas]

    {0.3 points} Task 3, sum and while:

    To do: 5 real numbers are entered. The program should output their sum only once, just before the end of the program. Make the task two times - using while and repeat loops.

    The resulting example:

    please enter 5 numbers: 
    >>> 4.2  >>> 7.1  >>> 3.1  >>> 2.5  >>> 8.6
    sum = 25.5
    

    [Program name: task-03-sum-while.pas]

    {0.3 points} Task 4, sum and while:

    To do: 5 numbers are entered. The program should output their product (multiplication) only once, just before the end of the program. Make the task two times - using while and repeat loops.

    The resulting example:

    please enter 5 numbers: 
    >>> 4  >>> 7  >>> 3  >>> 2  >>> 8
    multiplication = 1344
    

    [Program name: task-04-sum-while.pas]

    Lesson #7. Loops. Arbitrary step

    Theory

    Lection # 7 in pdf format

    Labs and tasks

    How to use arbitrary step in for loop & loop

    Lab 1:

    To do: Output all 2-digit odd numbers from 11 to 21.

    The resulting example:

    11  13  15  17  19  21

    ✍ Algorithm:

    • Solution 1. With loop
    • Solution 2. With for loop
    {0.4 points} Task 1:
    To do: Output the sequence 3 5 7 9 … 21 (from 3 to 21 with a step = 2). Make it twice: with loop and for loop.

    The fragment of the program:

    begin
    println('the result with a loop');
    var ...;
    loop ...;
      ...
    println('the result with a FOR loop');
    for var ...
      ...
    end.

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

    {0.4 points} Task 2:
    To do: Output the sequence of integers: 20 18 16 … 2 (from 20 downto 2 with a step = 2). Make it twice: with loop and for loop.

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

    {0.4 points} Task 3:
    To do: Output the sequence of integers: 15 12 9 6 3 0 (from 15 downto 0 with a step = 3). Make it twice: with loop and for loop.

    The resulting example:

    15 12 9 6 3 0
    

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

    {0.4 points} Task 4:
    To do: Output the sequence of integers: 5 10 15 20 … 100 (from 5 to 100). Make it twice: with loop and for loop.

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

    Functions z(x)

    Lab 2:

    To do: Calculate a value of the function z(x) = x3 for all x varying on the interval [1, 7] with a step = 2. Make it twice: with loop and for loop.

    The resulting example:

    1*1*1 = 1   3*3*3 = 27   5*5*5 = 125   7*7*7 = 343
    

    ✍ Algorithm:

    • Solution with for loop:
    {0.5 points} Task 5:
    To do: Calculate a value of the function z(x) = x2 for all x varying on the interval [3, 12] with a step = 3. Make it twice: with loop and for loop.

    The resulting example:

    3*3 = 9   6*6 = 36   9*9 = 81   12*12 = 144
    

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

    {0.5 points} Task 6:
    To do: Calculate a value of the function z(x) = √x for all x varying on the interval [5, 25] with a step = 5. Make it twice: with loop and for loop.

    Note: To calculate the square root of a number in pascal there is a standard function sqrt(x), for example:

    var result:=sqrt(2); // the result = 1.4142135623731

    The resulting example:

    sqrt(5) = 2.23606797749979   sqrt(10) = 3.16227766016838    
    sqrt(15) = 3.87298334620742   sqrt(20) = 4.47213595499958  sqrt(25) = 5
    

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

    {0.5 points} Task 7:
    To do: Calculate a value of the function z(x) = 2x-2 for all x varying on the interval [5, 20] with a step = 3. Make it twice: with loop and for loop.

    The resulting example:

    2*5-2 = 8   2*8-2 = 14   2*11-2 = 20   2*14-2 = 26   2*17-2 = 32  2*20-2 = 38
    

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

    {0.5 points} Task 8:
    To do: Calculate a value of the function z(x) = sin(x) for all x varying on the interval [1, 5].

    Note 1: To calculate the sin() in pascal there is a standard function sin(x), for example:

    var result:=sin(2); // the result = 0.909297426825682

    Note 2: To output the floating point number with a particular number of digits:

    writelnFormat('{0:f2}',3.1415); // output: 3.14

    The resulting example:

    'the rezult of z(x) : '      0.84   0.91   0.14  -0.76  -0.96
    

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

    How to use real step in for & loop

    Lab :
    To do: Output the sequence: 1.0    1.1   1.2    1.3   1.4    1.5   1.6    1.7  1.8    1.9   2.0.

    ✍ Algorithm:

    • Solution 1. With loop
    • Solution 2. With for loop
    {0.4 points} Task 9:
    To do: Output the sequence 0.1   0.3  0.5   0.7  0.9   1.1. Make it twice: with loop and for loop.

    The resulting example:

    0.1   0.3   0.5   0.7   0.9   1.1
    

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

    {0.4 points} Task 10:
    To do: Output the sequence: 0.0  0.5   1.0  1.5   2.0  2.5. Make it twice: with loop and for loop.

    The resulting example:

    0.0   0.5   1.0   1.5   2.0   2.5
    

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

    {0.4 points} Task 11:
    To do: A real number is given— the price of 1 kg of candy. The program has to output the prices of 1, 2, …, 10 kg of candy. Use for loop.

    Note. Use friendly variable names (it’s better to use writelnFormat statement).

    The resulting example:

    'enter a price of 1 kg of candy, please: '  
    >>> 150.5
    the cost of 1 kg = 150.5
    the cost of 2 kg = 301
    the cost of 3 kg = 451.5
    ...
    the cost of 10 kg = 1505
    

    [Program name: L7-task-11.pas]

    {0.4 points} Task 12:
    To do: A real number is given— the price of 1 kg of candy. The program has to output the prices of 1.2, 1.4, 1.6 1.8, 2 kg of candy.

    Note. Use friendly variable names (it’s better to use writelnFormat statement).

    The resulting example:

    'enter a price of 1 kg of candy, please: '  
    >>> 100.2
    the cost of 1.2 kg =  120.24
    the cost of 1.4 kg =  140.28
    ...
    the cost of 2 kg =    200.4
    

    [Program name: L7-task-12.pas]

    {0.4 points} Task 13:
    To do: Two integers A and B are given. Print the squares of all integers between A and B in ascending order and including these numbers themselves.

    The resulting example:

    'enter two integers, please:  A = , B = '  
    >>> 1   >>> -2   
    4, 1, 0, 1  
    ---
    'enter two integers, please:  A = , B = '  
    >>> 2   >>> 3   
    4, 9
    ---
    'enter two integers, please:   A = , B = '  
    >>> 2   >>> 2   
    4
    

    [Program name: L7-task-13.pas]

    {0.4 points} Task 14:
    To do: Two integers A and B are given. Print the square roots of all integers between A and B in ascending order and including these numbers themselves.

    The resulting example:

    'enter two integers, please: A = , B = '  
    >>> 1   >>> 5   
    sqrt(1) = 1    sqrt(2) = 1.4142135623731    
    sqrt(3) = 1.73205080756888    sqrt(4) = 2     sqrt(5) = 2.23606797749979 
    

    [Program name: L7-task-14.pas]


    Extra tasks

    Lab:

    To do: Using one loop, calculate the value of the sum given by the following formula (N> 0):

    The resulting example:

    Please input real number X 
    >>> 3
    Please input integer N > 0 
    >>> 5
    sum of the sequence = 10.2857142857143
    

    ✍ Algorithm:

      begin
        var X := ReadReal('Please input real number X ');
        var N := ReadInteger('Please input integer N > 0');
        Assert(N > 0, 'N<=0');
        var sum:=0.0;
        sum := 0.0;
        var num1:=-x;
        var num2:=x;
        var counter:=1;
        for var i:=1 to n do
        begin
          counter*=i;
          sum+=(num1+num2)/(i+counter);
          num1*=-x;
          num2*=x;
        end;
          writeln($'sum of the sequence = {sum}');
      end.
    {0.5 points} Extra task 1:
    To do: Using one loop, calculate the value of the sum given by the following formula (N> 0):

    The resulting example:

    Please input real number X 
    >>> 5
    Please input integer N > 0 
    >>> 2
    sum of the sequence = 2.78693528693529
    

    [Program name: L7-extask-1.pas]

    {0.5 points} Extra task 2:
    To do: Using one loop, calculate the value of the sum given by the following formula (N> 0):

    The resulting example:

    Please input real number X 
    >>> 5
    Please input integer N > 0 
    >>> 5
    sum of the sequence = -491.5
    

    [Program name: L7-extask-2.pas]

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