## Lesson #9. Nested loops

### 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

## Theory

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

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


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

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

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:

### 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! 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. 6. 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:
7. 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


{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


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


{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


{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


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


{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


{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

{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

{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

### 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

{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

## 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

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

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

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.

… // 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]

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

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

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.

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

Вставить формулу как
Дополнительные настройки
Цвет формулы
Используйте LaTeX для набора формулы
Предпросмотр
$${}$$
Формула не набрана
Вставить 