Lesson #9. Nested loops

Labs and tasks

Nested Loops

Lab 5:

To do: For every x changing in the interval [2;8], calculate the value of the function z(x,y) = xy. The variable y changes 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 in 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].

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

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

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, nested loops:

To do: The program must display the next sequences as in the example below. Use nested loops.

The resulting example:

0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
....
9 9 9 9 9

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

{0.4 points} Task 4, nested loops:

To do: The program must display the next sequences as in the example below. Use nested loops.

The resulting example:

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

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


Далее:
http://edu.mmcs.sfedu.ru/mod/assign/view.php?id=11454

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

Theory

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

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

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

✍ Algorithm:

    begin
      var n := ReadInteger;
      var count := 0;
      loop n do
      begin
        var x := ReadInteger;
        if x mod 2 <> 0 then
          count += 1;
      end;
    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:


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


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

{0.3 points} Task 3, counters:

To do: 10 integers are given. Use loop and a variable counter to find the quantity of positive among the numbers.

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

var genNumb:=random (a,b);

The resulting example:

1  -5  -12   2   3   9   -1  9   5   -8   
counter = 4

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

✍ Algorithm:

    begin
      var n := ReadInteger;
      var (c2, c3, c4, c5) := (0, 0, 0, 0);
      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(c2, c3, c4, 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.

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.3 points} Task 1, min & max:

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

The resulting example:

enter 5 numbers:
>>> 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 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
>>> 1  >>> 5
>>> 4  >>> 2
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
>>> 1  >>> 5
>>> 4  >>> 2
The maximum perimeter of all rectangles is 12.

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

{0.3 points} Task 4, min & max:

To do: Calculate the minimum of 5 entered numbers and print its serial number (order).

The resulting example:

enter 5 numbers:
>>>5   >>>3   >>>8  >>>1  >>>2 
minimum is 1, its serial number is 4

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

{0.4 points} Task 5, min & max:

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

The resulting example:

enter 10 numbers:
>>>2  >>>15  >>>3  >>>8  >>>1  >>>2  >>>9  >>>1  >>>7  >>>11   
max is 15, min is 1, 15 + 1 = 16 

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

{0.5 points} Task 6, min & max:

To do: An integer N is given and a set of N numbers (they are input). Find a serial number 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-06-maxmin.pas]

Lesson #7. Loops. Arbitrary step

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.

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

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]

Lesson #6. Loops. Simple tasks

Theory

Lection # 6 in pdf format

  • Loops are used to repeat actions
  • The loop consists of: a loop header and a loop body
  • One loop iteration is one repetition of the loop body
  • The simpliest type of loops is loop.
    Syntax:

    loop n do
       some operator;
    

For loop

  • For loop is a loop with a counter
  • After each iteration counter increments by 1

While and Repeat loop

Syntax of While loop:

while condition do
   statements

Syntax of Repeat loop:

repeat
   statements
until condition

Labs and tasks

Loops

Lab 1:

To do: Print digit 1 ten times.

The resulting example:

1 1 1 1 1 1 1 1 1 1

✍ Algorithm:

    begin
      loop 10 do
        print(1);
    end.

Note: Since this moment you should implement protection against invalid input with Assert function.
{0.3 points} Task 1, loop:
To do: An integer A (A > 0) is given. Output the word «Hello» A times. You need to put commas between the words.

Note: You should check if the number is positive:

assert(a>0,'a bad input; the variable a must be > 0');

The resulting example:

'Please enter how many times: A ='  
>>> 3   
Hello, Hello, Hello

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


{0.3 points} Task 2, loop:
To do: Two integers K and N (N > 0) are given. Output N times the number K.

Note: You should check if input numbers are positive (assert()).

The resulting example:

'enter the number to output:  K= '   
>>> 4  
'enter how many times to output: N= ' 
>>> 3  
4 4 4

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


Lab 2:

To do: Print numbers from 1 to 10.

The resulting example:

1 2 3 4 5 6 7 8 9 10

✍ Algorithm:


{0.4 points} Task 3, loop:
To do: An integer A (A > 0) is given. Output integers between 0 and A (including the value of A) in ascending order and output the number (quantity) of these numbers.

The resulting example:

'Enter a number where to stop: A= '   
>>> 5   
0 1 2 3 4 5  quantity = 6
---
'Enter a number where to stop: A= '   
>>> 3
0 1 2 3 quantity = 4

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


Lab 3:

To do: Print numbers from 10 downto 1.

The resulting example:

10 9 8 7 6 5 4 3 2 1

✍ Algorithm:


{0.4 points} Task 4, loop:
To do: An integer A (A > 0) is given. Output integers between A and 0 (including the value of A) in discending order.

The resulting example:

'Enter a number to begin the output:' 
>>> 5  
result: 5 4 3 2 1 0 
---
'Enter a number to begin the output:' 
>>> 3  
result: 3 2 1 0

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


Lab 4:

To do: Print a power of 2 starting at 0; eight powers (1 2 4 8 … 128).

The resulting example:

1 2 4 8 16 32 64 128

✍ Algorithm:


{0.5 points} Task 5, loop:

To do: An integer A (A > 0) is given. Print 3^A (3 in a power of A). You should use multiplication (*). It is forbidden to use standard functions.

Note: You should use the writelnFormat function:

WritelnFormat('3 in the power of {0} = {1}', a, ?);

The resulting example:

'Enter a number - power of 3: A= '  
>>> 4   
3 in the power of 4 = 81
---
'Enter a number - power of 3: A= ' 
>>> 2  
3 in the power of 2 = 9

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


For loops

Lab 5:

To do: Print a sequence of numbers from 1 to 10.

The resulting example:

1 2 3 4 5 6 7 8 9 10

✍ Algorithm:


{0.3 points} Task 1, for loop:

To do: Two integers K and N (N > 0) are given. The number K must be printed N times.

Note: to check if N > 0 you should use assert function:

assert(n > 0, 'bad input, n must be > 0');

The resulting example:

'enter the number to output, please: K ='  
>>> 4
'enter how many times to output: N ='  
>>> 3   
4 4 4

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


{0.4 points} Task 2, for loop:

To do: Two integers A and B are given (A < B). Output integers between A and B (including the values of A and B themselves) in ascending order and output the number (quantity) of these numbers. You should use assert function too.

The resulting example:

'enter two numbers, please: A= , B ='  
>>> 0  >>> 5  
0 1 2 3 4 5  quantity = 6
----
'enter two numbers, please:  A= , B ='  
>>> 2  >>> 7   
2 3 4 5 6 7 quantity = 6

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


Lab:

To do: Output the numbers from 10 downto 1 (10 9 8 7 6 5 4 3 2 1).

✍ Algorithm:

      begin
       for var i:=10 downto 1 do
       begin
         print(i)
       end;
      end.

{0.4 points} Task 3, for loop:

To do: Two integers A and B are given (A < B). Output integers between values of A and B (including A and B themselves) in discending order.

The resulting example:

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

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


While and Repeat loops

Lab 6:

To do: Print a sequence of numbers: 0 1 2 3 4.

The resulting example:

0 1 2 3 4

✍ Algorithm:


{0.2 points} Task 1, while & repeat loop:

To do: Output the sequence 15 16 17 18 19 20 … 30 (from 15 to 30). Make it twice: with while loop and with repeat loop.

Note: you should use different variables for loops counters.

The resulting example:

results with while loop:
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
results with repeat loop:
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

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


{0.2 points} Task 2, while & repeat loop:

To do: Output the sequence of integers: 3 5 7 9 … 21 (from 3 to 21 with a step = 2). Make it twice: with while loop and with repeat loop.

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


{0.2 points} Task 3, while & repeat loop:

To do: Output the sequence of integers: 20 18 16 … 2 (from 20 downto 2 with a step = 2). Make it twice: with while loop and with repeat loop.

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


{0.2 points} Task 4, while & repeat loop:

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 while loop and with repeat loop.

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


{0.2 points} Task 5, while & repeat loop:

To do: Output the sequence of real numbers: 0.1   0.3  0.5   0.7  0.9   1.1. Make it twice: with while loop and with repeat loop.

[Program name: task-05-while-repeat.pas]


{0.2 points} Task 6, while & repeat loop:

To do: Output the sequence of real numbers: 0.0   0.5  1.0   1.5  2.0   2.5. Make it twice: with while loop and repeat loop.

[Program name: task-06-while-repeat.pas]


{0.3 points} Task 7, while & repeat loop:

To do: Two integers A and B are given (A < B). Output integers between A and B (including A and B themselves) in ascending order and output the number (quantity) of these numbers. Make it twice: with while loop and repeat loop.

The resulting example:

'enter two numbers, please: A= , B ='  
>>> -1  >>> 5
results with a while loop:  
-1 0 1 2 3 4 5  quantity = 6
results with a repat loop:  
-1 0 1 2 3 4 5  quantity = 6

[Program name: task-07-while-repeat.pas]


Extra tasks

{0.5 points} * Task 8, while loop:

To do: Positive integers N and K are given. Using only the operations of addition and subtraction, find the quotient of dividing N by K, as well as the remainder of this division.

