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 the number K N times (loop must be used)

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 #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 or 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 nothing 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.3 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).

    Expected output:

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

    [Program name: L3task01.pas]

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

    Expected output:

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

    [Program name: L3task02.pas]

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

    Expected output:

    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]

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

    Expected output:

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

    [Program name: L3task04.pas]

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

    Expected output:

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

    Expected output:

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

    [Program name: L3task06.pas]

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

    Expected output:

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

    [Program name: L3task07.pas]

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

    Expected output:

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

    [Program name: L3task08.pas]

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

    Expected output:

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

    [Program name: L3task09.pas]

    Chained If statements and Logical operations in if statements

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

    Expected output:

    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.5 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".

    Expected output:

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

    [Program name: L3task11.pas]

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

    Expected output:

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

    [Program name: L3task12.pas]

    {0.5 points} Task 13:
    To do: Two integer values are given (set them to 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.

    Expected output:

    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.5 points} Task 14:
    To do: An two-digit 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.

    Expected output:

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

    [Program name: L3task14.pas]

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

    Note: The sign means boolean or.

    Expected output:

    Enter an integer: 
    >>> 4
    Result is 8
    

    [Program name: L3task15.pas]

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

    Expected output:

    please, enter an x value: -2
    result of 6-x =  8 
    
    please, enter an x value: 5
    result of 2sin(x) =  -1.91784854932628 
    

    [Program name: L3task16.pas]

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

    Expected output:

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

    Expected output:

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

    [Program name: L3task18.pas]

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

    Expected output:

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

    Expected output:

    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: L3task20.pas]

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

    Expected output:

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

    [Program name: L3task21.pas]

    {0.5 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!".

    Expected output:

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

    [Program name: L3task22.pas]


    Using a String type

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

    Expected output:

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

    Expected output:

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

    Expected output:

    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:
     

    begin
      var a:=1.2;
      var b:=4;
      var c:=a+b;
      WritelnFormat ('f ({0}, {1}) = {2}', a, b, c); 
    end.

    The result will be:

    f (1.2, 4) = 5.2

    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 an area of the square: S = a2. You should 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:

    enter a 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 an area of the rectangle (S = a*b) and its 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 the triangle are 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: A length of a cube side 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:

    enter a cube side length:
    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 copying and pasting. You should use curly brackets for comments:

    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:

    enter the temperature in Celsius 
    56
    The temperature in Fahrenheit  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]

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