Note 1. Use friendly variable names for quotient and remainder. For example: quotient is quotient, remainder is remainder. Possibly: quot / rem.

Note 2. Don’t forget to implement protection against invalid input with Assert.

The resulting example:

'N = '
>>> 12
'K = '
>>> 4 
quotient = 3, remainder = 0
---
'N = '
>>> 27 
'K = '
>>> 5 
quotient = 5, remainder = 2

[Program name: Extask-08-while.pas]


{0.5 points} * Task 9, while loop:

To do: Positive numbers A and B (A >= B) are given. The segment of length A contains the maximum possible number of segments of length B (without overlays). Without using the multiplication (*) and division(/, div) operations, find the length of the unoccupied part of segment A.

Note 1. To specify that input values are not valid, add Assert operators to the program. They must be placed after the data is entered, but before the calculations begin. Check how Assert works on incorrect input data:

Assert((A > 0) and (B > 0));
Assert(A >= B);

The resulting example:

A = 
>>> 10
B = 
>>> 4 
result: 2
---
A = 
>>> 12
B = 
>>> 4 
result: 0

[Program name: Extask-09-while.pas]

Lesson #5. Minimum and Maximum. If statemens (continuation)

Theory

Search for minimum and maximum

  • Which of the two variables is greater (maximum):
  • var (x,y) := ReadInteger2;
    var Max: integer;
    if x>y then
      Max := x
    else 
      Max := y;
  • Which of the two variables is greater (maximum) and which one is less (minimum):
  • var (x,y) := ReadInteger2;
    var Min,Max: integer;
    if x>y then
    begin // don't forget about compound statement! 
      Max := x;
      Min := y;
    end
    else
    begin
      Max := x;
      Min := y;
    end;
    It is very important here not to forget about compound statement begin..end.

Random function

  • Random function is often used in Pascal.
  • To generate numbers from 0 to n not including the value of n itself (integers in the interval [0,N)), you must write:
  • var genNumb:=random (n);
  • To generate numbers in the range [a,b], you must write:
  • var a:=readinteger();
    var b:=readinteger();
    var genNumb:=random (a,b);

    Nested If statements. Using Assert function

    Example:

    To do: A Point (x,y) on а coordinate plane is given ( ≠ 0, ≠ 0). Output a number of quarter:

    ✍ Решение:

      var (x,y) := ReadInteger2;
      var quater: integer;
      Assert((x<>0) and (y<>0)); // must return True
      if x>0 then
        if y>0 then
          quarter := 1
        else 
          quarter := 4;
      else
        if y>0 then
           quarter := 2
        else 
           quarter := 3;

    Tasks

    Maximum and Minimum

    {0.3 points} Task 1:
    To do: Three integers are given. Find the maximum (the greatest) number among the three entered numbers.

    The resulting example:

    please enter three integer numbers
    >>> 6   >>> 1   >>> 9
    The maximum number is 9 
    

    [Program name: L5task01.pas]

    {0.3 points} Task 2:
    To do: Two real numbers are given. Find a maximum (the greatest) and minimum (the least) number among them. Output max and min.

    The resulting example:

    please enter three integer numbers
    >>> 3    >>> 55   >>> 8
    Maximum number: 55  Minimum number: 3 
    

    [Program name: L5task02.pas]

    {0.5 points} Task 3:
    To do: A two-digit number is given. Find the minimum and the maximum among its digits and swap the digits in the number.

    The resulting example:

    please enter two-digit number
    >>> 74    
    max = 7, min = 4, swapped = 47
    

    [Program name: L5task03.pas]

    {1 point} Task 4:
    To do: The integers A, B and k are given. At first output the larger of A and B, then the lesser of them. Print True if the difference between the numbers does not exceed the value of k and print False otherwise. Check the correctness of your program with at least three input data sets, give the log of the program in the form of a comment.

    The resulting example:

    Please enter three integer numbers
    >>> 3   >>> 5    >>> 2
    5 3 True 
    ---
    Please enter three integer numbers
    >>> 44   >>> 20   >>> 9
    44 20 False 
    

    [Program name: L5task04.pas]

    {1 point} Task 5:
    To do: A three-digit integer is given. Find the maximum (the greatest) digit and minimum minNum (the least) digit among the three digits of the given number and swap them. Output the numbers.

    The resulting example:

    please enter three integer numbers
    >>> 16   >>> 55   >>> 4
    After swaping maximum and minimum we have: 16 4 55
    

    [Program name: L5task05.pas]

    If statements (continuation) and random function

    {0.4 points} Task 6:
    To do: For a given real x find the value of the following function f.

    The resulting example:

    please enter a real number
    >>> -4
    The result of function f is 4
    ---
    please enter a real number
    >>> 1.5
    The result of function f is 2.25
    

    [Program name: L5task06.pas]

    {0.3 points} Task 7:
    To do: An integer is given. Use random function to generate this number. Display its description in the following form: “negative even number” or “negative odd number” or “zero number” or “positive odd number” or “positive even number”. Check the correctness of your program, provide a log of the program in the form of a comment.

    The resulting example:

    generated number:
    -4
    negative even number
    ---
    generated number:
    -3
    negative odd number 
    

    [Program name: L5task07.pas]

    {0.4 points} Task 8:
    To do: The numbers X and Y are given. Print True if the point with coordinates (X, Y) lies in the fourth coordinate quarter and print False otherwise. Do not use conditional if statement.

    The resulting example:

    Please enter the values of x and y
    >>> 8   >>> -4
    True
    ---
    Please enter the values of x and y
    >>> -9  >>> 3
    False 
    

    [Program name: L5task08.pas]

    {0.4 points} Task 9:
    To do: The coordinates X and Y of the chessboard field are given (integers lying in the range of 1–8). Use random function to generate these numbers. Considering that the bottom left cell of the board (1, 1) is black, output True if the field of X and Y is white and print False otherwise.

    The resulting example:

    Please enter the values of x and y between 1 and 8 inclusive
    2 7
    False 
    ---
    Please enter the values of x and y between 1 and 8 inclusive
    3 5
    True 
    

    [Program name: L5task09.pas]

    {0.3 points} Task 10:
    To do: Three integer numbers are given. Use random function to generate these numbers. Print true if none of these numbers are positive and False otherwise. Check the correctness of your program with at least three input data sets.

    The resulting example:

    generated numbers:
    -9 -6 -49
    True
    ---
    generated numbers:
    0 77 -5
    False
    

    [Program name: L5task10.pas]

    {0.3 points} Task 11:
    To do: Integers x, y are given. Calculate the value of the function:.

    A snippet of code:

    begin
      var x, y: integer; // arguments of f function
      Write('Input integers x, y: ');
      Readln(x, y);
     
      var f: integer;    // TODO: set the value of the function f(x, y) to f variable 
     
      WritelnFormat('f({0}, {1}) = {2}', x, y, f);
    end.

    The resulting example:

    Input integers x, y: 
    >>> 7    >>> -5
    f (7, -5) =  70 
    

    [Program name: L5task11.pas]

    Lesson # 5. Using vector

    Theory

    Vectors

    • A template type is a special type that can take on different types when the type is initialized.
    • std::vector standard library class that provides the functionality of a dynamically growing array with a “templated” type.
    • std::vector uses a template type:

    • Example:

      #include <vector>   // Definition
      using namespace std;
      int main()
      {
      vector<int> mm(5);  // Initialization
      vector<int> a {1, 2, 3, 7};  // Initialization
      // Loop for to iterate and print values of vector
      for (int i=0; i < a.size(); i++)  // size() - Number of elements
         cout << a[i] << " ";
      // Another kind of for loop (foreach) to iterate and print values of vector
      for (auto x : a)
         cout << x << " ";
      for (int& x : a)
         x++;
      }
      To use vector #include directive need to be placed.
    • When initializing a “templated” type, the template type goes inside of < > at the end of the type name:
    • std::vector v1;
      std::vector v2;
      
    • pop_back function removes the last element
    • push_back function adds an element to the end:
    • Example 1:

      #include <iostream>
      #include <vector>
       
      int main()
      {
          // Create a vector containing integers
          std::vector<int> v = {7, 5, 16, 8};
       
          // Add two more integers to vector
          v.push_back(25);
          v.push_back(13);
       
          // print out the particular elements
          cout << v[0] << std::endl;
          cout << v[1] << std::endl;
          cout << v[2] << std::endl;
       
          // Iterate and print values of vector
          for(int n : v) {
              std::cout << n << '\n';
          }
      }

      Example 2:

      #include <vector>
      #include <iostream>
       
      int main() {
      vector<int> v;
      for (int i = 0; i < 100; i++) {
         v.push_back( i * i );
      }
       
      cout << v[12] << std::endl;
       
      return 0;
      }

    Function template

    • A template variable is defined by declaring it before the beginning of a class or function:
    • template <typename T>
      int max(T a, T b) {
        if (a > b) { return a; }
           return b;
      }
      
    • Templated variables are checked at compile time, which allows for errors to be caught before running the program.
    • #include <iostream>
      using namespace std;
       
      template <typename T>
      T max(T a, T b) {
      	if (a > b) { return a; }
      	return b;
      }
      int main()
      {
      	cout << "max(3, 5): " << max(3, 5) << endl; // 5
      	cout << "max('a', 'd'): " << max('a', 'd') << endl; // d
      	cout << "max(\"Hello\", \"World\"): " << max("Hello", "World") << endl; // Hello
      	cout << "max(3, 5, 6): " << max(3, 5, 6) << endl; // error
       
      	system("pause");
      	return 0;
      }
    • A function template defines a family of functions.
    • A function template by itself is not a type, or a function, or any other entity. No code is generated from a source file that contains only template definitions. In order for any code to appear, a template must be instantiated: the template arguments must be determined so that the compiler can generate an actual function.
    • An explicit instantiation definition forces instantiation of the function or member function they refer to. It may appear in the program anywhere after the template definition, and for a given argument-list, is only allowed to appear once in the program, no diagnostic required.
    • template<typename T>
      void f(T s)
      {
          std::cout << s << '\n';
      }
       
      template void f<double>(double); // instantiates f<double>(double)
      template void f<>(char); // instantiates f<char>(char), template argument deduced
      template void f(int); // instantiates f<int>(int), template argument deduced
    • Implicit instantiation: When code refers to a function in context that requires the function definition to exist, and this particular function has not been explicitly instantiated, implicit instantiation occurs. The list of template arguments does not have to be supplied if it can be deduced from context.
    • #include <iostream>
       
      template<typename T>
      void f(T s)
      {
          std::cout << s << '\n';
      }
       
      int main()
      {
          f<double>(1); // instantiates and calls f<double>(double)
          f<>('a'); // instantiates and calls f<char>(char)
          f(7); // instantiates and calls f<int>(int)
          void (*ptr)(std::string) = f; // instantiates f<string>(string)
      }

      Note: omitting <> entirely allows overload resolution to examine both template and non-template overloads.

    * resources: 1) https://en.cppreference.com/w/cpp/container/vector

    Labs and tasks

    To do all the tasks and labs of this lesson you must create three files:

    1. a header file (basicVectors.h) (functions definitions for all the tasks must be placed here);
    2. a basicVectors.cpp file (the implementations of the functions with comments for all the tasks must be placed here)
    3. a main.cpp must provide prompts for user, calling created functions and output results for all the tasks.

    Each function should be accompanied by a comment about what it is intended for.

    Lab:
    The tasks of this lesson will be continuation of this lab.

    To do: An integer N (N > 0) and an integer vector (array) of length N are given. Fill the vector with the first N positive odd numbers: 1, 3, 5,… N. Do not use the conditional statement. Create a oddVectorGenerator() fuction to do the task.

    Note: To print the resulting vector, hereinafter, you must use the print_vector() function template. The function must be placed inside special header file printVect.h (you should add a new file to your application).

    Copy the print_vector function code and paste it to the printVect.h file:

    #ifndef PRINTVECT_H
    #define PRINTVECT_H
     
    #include <iostream>
    #include <vector>
     
    // note: function templates are always must be inside header files
     
    // function template to output vector
    template<typename T>
    void print_vector(const std::vector<T>& v, char delim = ' ') {
    	for (auto x : v)
    		std::cout << x << delim;
    	std::cout << std::endl;
    }
     
    /* #ifndef PRINT_VECT_H: */
    #endif

    Expected output:

    lab 1
    enter N - the number of vector elements
    >> 25
    1 3 5 7 9 11 13 15 17 19 21 23
    

    ✍ How to do:

    • Create a new console application with a name Lesson 5.
    • In the Source files folder of the Solution Explorer window, add new files: basicVectors.cpp and main.cpp. In the Header Files folder add a new header file: basicVectors.h.
    • Function templates are always placed in header files unlike regular functions. Add a new header file and name it printVect.h. Copy and paste the template function code into it.
    • Open your main.cpp file and include there all the header files that program will need:
    • #include <iostream>
      #include "basicVectors.h"
      #include "printVect.h"
      using namespace std;
    • Then, you must define an integer vector. You should do it inside the main.cpp file, right after all the included directives:
    • vector<int> v;
    • Output the comment to indicate that this is lab 1. Then, ask user to input a number of the vector elements. Set the entered value to the n variable:
    • cout << "lab 1"<< endl;
      cout << "enter N - the number of vector elements";
      int n;
      cin >> n;
    • Open your basicVectors.h header file. Include all necessary directives:
    • #pragma once
      #include <iostream>
      #include <vector>
      using namespace std;
    • We’re going to define our oddVectorGenerator() function, that must fill the vector with the first N positive odd numbers:
    • void oddVectorGenerator(vector<int>&, int);
      We’re going to pass vector parameter by reference (&), because we don’t need to locate a new memory space to store it.
    • Open basicVectors.cpp file to add an implementation of the created function. But first, add all the include directives to the file:
    • #include <vector>
      #include <cassert>
      #include "printVect.h"
      #include "basicVectors.h"
      using namespace std;
    • After that, let’s create the oddVectorGenerator() function and all the code it must implement:
    • void oddVectorGenerator(vector<int> &v, int n)
      {
      	for (int i = 1; i < n; i += 2)
      	{
      		v.push_back(i);
      	}
      }
      push_back function adds an element to the end of the vector.
      Only odd numbers will be set to vector due to the for loop step=2.
    • Open your main.cpp file and call the function. To output the results call the print_vector() function too:
    • oddVectorGenerator(v, n);
      print_vector(v);
      system("pause");
    • Run the program. And proceed with Task 1.
    Task 1:

    To do: A vector is given. Output its elements in reverse order. Create a function to do it.

    Note 1: You must complete this task in the same application as Lab 1. Output the task number before the results of this task are printed.

    Note 2: To use the same variable v in this task you should clear the elements, and then, set new elements to it:

    v.resize(0);
    v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    Note 3: You can create a new vector with the reversed elements.

    Expected output:

    task 1
    before task:
    1 2 3 4 5 6 7 8 9 10
    after task:
    10 9 8 7 6 5 4 3 2 1
    Task 2:

    To do: An integer vector is given. Calculate the number of odd numbers in this vector, as well as the number of positive numbers in it.

    Note 1: You must complete this task in the same application as Lab 1. Output the task number before the results of this task are printed.

    Note 2: To use the same variable v in this task you should clear the elements, and then, set new elements to it:

    v.resize(0);
    v = { -1, 2, 3, 4, -5, 6, 7, 8, -9, 10 };

    Note 3: To check if the negative number is odd you should use abs function.

    Expected output:

    task 2
    vector:
    -1 2 3 4 -5 6 7 8 -9 10
    number of positive: 7 number of odd : 5
    
    Task 3:

    To do: An integer vector is given. Output the index of its first even element.

    Note 1: You must complete this task in the same application as Lab 1. Output the task number before the results of this task are printed.

    Note 2: To use the same variable v in this task you should clear the elements, and then, set new elements to it:

    v.resize(0);
    v = { -1, 2, 3, 4, -5, 6, 7, 8, -9, 10 };

    Expected output:

    task 3
    vector:
    -1 5 3 4 -5 6 7 8 -9 10
    the first even element number is: 4
    
    Task 4:

    To do: An integer vector is given. Ouput the maximum of its local minima (a local minimum is an element that is less than any of its neighbors: e.g. ... 5 2 7 ... => number 2 is a local minium, because 2 < 5 and 2 < 7).

    Note 1: You must complete this task in the same application as Lab 1. Output the task number before the results of this task are printed.

    Note 2: To initialize a variable that should store the current value of the maximum local minimum, it is convenient to use the INT_MIN constant from the standard header:

    int max = std::numeric_limits<int>::min();

    Expected output:

    task 4
    vector:
    -1 5 3 4 -5 8 7 8 -9 10
    the maximum of local minima is: 7
    
    Task 5:

    To do: An integer vector A of size N (> 0) is given. Fill it with powers of two from the 1 power to the N: 2, 4, 8, 16,….

    Note 1: You must complete this task in the same application as Lab 1. Output the task number before the results of this task are printed.

    Expected output:

    task 5
    Enter N number:
    >>> 5
    vector:
    2  4  8  16  32
    
    Task 6:

    To do: an integer vector A of size N is given. It contains at least one even number. Find the first and last even number in the given vector. To do the task create getFirstAndLastEvenNumber() function.

    Note 1: Use passing parameters by reference (&) to return two values from a function.

    Note 2: Besides the getFirstAndLastEvenNumber() function you should create one more function of boolean type, to check if the number is even:

    inline bool isEven(int n)
    {
        //
    }

    Note 3: You must complete this task in the same application as Lab 1. Output the task number before the results of this task are printed.

    Expected output:

    task 6
    Enter N number:
    >>> 5
    vector:
    2  12  1  16  3
    the first: 2, the last: 16
    
    Task 7:

    To do: Three integer vectors A, B and C of the same size N are given. You must fill in vector C with values according to the following rule: each of its elements is equal to the maximum of the elements of vectors A and B with the same index.

    Note 1: You must complete this task in the same application as Lab 1. Output the task number before the results of this task are printed.

    Note 2: To compare two values you should use the standard max function, for example:

    int maximum = std::max(a, b);

    Note 3: You should check if the sizes of the vectors are equal, use assert() function, for example:

     assert((a.size() == b.size()) && (c.size() == a.size()));

    Note 4: You should create the following function signature:

    void maxInVectors(std::vector<int> &a, std::vector<int> &b, std::vector<int> &c)
    {
    // body function
    }

    Expected output:

    task 7
    A vector:
    0 1 2 3 4 42 6 7 8 422
    B vector:
    9 8 7 6 5 4 3 2 1 0
    vector C:
    9 8 7 6 5 42 6 7 8 422
    

    Extra tasks

    *ExTask 1:

    To do: An integer vectors Ais given. You must create B vector of the same size and fill in the vector with all numbers from vector A that have the digit 2 in decimal notation.

    Note 1: You must complete this task in the same application as Lab 1. Output the task number before the results of this task are printed.

    Note 2: In the implementation of the function, use a function that checks whether a given integer has a given digit in its decimal notation. You should implement it yourself:

    bool hasDigit (int n, int digit);

    Note 3: You should check if the sizes of the vectors are equal, use assert() function.

    Note 4: You should use push_back(value) method to add the new value to a vector. The method adds a new element to the end of the vector, for example:

    b.push_back(x);

    Expected output:

    task 6
    vector A:
    0 1 2 3 4 42 6 7 8 422
    vector B:
    2 42 422
    
    *ExTask 2:

    To do: An integer vector is given. Output the length of the largest series of consecutive zeros.

    Note 1: You must complete this task in the same application as Lab 1. Output the task number before the results of this task are printed.

    Expected output:

    task 7
    vector:
    0 1 0 0 0 42 6 7 8 422
    maximum length of 0: 3
    
    *ExTask 3:

    To do: Remove all odd elements from the vector by shifting the remaining elements to its beginning.

    Note 1: You should use the remove_if() standard method, which removes elements from the container that pass a specified test:

    auto newEnd = std::remove_if(a.begin(), a.end(), [](int n)
    	{
    		return // some test;
    	});

    Note 2: To delete the elements from the vector you can use the erase() standard method.

    Expected output:

    task 8
    before task:
    0 1 2 3 4 42 6 7 8 422
    after task:
    0 2 4 42 6 8 422
    
    *ExTask 4:

    To do: A vector of size N and an integer K (0 ≤ K < N) are given. Remove the element with K index from the vector by shifting all the following elements one position to the left and decreasing the vector size by one.

    Note 1: To check the index you can use the following construction:

    if(index < 0 || index > size)
            throw "Incorrect index!";

    Note 2: To delete the elements from the vector you can't use the erase() standard method.

    Expected output:

    task 9
    enter the index to delete
    >>> 2
    before task:
    1 2 3 4 5 6 7 8 
    after task:
    1 2 4 5 6 7 8
    

    Lesson #3 and #4. Conditions

    Theory

    Lection # 3 in pdf format

    IF Statements

    • If statements are concerned with Boolean logic. If the statement is true, the block of code associated with the if statement is executed. If the statement is false, control either jumps to the line after the if statement, or after the end keyword of an if statement block.
    • var numb:= 1;
      if numb = 1 then 
        begin
          // statements that will execute if the value of the numb variable is 1, 
          // will be placed here.
        end;
    • You can remove the begin and end keywords if your statement to execute is a single line statement. PascalAbc understands that if no begin and end are used, the line immediately after the if (condition) will be executed if the condition is true.
    • Else clauses
    • IF statements can also have associated else clauses. The else clause executes when the if statement is false:
    • var numb:= 1;
      if numb = 1 then
        begin
            // Block of code executes if the value of the numb variable is 1.
        end
      else
        begin
            // Block of code executes if the value of the numb variable is not 1.
        end
      Else if clauses (or Chained If statements)
    • If statements can also have associated else if clauses. The clauses are tested in the order that they appear in the code after the if statement. If any of the clauses returns true, the block of code associated with that statement is executed and control leaves the block of code associated with the entire if construct.
    • var numb:= 1;
      if numb = 1 then
        begin
            // Block of code executes if the value of the numb variable is 1.
        end
      else if numb = 0 then
        begin
          // Block of code executes if the value of the numb variable is 0.
        end
      else
        begin
          // Block of code executes if the value of the numb variable is neither above answers.
        end
    • The semicolon before else is not needed!
    • You can create as many else if blocks as necessary.
    • Sample:
      To do: A number of season (Winter is the first) is given. Output a name of the entered season number. It is better to use the chained If statements.

      ✍ Algorithm:

    Logical (boolean) operations

      We can define variables of boolean type:

      var A,B: boolean;
      A := True;
      B := False;
      Print(A and B);
      Print(A or B);
      Print(not A);
    • A and B is True if A is True and B is True at the same time. In other cases A and B is False
    • A or B is False if A is False and B is False. In other cases A or B is True
    • not A has opposite value: not A is True if A is False
    • Logical (boolean) operations in if statements:
    • Conditions may consist of logic operations: not, or, and. If there are more than one condition, so each condition must be surrounded by round brackets.
    • For example if we must check two conditions:

      if (year < 20) or (year > 18) then
      begin
        // if body
      end
      If one of the conditions or both conditions are True then if body executes.
    • Or another example:
    • var a: = 5;
      if (not (a<4)) and (7>5) then // ← True
      begin
        // if body
      end
    • The statements write and print can also return True or False:
    • //...
      a = 5;
      write (a >= 5); // returns True
      // ...
    The «most popular» errors:
    • You don’t need to write semicolon before else clause.
    • Don’t forget about begin..end in the cases when there is more than one lines of code after then or else.

    Case statement

    If there are too many else if statements, code can become difficult to understand. In this case, a better solution is to use a switch statement:

    var numb:= 1;
    case numb of  
    1,2 : writeln ('1 or 2'); //  Block of code executes if the value of numb is 1 ot 2.
     3: writeln('3'); //  Block of code executes if the value of numb is 2.
     4: writeln('4'); //  Block of code executes if the value of numb is 3.
     5: writeln('5'); //  Block of code executes if the value of numb is 5.
     else writeln('nothing matches'); //  Block of code executes if noone matches.
    end
    • A block labeled else will execute when none of the other blocks match.

    Using String type

    Case statement can check the variable of String type.

    Lab 1 Example:
    Given: the english words ‘dog’, ‘use’, ‘find’.
    To do: Output translations of the words into russian.

    ✍ Algorithm:

    Using ranges and enumerations

    Lab 2 Example:
    Given: Month ordinal.
    To do: Output corresponding name of a season.

    ✍ Algorithm:

    Labs and tasks

    True or false?

    {0.5 points} Task 1:
    To do: Two integers are given. Check if the following statement is True: the first number is greater than the second (the program must return True if it is true, and False otherwise).

    The resulting example:

    please enter two integers
    >>> 23
    >>> 1
    23 is greater than 1 is True 
    

    [Program name: L3task01.pas]

    {0.5 points} Task 2:
    To do: Two integers are entered. Check the truth of the statement: the first number is not equal to the second (the program must return True if it is true and False otherwise).

    The resulting example:

    please enter two integers
    >>>5 
    >>>5
    5 is not equal to 5 is False
    

    [Program name: L3task02.pas]

    {0.5 points} Task 3:
    To do: Three integers are given: the values of variables A, B, C. Check the truth of the double inequality A < B < C. Make sure that your program is correct with at least two input data sets, give the log of the program in the form of a comment.

    The resulting example:

    please enter three integers
    >>>3 >>>6 >>>2
    3 is less than 6 less than 2 is False
    ---
    please enter three integers
    >>>2 >>>5 >>>7
    2 is less than 5 less than 7 is True
    ---
    

    [Program name: L3task03.pas]

    {1 point} Task 4:
    To do: Three-digit integer is given. Check the truth: the first digit (left digit) of the number is less than the second (middle) and third (right).

    The resulting example:

    please enter a three digit number
    >>> 854
    8 is less than 5 and 4 is : False
    

    [Program name: L3task04.pas]

    {1 point} Task 5:
    To do: Two integers are entered. Check the truth of the statement: at least one of these numbers is odd.

    Note. Use the odd standard function:

    // The function odd returns True when its argument is odd integer:
    print (odd(5)); // true 
    print (odd(6)); // false .
    

    Check the following:

    -5,  8 => True
     12, 0 => False
     6, -1 => True
     11, 7 => True
    

    The resulting example:

    please enter two integer numbers
    >>> 9 >>> 2
    Either 9 or 2 is an odd number. This is : True
    

    [Program name: L3task05.pas]


    If statement

    {0.5 points} Task 6:
    To do: An integer is entered. If this is positive number, you should add 1 to it. Output the result.

    Check the following:

    -3 => -3
     0 =>  0
     1 =>  2
     5 =>  6
    

    The resulting example:

    please enter an integer number
    >>> -77
    The result is -77
    

    [Program name: L3task06.pas]

    {0.5 points} Task 7:
    To do: An integer is given. If this is even number then myltiply it by 10. Output the result.

    Check the following:

    2   => 20
    1   =>  1
    -10 => -100
    

    The resulting example:

    please enter an integer number
    >>> 8
    The result is 80
    

    [Program name: L3task07.pas]

    {0.7 points} Task 8:
    To do: An integer is given. If this is an even number, then multiply it by 3, if it is not even, then divide it by 3. Output.

    Check the following:

    4 => 12
    9 =>  3
    -10 => -30
    

    The resulting example:

    please enter an integer number
    >>> 12
    The result is 36
    

    [Program name: L3task08.pas]

    {0.7 points} Task 9:
    To do: An integer is given. If this is a positive number then add 1 to it; otherwise subtract it by 2. Output.

    Check the following:

    -3 => -5
     0 => -2
     1 =>  2
     5 =>  6
    

    The resulting example:

    please enter an integer number
    >>> 48
    The result is 49
    

    [Program name: L3task09.pas]

    Chained If statements and Logical operations in if statements

    {0.8 points} Task 10:
    To do: An integer is given (age of the person). If it is greater than or equal to 18, then output "you can watch this movie"; if the number is less than 10, then output "you should watch the cartoon". Otherwise, print "you can take a walk".

    The resulting example:

    how old are you?
    >>> 8
    you should watch the cartoon
    ---
    how old are you?
    >>> 15
    you can take a walk
    

    [Program name: L3task10.pas]

    {0.8 points} Task 11:
    To do: The student received a grade. If it is 2 points, then the program should output "it's very bad"; if it is a 3 - program should print "it's bad"; if it is 4 - "it's good", in case of 5 - "it's excellent", otherwise - "there are no such marks".

    The resulting example:

    what's your grade?
    >>> 2
    "it's very bad"
    ---
    what's your grade?
    >>> 4
    "it's good"
    

    [Program name: L3task11.pas]

    {0.8 points} Task 12:
    To do: The program must request the time of day in hours (from 1 to 24). Depending on the time entered, display a message indicating what time of day the entered hour belongs to (midnight (24), night (1-4), morning (5-11), day (12-16), evening (17-13)).

    The resulting example:

    what's time of the day?
    >>> 2
    "night"
    ---
    what's time of the day?
    >>> 24
    "midnight"
    

    [Program name: L3task12.pas]

    {0.8 points} Task 13:
    To do: Two integer values are given: for variables A and B. Assign a sum of these values to each variable if their values are not equal; otherwise (if they are equal) assign zero to the variables. Output the new values of variables A and B.

    The resulting example:

    please enter two integer numbers
     3 5
    The result is A = 8, B = 8
    ---
    please enter two integer numbers
    4 4
    The result is A = 0, B = 0 
    

    [Program name: L3task13.pas]

    {0.8 points} Task 14:
    To do: An integer N is entered, |N| ∈ [10;99].
    ‒ If it is even and divided by 4, then "add" 4 digit from the left (that is, to form a new number, which in the category of hundreds has 4, and the digits of tens and units are left as in the original number);
    ‒ If it is even, but is not divided by 4, then "add" 2 digit from the left of the number;
    ‒ If it is odd, then "add" 0 digit from the right of the number. Print the resulting number.

    The resulting example:

    N: 
    >>> 16 
    result =  416
    ---
    N: 
    >>> 86
    result = 286
    ---
    N:
    >>> 31
    result = 310 
    

    [Program name: L3task14.pas]

    {0.8 points} Task 15:
    To do: Integer number x is entered. Calculate the value of the function f:

    Note: The sign means boolean or.

    The resulting example:

    Enter an integer: 
    >>> 4
    Result is 8
    

    [Program name: L3task15.pas]

    {0.8 points} Task 16:
    To do: Real number x is entered. Calculate the value of the function f:

    The resulting example:

    
    

    [Program name: L3task16.pas]

    {0.8 points} Task 17:
    To do: A three-digit integer a is entered. Print True if there is a permutation of digits that makes number which is divided by 10, and False otherwise (e.g. 602 => True [620, 260]).

    Note. It is allowed to use no more than three operators div and mod (in total).
    The resulting example:

    Enter three-digit integer:
    >>> 602 
    True 
    ---
    Enter three-digit integer:
    >>> 311 
    False
    ---
    Enter three-digit integer:
    >>> -100
    True
    

    [Program name: L3task17.pas]


    Switch statement

    {0.6 points} Task 18:
    To do: Perform the task using the Case statement. The student received a grade. If it is 2 points, then the program should output "it's very bad"; if it is a 3 - program should print "it's bad"; if it is 4 - "it's good", in case of 5 - "it's excellent", otherwise - "there are no such marks".

    The resulting example:

    what's your grade?
    >>> 2
    "it's very bad"
    ---
    what's your grade?
    >>> 4
    "it's good"
    

    [Program name: L3task18.pas]

    {0.5 points} Task 19:
    To do: Perform the task using the Case statement. An integer in the range [1;7] is entered. Output a name of the day corresponding to this number (1 - “Monday”, 2 - “Tuesday”, etc.).

    The resulting example:

    please enter an integer from 1-7, for day of the week
    4
    Thursday
    ---
    please enter an integer from 1-7, for day of the week
    9
    such day does not exist
    

    [Program name: L3task19.pas]

    {0.6 points} Task 20:
    To do: Perform the task using the Case statement. Arithmetic operations are numbered as follows: 1 - addition, 2 - subtraction, 3 - multiplication, 4 - division. Ask user to enter number - arithmetic operation (integer in the range of [1;4]) and two reals A and B (B is not = 0). Output the result of the specified arithmetic operation with the given numbers.

    The resulting example:

    Enter arithmetic operation, please (from 1 to 4):
    >>> 1
    Enter two real numbers
    >>> 2.2
    >>> 5.0
    the result is: 2.2 + 5.0 = 7.2
    

    [Program name: L3task20.pas]

    {0.6 points} Task 21:
    To do: Perform the task using the Case statement. Program requests to enter a number of the mass units (1 means kilogram, 2 means ounce, 3 - gram, 4 - ton, 5 - pound). Then the program requests body weight in one of these units. Output body weight in kilograms (1 ounce = 0.0283 kilograms, 1 gram = 0.0010 kilograms, 1 ton = 1000 kilograms, 1 pound = 0.4536 kilograms).

    The resulting example:

    enter body weight 
    >>> 4
    enter mass 1..5 
    >>> 4
    in kilograms = 4000 
    

    [Program name: L3task21.pas]

    {0.8 points} Task 22:
    To do: Perform the task using the Case statement. The commands are numbered as follows:

    1 — check if the number is negative;
    2 — check if the number is odd;
    3 — check if the number is the divided by entered number D (the number D is entered by the user when this command is selected).

    You must ask the user to input an integer N - the sequence number of the C command, and then to output the result. For example, for the command "2" output True if the number is odd and False otherwise.

    Note: In response to entering an incorrect command, you should display the message "Command is unknown!".

    The resulting example:

    N :
    >>> -23 
    C : 
    >>> 1
    True
    ---
    N :
    >>> 103
    C :
    >>> 3
    D : 
    >>> 7 
    False
    

    [Program name: L3task22.pas]

    {0.4 points} Task 23:
    To do: Perform the task using Case statement: Arithmetic operations are numbered as follows: 1 - addition, 2 - subtraction, 3 - multiplication, 4 - division. Ask user to enter a number - arithmetic operation (integer in the range 1–4) and two reals A and B (B is not = 0). Output the result of the specified arithmetic operation with the given numbers.

    The resulting example:

    Enter arithmetic operation, please (from 1 till 4):
    >>> 1  
    Enter two real numbers:  
    >>> 2.2  >>> 5.0 
    the result is 2.2 + 5.0 = 7.2
    ---
    Enter arithmetic operation, please (from 1 till 4):
    >>> 2  
    Enter two real numbers:
    >>> 5.3  >>> 3.2 
    the result is 5.3 - 3.2 = 2.5
    

    [Program name: L3task23.pas]


    Using a String type

    {0.4 points} Task 24:
    To do: Perform the task using Case statement: The program must request the time of a day: midnight or night or morning or day or evening. The program must display a range of hours belonging to entered time of a day (midnight (24), night (1-4), morning (5-11), day (12-16), evening (17-23)).

    The resulting example:

    enter the time of the day
    >>> night
    result: a range of hours for night is 1..4
    

    [Program name: L3task24.pas]


    Using ranges and enumerations

    {0.4 points} Task 25:
    To do: Perform the task using Case statement with ranges: The program must request the time of day in hours (from 1 to 24). Depending on the time entered, display a message indicating what time of day the entered hour belongs to (midnight (24), night (1-4), morning (5-11), day (12-16), evening (17-13)).

    The resulting example:

    Enter a time of a day in hours (from 1 to 24), please: 
    >>> 14 
    result: 14 hours belongs to day
    ---
    Enter a time of a day in hours (from 1 to 24), please: 
    >>> 24
    result: 24 hours belongs to midnight
    

    [Program name: L3task25.pas]

    {0.4 points} Task 26:
    To do: Perform the task using Case statement with ranges: The program must request number - the age. Depending on the entered number display a message indicating the age of person in words (infancy: from 0 to 1 year old, early childhood: 2-4 years old, preschool: 5-7 years old, school age: 8 - 12 years old, youth: 13-19 years old, second youth: 20–35 years old, adulthood: 36-65 years, old age: over than 66 years).

    The resulting example:

    how old are you?
    >>> 6 
    preschool
    ---
    how old are you?
    >>> 37 
    adulthood
    

    [Program name: L3task26.pas]


    Hometask

    Complete this week's tasks that you didn't have time to do in class. The file names are specified in the tasks. You should upload your files to Microsoft Teams.

    Lesson #2. Working with digits of a number

    Theory

    Lection # 2 in pdf format

    Integer division and remainder after division

      Div
    • The div operation is an integer division, where the result is a number without fractional part.
    • The div operation calculates the integer part of the result of dividing integers (partial quotient ). For example:
    • 10 div  2 = 5
      22 div  7 = 3
      65 div 10 = 6
      ---
      N div K
      
      The result of N div K shows how many times K «fits inside» N.

      Examples:
      Example 1.

      How many Kilobytes are in x bytes?
      Answer: x div 1024
      

      Example 2.

      x is a time in seconds
      How many seconds have passed since the last minute?
      Answer: x mod 60
      
      Mod
    • The mod operation calculates the remainder after dividing two integers. In this case, if the numbers are evenly divisible, the remainder is zero. Example:
    • 10 mod  2 = 0
      22 mod  7 = 1
      65 mod 10 = 5
      ---
      N mod K
      
      The result of N mod K shows the «remainder of N» after the maximum number of K is «thrown» out of N.

      Examples
      Example 3.

      x mod 2 = 0 ⟹ x – even number
      x mod 2 <> 0 ⟹ x – odd number
      

      Example 4.

      var x := 1234;
      var LastDigit := x mod 10; // 4
      var NumWithoutLastDigit := x div 10; // 123

      Example 5.

      // x is a 3-digit number. What is the second digit?
      // Answer:
      var x := ReadInteger('Enter x:'); // 456
      x := x div 10; // 45
      Print(x mod 10); // 5

      Bitwise number operation

      Formula to get the number out of the quotient, divisor and remainder

      By parsing any integer N into two components — the quotient d and remainder m, using the same divisor K and operations div and mod, you will then easily restore this number by the formula:

      If we have 10:
      10 div 2 = 5
      10 mod 2 = 0
             ↓
      5 * 2 + 0 = 10


      Examples:

      10 div  2 = 5;  10 mod  2 = 0    =>   5*2 + 0  = 10
      22 div  7 = 3;  22 mod  7 = 1    =>   3*7 + 1  = 22
      65 div 10 = 6;  65 mod 10 = 5    =>   6*10 + 5 = 65 
      
    Standard Form Of A Number

    Any number can be disassembled into digits using powers of 10 and specified operations. This rule is called the standard form of a number:

    123 = 1*100 + 2*10 + 3

    Therefore, to make a certain number a hundred, you need to multiply it by 100 (as we have for digit 1 we have 1 * 100 = 100).

    3 Rules To Get Digits Of Three-Digit Integer (three bit width)
      It can be seen that:

    • to get hundred (first digit) of three-digit number, you need to calculate the quotient after dividing that number by 100 (number div 100, e.g. 123 div 100 = 1)
    • to get ten (second digit), you need to calculate the remainder after dividing that number by 100, and then — the quotient of dividing the result by 10 (1. number mod 100: 123 mod 100 = 23; 2. 23 div 10 = 2) (also there is another way)
    • to get unit number (third digit), you need to calculate remainder after dividing this number by 10 (number mod 10: 123 mod 10 = 3).
      For numbers with a different bit width, these algorithms can be changed.

    Labs and Tasks

    To complete the tasks, please, follow the rules.

    Task 1:
    To do: A distance L in centimeters is entered. Use the operation of integer division to convert it to meters of (1 meter = 100 centimeters). Use comments to make the program clear to user. Give the log of your program in the form of a comment after the program code.

    The resulting example:

    Please enter the distance in centimeters
    >>> 245
    The distance in meters is  2.45 
    

    [Program name: L2task01.pas]

    Task 2:
    To do: A mass in kilograms is entered. Use integer division to convert it to tons (1 ton = 1000 kilos). Use comments to make the program understandable to user. Give the log of your program as a comment after the program code.

    The resulting example:

    Please enter the mass in kilos
    >>> 4527
    The mass in tons is 4 
    

    [Program name: L2task02.pas]

    Task 3:
    To do: You are given the person’s age in months. Convert it to a person’s age in years (e.g: 65 months is 5 full years, 24 months is 2 years). Verify the correctness of your program, give the log s a comment.

    The resulting example:

    Please enter the age in months
    >>> 37
    The age in years is 3 
    

    [Program name: L2task03.pas]

    Task 4:
    To do: A two-digit integer is known. Output its first and second digits separated by commas.

    Note. Run the program and enter a non-two-digit number. What has happened? Is the result right? Later we will learn how to perform validation of the input data.

    The resulting example:

    Please enter a two digit number
    >>> 37
    The first and second are  7,  3 
    +++
    Please enter a two digit number:
    >>> -35
    The first and second are 5, 3
    +++
    Please enter a two digit number:
    >>> 90
    The first and second are 0, 9 
    

    [Program name: L2task04.pas]

    Task 5:
    To do: You are given a two-digit integer. Output the addition and multiplacation of its digits. Check the correctness of your program, give the log in the form of a comment.

    Note. Each digit of the number will be needed twice: in the calculation of the sum — the first time and in the calculation of the multiplacation — the second time. It is recommended to use auxíliary variables for storing the values of the digits.

    The resulting example:

    please enter a two digit number
    >>> 73
    you entered 73. The result is 10, 21 
    

    [Program name: L2task05.pas]

    Task 6:
    To do: A three-digit integer is entered. Output all of its digits (the order does not matter). Check the correctness of your program, give the log in the form of a comment.

    The resulting example:

    Please enter a three-digit number
    >>> -105
    The three digits are : 1, 0, 5 
    

    [Program name: L2task06.pas]

    Task 7:
    To do: A three-digit integer is entered. Output the addition of its digits. Make sure that your program works correctly with negative numbers.

    The resulting example:

    Please enter a three-digit number
    >>> -745
    You entered: 745. The addition of its three digits is equal to 16 
    
    

    [Program name: L2task07.pas]

    Task 8:
    To do: You are given two digits from 0 to 9. Use the standard form of a number to make a number, the digits of which are the specified digits.

    The resulting example:

    Please enter two digits
    >>> 3
    >>> 5
    The new number is 35 
    

    Check the following:

    3, 5 => 35
    7, 0 => 70
    0, 4 => 4
    

    [Program name: L2task08.pas]

    Task 9:
    To do: A two-digit integer is entered. Swap the values of its left and right digits. Check the correctness of your program, give the log in the form of a comment.

    The resulting example:

    please enter a two digit number
    >>> -57
    you entered -57. The result is -75
    

    Check the following:

    35 =>  53
    -10 => -1
    

    [Program name: L2task09.pas]

    Task 10:
    To do: A three-digit integer is entered. Swap the values of its left and middle digits. Check the correctness of your program, give the log in the form of a comment.

    The resulting example:

    please enter a three digit integer
    >>> 846
    After swaping the left and middle digits, the result is 486 
    

    [Program name: L2task10.pas]

    Task 11:
    To do: A three-digit integer is entered. Make a cyclic shift of digits to the left.

    The resulting example:

    please enter a three digit integer
    >>> -734
    After making a cyclic shift of digits to the left, the result is -347 
    

    Check the following:

     123 =>  231
    -602 => -26
    

    [Program name: L2task11.pas]

    Task 12:
    To do: A three-digit integer is known. Make a cyclic shift of digits to the right.

    The resulting example:

    please enter a three digit integer
    >>> -184
    After a cyclic shift of digits to the right, the result is -418 
    

    [Program name: L2task12.pas]

    Lesson #1. Introduction to PascalABC.NET

    Theory

    Lection # 1 in pdf format

    Variable Definition & Assigning a value to it

    • In Pascal abc.net variables can be defined within the body of the program between begin and end keywords. The principle of locality: a variable is defined immediately before it is used.
    • When we define a variable, we specify its name and type:

    •   
      So we have two possible versions:

    • In traditional pascal:
    • var n: integer; // variable declaration
      begin
        n:=1; // assignment statement
    • pascalAbc.net:
    • 1 method:

      begin
        var n:integer; // variable declaration
        n:=1; // assignment statement

      2 method (canonical method when type is defined depending on the value):

      begin
        var n:=1; // variable declaration and assignment statement => initialization

    Arithmetic operations and expressions

      common method:

      begin
        var a := 6; // Assigning value 6
        a:= a + 2; // Increasing by 2
        a:= a - 2; // Reduction of 2
        a:= a * 3; // Multiplication by 3
        a:= a / 2; // division
      end.

      short method:

      begin
        var a := 6; // Assigning value 6
        a+= 2; // Increasing by 2
        a-= 2; // Reduction of 2
        a*= 3; // Multiplication by 3
        a/= 2; // division
      end.

    Data input

    1-st way:

    begin
      var n:integer; // n is a variable of integer type
      read(n); // input some value to store it in n variable
    begin
      var n:real; // n is a variable of real type - floating point number
      read(n);// input some value to store it in n variable

    2-nd way:

    var n:=ReadInteger(); // n is a variable of integer type & we input some value to store it in n
    var x:=ReadReal(); // x is a variable of real type & we input some value to store it in x

    3-d way (tuple assignment):

    var n1, n2: integer; // two integers are declared
    (n1, n2) := (1, 2); // 1 is assigned to n1, 2 is assigned to n2

    4-th way:

    var(n1, n2) := readInteger2; // n1 and n2 are the variables of int type & we input some values to store it in them

    Usually before data reading you must print the prompt with an explanation of what data you read:

    var x := ReadInteger('Enter x:');
    var y := ReadInteger('Enter y:');
    var res := x + y;

    Data output

    1-st way:

    begin
      var n:integer;
      read(n);
      n: = n * n;
      writeln('n = ',n);

    2-nd way:

    begin
      begin
      var n:integer;
      read(n);
      n: = n * n;
      print('n = ',n);

    What does formatted output mean?

    For beautiful output, you should use formatted output with the WritelnFormat procedure or Print:
    1. WritelnFormat:
     

    WritelnFormat ('f ({0}, {1}) = {2}', a, b, c);

    The result will be:

    f (x, y) = z

    The first parameter in brackets and single quotes is a format string that specifies the format for outputting expressions.
    So, if we want to output:

    a + b = b + a = sum

    then you just need to replace a, b with {0}, {1}:

    WritelnFormat ('{0} + {1} = {1} + {0} = {2}', a, b, x + y)
  • You can specify the width (W) of the output field of the expression N (width in characters): {N,W}. For example, the operator
  • WritelnFormat('x = *{0,5}*', x); // 5 means 5 charecters for displaying x

    works this way:

    x = *    6*
    x = *   -3*
    x = *  123*
    x = *-9876*
    

    2. Print:

    var x := ReadInteger('Enter x:');
    var y := ReadInteger('Enter y:');
    var res := x + y;
    Print($'Sum of {x} and {y} is {res}');

    Swapping Variable Values

    We have:

    var (x,y) := (3,5);


    To do: To swap values of variables:
    Solution 1. Using temporary variable:

    var t := x;
    x := y;
    y := t;

    Solution 2. Using multiple assignment:

    (x,y) := (y,x);
    Two assignments x := y and y := x are carried out simultaneously! Not
    sequentially!

    Labs and tasks

    Follow the rules to make the tasks

    1. Save your files with names as it is given in tasks (e.g. task-04.pas).
    2. Give meaningful names to your variables.
    3. Use comments to make the program clear.
    4. Give the task of the program as a comment before the program code. Use curly braces for comments:
    5. Give the results of your program (log) as a comment after the program code. It’s easy to do just by copying. Use curly brackets to add comments:
    Sample 1:
    To do: Calculate the expression. The values of x, y and z are entered.

     
    The resulting example:

    Input x 
    3
    Input y 
    4
    Input z 
    5
    The result = 1.77800712886037
    

    [Program name: L1sample1.pas]

    ✍ Algorithm (how to do):

    {0.2} Task 1:
    To do: Assign the values to two variables (a=5, b=6). Calculate their average: (a + b)/2. Do this task twice: use different ways of assigning and output.

    Note: it is better to use here formatted output.  

    The resulting example:

    (5 + 6) / 2 = 5.5
    

    [Program name: L1task00.pas and L1task01.pas]

    {0.2} Task 2:
    To do: Assign the values to two variables (a=-0.80, b=-8.0). Calculate the sum, substruction, product and quotient of their squares.
      
    Note 1: To specify a particular number of digits after the floating point you can use format expression of writeln function:

    writeln('result = ', x:5:3) 
    5 means total number of signs to output the number,
     3 means the number of digits to output after floating point.
    

    Note 2: it is better to use here formatted output.

    The resulting example:

    a^2 + b^2 = 64.64
    a^2 * b^2 = 40.96
    a^2 - b^2 = -63.36
    a^2 / b^2 = 0.01
    

    [Program name: L1task02.pas]

    Sample 2:

    To do: The side of a square (variable name is side) is entered. Calculate its perimeter: P = 4·a. Use different methods of assigning, input and output.

     
    The resulting example:

    please enter the side length of a square:
    5.6
    Perimeter P = 22.4
    

    [Program name: L1sample2.pas]

    ✍ Algorithm (how to do):

      1-st way:

      begin
        Writeln('please enter the side length of a square:');
        // Variable declaration to store the value of the side length
        var a := ReadReal;
        var P := 4 * a; // Perimeter calculation
        Writeln('Perimeter P = ', P);
      end.

      2-nd way:

      begin
        Writeln('please enter the side length of a square:');
        // Variable declaration to store the value of the side length
        var a: real;
        readln(a);
        var P := 4 * a; // Perimeter calculation
        Print('Perimeter P = ', P);
      end.
    {0.3} Task 3:

    To do: The side of the square (variable name is side) is entered. Calculate its area: S = a2. Use different methods of assigning, input and output.

    Note: To calculate square of a number you can use sqr() standart function, for example:

    sqrX:=sqr(x);  

    The resulting example:

    please enter the side length of a square:
    2.90
    Area S = 8.41
    

    [Program name: L1task03.pas]

    {0.3} Task 4:

    To do: The sides of the rectangle are entered (a and b). Calculate its area (S = a*b) and perimeter (P = 2 (a + b)).
      
    Note: To specify a particular number of digits after the floating point you can use format expression of writeln function:

    writeln('S = ', S:0:2);
    // :2 means the number of digits to output after floating point

    The resulting example:

    Enter the values of two sides:
    12
    13
    result:
    S = 156.00
    P = 50.00
    

    [Program name: L1task04.pas]

    {0.4} Task 5:

    To do: A diameter of a circle (variable name is d) is entered. Calculate its length (formula L = π·d). The value of π is 3.14. Use different methods of assigning, input and output.
      
    Note 1: π has a constant value. In pascalAbc we can declare constant before the begin section of the program:

    const
      pi = 3.14;
    begin
     // ...
    end.

    Note 2: Make the program using the same style of coding as in sample 2.

    The resulting example:

    please enter a diameter of a circle:
    6.7
    the length of a circle is: 21.038
    

    [Program name: L1task05.pas]

    Sample 3:

    To do: Calculate hypotenuse and perimeter of a right-angled triangle, legs of triangle is entered (square root of (a2 + b2)).

    Note: To calculate square root of a number you can use sqrt() standart function, for example:

    sqrtX:=sqrt(x);  

    The resulting example:

    Input the values of triangle legs:
    3.0
    6.0
    hypotenuse = 6.70820393249937
    perimeter = 15.7082039324994
    

    [Program name: L1sample3.pas]

    ✍ Algorithm:

      Here is an example of right program which is clear for user:
    {0.4} Task 6:

    To do: The length of a cube edge is entered (a). Calculate the volume of the cube (V = a3) and its surface area (S = 6·a2). Give the program log in the form of a comment.
     
    Note: To specify a particular number of digits after the floating point you can use format expression of writeln function:

    writeln('V = ', v:5:3) 
    5 means total number of signs to output the number,
     3 means the number of digits to output after floating point.
    

    The resulting example:

    please enter the side length of a square:
    9.000
    V = 729.000
    S = 486.000
    

    [Program name: L1task06.pas]

    {0.4} Task 7:

    To do: Assign a value to integer variable x (x = 5). Calculate the value of the function:

    y = 4(x-3)6 - 7(x-3)3 + 2
    

     
    Note 1: To calculate the power of a number you can use the power(x:real, y:real) function. For example:

    //2 in the power of 5 =
    powNumb = power (2,5);

    Note 2: It is better to use an auxiliary variable for (x-3)3.

    The resulting example:

    for x = 5 we have y = 202
    

    [Program name: L1task07.pas]

    {0.4} Task 8:

    To do: Calculate the distance between two points with the given coordinates x1 and x2 on the number axis; the coordinates are entered. Formula |x2 − x1|.

    Note: To calculate the absolute value of a number you can use abc(x:real) standart function:

    abs(x2 - x1);

    The resulting example:

    x1 = 3.2
    x2 = 2.5
    the distance between two points: 0.7

    [Program name: L1task08.pas]

    {0.4} Task 9:

    To do: Calculate the distance between two points on the plane; coordinates (x1,y1) and (x2,y2) are entered. The distance is calculated by the formula:

    Note 1:Verify that your program is correct using «simple» values that are easy to calculate. For example:

    d((0,  0); (6, 0)) = 6;   
    d((0,  -4); (0, 1)) = 5;   
    d((-1,  1); (2, 5)) = 5:
    

    Note 2: Display the results of your program (log) in the form of a comment after the program code. It’s easy to do by simply copying. For comments use curly brackets:

    The resulting example:

    enter x1 of the first point:
    0
    enter y1 of the first point:
    0
    enter x2 of the second point:
    6
    enter y2 of the second point:
    0
    The distance equals 6

    [Program name: L1task09.pas]

    {0.3} Task 10:

    To do: The temperature in Celsius is entered, convert temperature to Fahrenheit. Celsius and Fahrenheit scales are related by the ratio:

    and opposite:

    The resulting example:

    please enter the temperature in celsius 
    56
    The temparature in fahrenhiet  132.8

    [Program name: L1task10.pas]

    Swapping Variable Values

    {0.2} Task 11:

    To do: Swap the values of variables A and B and print out the new values to the console.

    The resulting example:

    Enter A: 5.7
    Enter B: 3
    Result:
     A = 3, B = 5.7

    [Program name: L1task11.pas]

    {0.2} Task 12:

    To do: The values of variables A, B, C are entered. Swap their values to make A = B, B = C, C = A, and display the results.

    The resulting example:

    A = 3.4
    B = 2
    C = 1.5
    Result:
     A = 1.5, B = 3.4, C = 2

    [Program name: L1task12.pas]

    Lesson # 4. Enumerations

    Theory

    Enumerations

    The enum type declaration can be in the .cpp file at the top of the code (that is, outside of the functions), as well as in the header files.

    int main()
    {
      enum MyType { A, B, C }; // A=0 B=1 C=2
      enum YourType { D = 2, E, F = 0 }; // E=3
      MyType m = A;
    }
    Each enumerator is associated with a value of the underlying type. When initializers are provided in the enumerator-list, the values of enumerators are defined by those initializers. If the first enumerator does not have an initializer, the associated value is zero. For any other enumerator whose definition does not have an initializer, the associated value is the value of the previous enumerator plus one.
    Enumerations in style of C++11:
    int main()
    {
      enum class Color { Red, Green, Blue };
      Color c = Color::Blue;
    }

    One more example:

    enum Color { red, green, blue };
    Color r = red;
    switch(r)
    {
        case red  : std::cout << "red\n";   break;
        case green: std::cout << "green\n"; break;
        case blue : std::cout << "blue\n";  break;
    }
    // int n = r; // error: no scoped enum to int conversion
    int n = static_cast<int>(r); // OK, n = 21

    Type conversion by static_cast

    Sample 1:

    char c = 97;
    std::cout << static_cast<int>(c) << std::endl; // output 97, but not 'a'

    Sample 2:

    int i1 = 11;
    int i2 = 3;
    std::cout << i1/i2; // 3
    float x = static_cast<float>(i1) / i2;  // output x = 3.66667

    Labs and tasks

    Follow the rules:

    • To do the tasks, you must create a Visual Studio project: Lesson_4. When the tasks are done, it is necessary to upload the Lesson_4 project files (e.g. L4Task1Imp.cpp, L4Task1header.h and L4Task1main.cpp).
    • To do the tasks, you should use such C ++ structures as enumerations and switch statement.
    • All tasks must be done using functions, the results should be checked by assert statement from the header file , calling them from main with different arguments.
    • All functions and files must be accompanied by comments that describe the task.
    Lab 1:

    To do: Create a function (named printDay) that inputs the days of week (from 1 to 7) and returns the full name of the corresponding day (if 1 is entered, so function must print «Monday», etc.)

    Note: Add a header file to your project. Type there a declaration of the enumeration and the signature of your method:

    // enum type for representing a day: MON for Monday, etc.
    enum Day {MON=1, TUE, WED, THE, FRI, SAT, SAN };
     
    // prints given day to the standard output
    void printDay(Day);

    The resulting example:

    please enter the number of a day of a week:
    >> 2
    Tuesday
    

    [Solution and Project name: Lesson_4, file name L4Lab1Imp.cpp, L4Lab1main.cpp, L4Lab1header.h]

    ✍ How to do:

    1. Open Microsoft Visual Studio. Create a new console project, name your project Lesson_4. Among the Additional options mark Empty project and nothing more. Click Finish button.
    2. In the Solution Explorer window find a Source files folder, click the right mouse button on it and select Add -> New Item. We’re going to create two .cpp files. Call them as it is written in this lab description.
    3. In the Solution Explorer window find a Header files folder, click the right mouse button on it and select Add -> New Item. We’re going to create .h file. Give it a name as it is written in this lab description.
    4. First, let’s define an enumeration to store the names of the week days. The definition must be placed inside the header file. So, open header file and add the code:
    5. #ifndef L4LAB1HEADER_H
      #define L4LAB1HEADER_H
      // type for representing a day of a week
      enum Day { MON = 1, TUE, WED, THE, FRI, SAT, SAN };
       
      #endif L4LAB1HEADER_H
    6. Add the definition of our function printDay(). It must accept one parameter – the number of the day of a week (the type of parameter is Dayenum). The function definition must be placed inside the header file too:
    7. // prints given day to the standard output
      void printDay(Day);
    8. Open the code of L4Lab1Imp.cpp, we’re going to create an implementation of our function. Include the header file and std namespace:
    9. #include <iostream>
      #include <cassert>
      #include "L4Lab1header.h"
      using namespace std;
    10. Add a signature of your function:
    11. // prints given day to the standard output
      void print_month(Day d) {
        // ...
      }
    12. To check the day number we need to use Switch statement. Add the code inside the function scope:
    13. switch (d)
      	{
      	case 1:
      		std::cout << "Monday" << std::endl;
      		break;
      	case 2:
      		std::cout << "Tuesday" << std::endl;
      		break;
      	case 3:
      		std::cout << "Wednesday" << std::endl;
      		break;
      	case 4:
      		std::cout << "Thursday" << std::endl;
      		break;
      	case 5:
      		std::cout << "Friday" << std::endl;
      		break;
      	case 6:
      		std::cout << "Saturday" << std::endl;
      		break;
      	case 7:
      		std::cout << "Sunday" << std::endl;
      		break;
      	}
    14. Open the L4Lab1main.cpp. Include the header file and needed libraries:
    15. #include <iostream>
      #include <cassert>
      #include "L4Lab1header.h"
      using namespace std;
    16. Inside the main function ask user to enter an integer and assign the value to dayNumb variable.
    17. int dayNumb;
      cout << "please enter the number of a day of a week:";
      cin >> dayNumb;
    18. To call the function we need to pass it one parameter of out enumeration type (Day type). But all we have is dayNumb variable of integer type. We can use static_cast to convert the variable to Day type:
    19. Day d;
      d = static_cast<Day>(dayNumb);
    20. Now we can call a function:
    21. printDay(d);
    22. Run the program and check the output.
    Task 1:

    To do: Define a Month enumeration data type to represent the month.
    Create a function (named printMonth()) that will display the full month name for the passed short month name. Use a switch statement.

    Note 1: Create another function (named inc()) that displays the next month for the passed short month name.

    Note 2: add the header file. Inside the file add the enum and your function declaration:

    // type for representing a month: JAN for January, etc.
    enum Month {JAN=1, FEB, MAR, /* TODO: ... */ DEC};
    // prints given month to the standard output
    void printMonth(Month);
    // return next month
    Month inc(Month);

    Note 2: Look at the code below and understand it (using static_cast):

    (m == DEC)? JAN: static_cast<Month>(m + 1);
    Test this function from the main:
     assert (JAN == inc (DEC));

    The resulting example:

    Full name for JUN is: June
    The next month for DEC is: 1

    [Solution and Project name: Lesson_4, file name L4Task1Imp.cpp, L4Task1main.cpp, L4Task1header.h]

    Task 2:

    To do: Within the previous task create a function (named dec()) that, for the entered month, displays the preceding month.

    Note 1: Test this function from main:

    assert (JAN == dec (FEB));

    Note 2: Add the declaration into the header file:

    // return previous month
    Month dec(Month);

    The resulting example:

    Full name for JUN is: June
    The previous month for JUN is: 5

    [Solution and Project name: Lesson_4, file name L4Task2Imp.cpp, L4Task2main.cpp, L4Task2header.h]

    Task 3:

    To do: {2 points} Create function of Boolean type that returns True (or 1) if the year (positive integer) is a leap year, and False (or 0) otherwise.

    Note 1: A leap year is a year that is divisible by 4, except for those years that are divisible by 100 and not divisible by 400.
    Note 2: Add some tests to the main function. 2000 and 2012 are leap years, 2100 is a common year.

    Note 3: Add the declaration into the header file:

    // check if given year is leap
    bool is_leap(int);

    The resulting example:

    please enter the year:2000
    year is leap - 1

    [Solution and Project name: Lesson_4, file name L4Task3Imp.cpp, L4Task3main.cpp, L4Task3header.h]

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