Programming linear algorithms. Independent work on computer science in 9th grade. methodological development in computer science and ICT (grade 9) on the topic


Program structure in Pascal language

Before writing programs yourself, let’s look at its structure using an example. Below is the code for a program that calculates the sum of two numbers and displays it on the screen.

program primer1; var x,y,z:integer; { description of variables } begin { start of program } x := 3; { setting the value of x } y := 5; { setting the value of y } z := x + y; { calculate the sum } write(z); {output the calculation result to the screen } end. {end of program}

how to write a pascal program structure of a pascal program

Program title

The program text begins with the word program . After it the name of the program is written. This line is for informational purposes and does not need to be written.

The section for connecting modules begins with the service word uses , followed by a list of module names, separated by commas.

The description section may include sections describing variables, constants, labels, types, procedures and functions, which follow each other in any order. The section for connecting modules and the section for descriptions of labels, constants, etc. may be missing.

Variable description section

The section of the program, designated by the operative word var, contains a description of variables indicating their types. They are used to store source data, calculation results and intermediate results.

Comments in a program can be written inside curly braces. They are ignored during program execution. You write these explanations only for yourself.

In our example, variables named X and Y are used to store the original data. A variable named Z is used to store the result of the calculation.

The variable name can be written in capital or small Latin letters. The name can contain numbers, underscores and must not start with a number. Uppercase and lowercase characters are considered the same. You cannot use a Pascal function word as a name.

Variables of the same type can be specified on one line, separated by commas. After that, a colon is placed and the type to which the variables belong is indicated. The type defines the valid range of values.

integer variable means that it can only store integers. If you need to store real (fractional) numbers, then the real .

Program body

Everything that is between the service words Begin and end is the body of the program. Basic commands are written here.

The variable assignment operator has the following structure: variable := expression

The symbol : = (colon, equals) is read as “assign”. Multiplication is indicated by the symbol * (asterisk), division by the symbol / (slash).

write command .

Each line containing a command in the Pascal language must end with a semicolon.

Pascal language online

§ 58. Linear algorithms and programs

Having studied this point, we:

Let's find out how you can assign a value to a value while the program is running; Let's get acquainted in practice with the procedure for compiling an algorithm and program; learn how program testing is carried out;

Let's learn from an example how a computer experiment is carried out.

==== 58.1.Assigning values ​​to quantities

=======================================

In linear algorithms, the main means of processing quantities is to assign them a new value. Assignment command

The NAM language is quite similar in designation, action and methods of application
to the Assignment Operator
of the Pascal programming language.

We know that in the Pascal language there is a Read operator,

which allows you to provide a value with a specific value from the keyboard.
Unlike the Read
, the assignment operator allows you to provide a variable with a value that is not known in advance and will be determined by the computer itself during the execution of the algorithm. If there were no assignment operator, a computer would be no different from a simple calculator that performs operations only on known numbers.

The assignment operator is denoted by
Assignment =
sign and has the following construction:

Variable name =

expression;

The assignment operator is executed from right to left: first the value of the expression is calculated, then this value is assigned to the variable. The preliminary value of the variable is lost and replaced with a new one.

The value type of the expression must match the value type of the variable. A numeric variable cannot be given a text value, while an integer variable cannot be given a real value. However, a real variable can be given an integer value and it will become true (for example, the integer value 5 will become true 5.0).

==== 58.2.Using the assignment operator

===================================

The assignment operator allows you to assign values ​​to variables of any type. We'll look at using the operator to provide values ​​for numeric type variables.

1. A variable can be given a specific numeric value. In this case, a numerical constant acts as an expression. For example:

I: = 1;

S: = 0;

Such assignments are typically used to provide initial values ​​for variables.

Read Table and its elements, tabular values

2. A variable can be given the value of another variable, for example:

X = y;

As a result of executing the operator, the variable x (not y) acquires a new value equal to the Current

the value of y, that is, the one that the variable y had at the time of assignment. If the variable y later acquires different values, this will not affect the value of the variable x.

3. The new value of a variable can be determined through its current value. For example, to increase the value of x by one, the operator is used:

X = x + 1;

To double the operator:

X = 2 * x;

4. A variable can be assigned a value using a formula. The formula is given by the corresponding expression. So, to provide x the value using the formula X

= n
R
2, write the assignment operator in the form:

X = pi * sqr (r)

Let's see how the values ​​of the integer variables x and y change during the execution of the chain of operators:

==== 58.3. The procedure for compiling an algorithm and program. Program "Segment"

============

Let's get acquainted with the procedure for compiling an algorithm and a program using the example of the problem of calculating the length of a segment from the known coordinates of its ends.

· First of all, let us clarify the statement of the problem. We will assume that the segment is in the XOY plane and is specified by the Cartesian coordinates of its end points. You need to find the length of the segment, that is, the distance between two given points.

· Let us introduce some notation. Let xp, yp denote the coordinates of the starting point of the segment, and xk, yk

the coordinates of its end point, through d
-
the length
of the Segment.
For any coordinate values, we can calculate the value of d.

· Let's find out the relationship between the quantities xp, yp, xk, yk and D.

The length of a segment is found through the coordinates of its end points with the formula:

D = ((xk - xp) 2 + (yk - yp) 2) 1/2.

This is the information model of the problem.

· Let's create an algorithm for solving the problem. Our problem is simple, it can be solved using one formula, and allows us to immediately write down the algorithm.

According to the statement of the problem, the variables xp, yp, xk, yk, d are real. Value of xp, yp and

Read Lecture Operators of the Pascal language

Xk, yk are the method arguments, the value d is its result.

Let's write the algorithm using NAM (Fig. 58.1) and, according to the algorithm, create a program

(Fig. 58.1b).

Alg segment (Really
Xp, yp, xk, yk, d)
Program
distance;

Uses

Crt;

Arg xp, yp, xk, yk
Res d
Var
Xp, yp, xk, yk, d: Real;
BeginningBegin
Clrscr;
Writeln

('Enter xp,yp');
Readln
(xp, yp)
Writeln
('Enter xk, yk');
Readln
(xk, yk)

D =
((xk-xp) 2 + (yk-yp) 2) 1/2
D =
sqrt (sqr
(xk-xp)
+ sqr (yk-yp))
Writeln
('Segment length', d: 7:2)

Readln;

ConEnd.

A) NAM algorithm; b) Pascal program

Rice. 58.1. Calculation of the length of a segment based on the given coordinates of its ends.

· The compiled algorithm and then the program must be checked for correctness. The simplicity of our task does not exclude such verification. To prove the correctness of the program, we will use testing. Testing

means launching a program for execution with such input data for which the results of the program are known in advance.

Let's create a data table to test our program.

Test
Input dataResultHelp
XpYpXkYkD
1594The segment lies on the OY axis
2-2-53The segment lies on the OX axis
3345The segment is the hypotenuse of a right triangle

If at least one result does not coincide with the expected one, it is necessary to find and eliminate the error in the program. If testing confirmed the correctness of the program, then we received a computer model that can be used to calculate the lengths of any segments (provided that the coordinates of their ends and lengths do not exceed the permissible values ​​of variables of the Real type).

==== 58.4. Conducting a computer experiment

===============================

We will use the developed “Segment” program as a computer model to conduct the experiment.

Let's consider the problem. At a distance from the village there is a gas main. To gasify a village, you need to find the shortest way to connect it to the main line.

Let us denote the coordinates of the village on the plane by Xp,
Yp;
let's define the gas pipeline line as straight line
Y = kx + b;
We will denote the length of the gas pipeline that should connect the village with the main line by
D.
We need to find the point of the main line
K
to which the gas pipeline should be extended so that the value of
D
is minimal.
the coordinates of point K
by
Xk, yk.
The required values ​​Xk, yk

we will find through a computer experiment.

Let's carry out the experiment for the case: Xp

= 5,
Yp
= 7;
K
= 1;
B
= 0. Since the gas pipeline line is a straight line
Y = - x,
it is enough for us to set the value of
Xk,
and the value
of Yk
to determine as
Yk = - xk.
We summarize the obtained data in a table.

Xk321
Yk-3-2-1
D10,209,498,94

You can make sure that the value of D,

which corresponds to the coordinates
Xk
= 1;
Yk
= 1, namely
D
= 8.94, is the smallest.
So, the desired point of the gas main is point K
(-1, 1). This conclusion is also confirmed theoretically.

Note that for the convenience of conducting the experiment, it is advisable to value Xp

= 5,
Yp
= 7

Present as constants:

Const

xp = 5, yp = 7;

And exclude Xp,
Yp
from the description of variables, and

remove Writeln, Readln

CONCLUSIONS

The main tool for processing quantities in linear algorithms and programs is the assignment command (operator). It is written using the assignment sign: = and allows you to provide values ​​to quantities during the execution of the algorithm (program). The procedure for compiling an algorithm and a program corresponds to the stages of creating a computer model: first, we analyze the formulation of the problem, introduce the designations of quantities used in the problem, establish their relationships and develop an information model of the problem, on its basis we compile an algorithm for solving the problem and turn it into a program. We analyze the algorithm for correctness, and verify the correctness of the program by testing, that is, for specially selected input data, we check whether the results obtained by the program coincide with those known in advance. The developed program is a computer model of the problem and can be used to conduct experimental research.

Test questions and exercises

1. Which variable will receive a new value as a result of executing the operator: m = n?

A) variable n;

B) variable m;

B) variables m and n.

2. What value will be provided to the variable y as a result of executing the statements:

X = 10; y = x + 2, x = 3 * Y;

A) 10;

B) 30;

B) 36;

D) 12.

3. which values ​​will be received by the variables x and y as a result of executing the operators:

X = 30; y = x Div

5, x = x - y
Mod
2;

A) X

= 24;
Y =
6;
b) X
= 27;
Y =
6;
c) X
= 30;
Y =
6;
d) X
= 24;
Y =
0.

4. What values ​​will the variables x and y receive as a result of executing the operators?

X = 22; y = 34 - x Div

5, x = (y - x)
Mod
7 - 2;

A) X

= 1;
Y=
30;

B) X

= -5;
Y =
2;
c) X
= 1;
Y =
32;
d) X
= 3;
Y =
30.

5. which values ​​will be received by the variables x and y as a result of executing the operators:

X = 2; y = sqr (7 + x) Div

8; x = abs (x - 2 * y) * (x - y)

A) X

= -4;
Y=
3;

B) X

= -144;
Y=
10;

B) X

= 0;
Y =
1;
d) X
= 4;
Y =
0;
e) X
= 4;
Y =
3;

E) X

= 144;
Y = 10.
6. Create a program for determining the traction force of a car engine based on the known weight of the car and the time during which it, moving from a standstill, picks up a speed of 100 km/h.

P was placed on one pan of the scale.

kg on another put
M
kg of bananas
(m> P). Create a program to determine how many bananas a monkey eats in one minute if the scales
are leveled in 5 minutes.

8. Create a “Breakfast to Order” program. A menu of 5 dishes (one at a time) is displayed on the screen. For each dish, the user must put either 0, if he does not need it, or 1, if he orders it for breakfast. The program displays the bill for breakfast and wishes the customer bon appetit.

9. Create a program that, based on data about the owner of the apartment, its area, number of residents and electricity costs, calculates utility bills and displays a corresponding message addressed to the apartment owner.

10. Create a program for counting the number of rolls of wallpaper that you need to purchase to cover the walls of a room of height H

meters, if the perimeter of the room is
S
meters.
Using the program, perform calculations and determine which wallpaper is more profitable to purchase for covering walls in a room with given dimensions (for example, H
= 2.75 m,
S =
15 m):

In rolls 10.5 m long, 0.5 m wide (price 15 UAH per roll), in rolls 18 m long, 0.5 m wide (price 25 UAH per roll),

In rolls 25 m long and 0.6 m wide (price 35 UAH per roll).

The walls are covered with continuous stripes.

11. Create a program for determining the entrance number and floor number where apartment number N is located,

if it is known that the house
P
storeys and there are
K
apartments on each floor in the entrance.

12. Rectangular box size A

´
B
´
C
is filled with layers of identical metal balls with diameter
D.
Create a program for calculating the weight of the balls that fill the box, using the known values ​​of
A, B, C, d
and
P -
the specific gravity of the metal from which the balls are made. Using the program:

1) find the weight of the balls for the following data: A

= 18 cm,
B
= 24 cm,
C
= 12 cm,
D
= 6 cm,
P
= 7.9 g/cm 3 (iron)

2) explore how the weight of the filling changes if the balls are taken twice, three times, four times, six times smaller in diameter. Draw conclusions;

3) complete your result mathematically.

[Total votes: 3 Average: 5/5]

  • Lectures Pascal

Related Articles

COMPUTER SIMULATION – Fundamentals of algorithmization and programming updated: November 16, 2018

Algorithm, its properties and forms of representation

updated: November 16, 2018

Basic structures of algorithms – Types of algorithms

updated: November 16, 2018

Quantities and their description, General structure of the algorithm

updated: November 16, 2018

Entering and displaying values ​​| Components of the value processing algorithm

updated: November 16, 2018

Add a comment Cancel reply

« Laboratory work No. 1 Pascal – Compilation and debugging of linear programs

Significant Paragraph is a large set of text data in office programs, which is divided by its formatting parameters: alignment, intervals, styles, etc.

Input and Output Commands

Read command

In the first example, we assigned values ​​to variables directly in the program text. But since the program is written to solve many similar problems, it is more convenient to set values ​​for variables while it is running. To do this, use the read , which allows you to enter text or numeric data from the keyboard.

Let's modify the program code from the example above.

program primer1; var x,y,z:integer; { description of variables } begin { start of program } read(x,y); { entering x and y values ​​from the keyboard } z := x + y; { calculate the sum } write(z); {output the calculation result to the screen } end. {end of program}

Now the values ​​of the variables X and Y will be entered at the request of the running program. At this point, you will need to enter two numbers separated by a space from the keyboard and press the Enter key to continue executing the program.

When the program is running, a data entry line will appear in the PascalABC programming system. The values ​​of the variables are written there.

Write command

In the previous example, when the program is running, it is not entirely clear what needs to be entered and what numbers appear on the screen when the program completes. Therefore, we will change the program code so that it has a minimal user interface. To do this, we will use the Write command that is already familiar to us.

program primer1; var x,y,z:integer; { description of variables } begin { start of program } writeln('Calculating the sum of two numbers'); write('Enter two integers separated by spaces'); readln(x,y); { entering x and y values ​​from the keyboard } z := x + y; { calculating the sum } write('Sum = ',z); {output the calculation result to the screen } end. {end of program}

Now see how the added lines affected the program's performance.


We have some clues.
Look at the write . The text enclosed in apostrophes was used as her argument. And yet, the ending ln in the write . It is this that forces subsequent output of information to be done on a new line. This same ending can be used in conjunction with the read .

The output of the result has also changed. There is also a hint here.

Examples of Pascal programs - tasks on linear algorithms

Task 1. Modify the program so that it calculates and displays the sum and product of three integers.

Solution:

program zadanie1; var x,y,k,z,p:integer; { description of variables } begin { start of program } writeln('Calculating the sum and product of three numbers'); write('Enter three integers separated by spaces'); readln(x,y,k); { entering values ​​x,y,k from the keyboard } z := x + y + k; { sum calculation } p := x * y * k; { calculating the product } write('Sum = ',z); {output the result of addition to the screen } write('Product = ',p); {output the result of the product to the screen } end. {end of program}

Task 2. Given the length of the cube edge a. Find the volume of the cube V=a3 and its surface area S=6a2.

Solution:

program zadanie2; var a,v,s:real; { description of variables } begin { start of program } writeln('Calculating the volume and surface area of ​​a cube'); write('Enter the length of the cube edge'); readln(a); { entering the value of a from the keyboard } v := a * a * a; { volume calculation } s := 6 * a * a; { area calculation } write('Volume of cube = ',v); {output the result volume of the cube } write('Surface area = ',s); { output surface area result } end. {end of program}

See more examples of linear algorithms.

If you want to learn more about the PascalABC system and start writing your first programs in it, then the article “Introducing PascalABC” is for you.

Next topic to study Conditional operator

PROGRAMMING OF LINEAR ALGORITHMS START OF PROGRAMMING. - presentation


PROGRAMMING OF LINEAR ALGORITHMS START OF PROGRAMMING


Keywords real data type integer data type character data type string data type logical data type

Numeric data types Standard Pascal functions: Function Purpose Argument type Result type abs (x) Module x integer, real Same as argument sqr (x) Square x integer, real Same as argument sqrt (x) Square root of x integer, realreal round (x) Rounding x to the nearest integer real frac (x) Integer part of x real int (x) Fractional part of x real random Random number from 0 to 1 -real random (x) Random number from 0 to x integer

roundint frac Exploring the functions round, int and frac Execute the program several times for x {10,2; 10.8; –10.2; –10.8}. What will be the result type of each of these functions? program n_3; var x: real; begin writeln('Exploring the functions round, int, frac'); write('Enter x>>'); readln(x); writeln('Rounding - ', round(x)); writeln('Integer part is ', int(x)); writeln('Fractional part is ', frac(x)) end. ?

Integer data type Operations on integers in the Pascal language: Operation Notation Result type Addition + integer Subtraction - integer Multiplication * integer Getting an integer quotient div integer Getting an integer remainder of division mod integer Division / real

divmod Operations div and mod program n_4; var x, a, b, c, s: integer; begin writeln('Finding the sum of the digits of a three-digit number'); write('Enter original number >>'); readln(x); a:=x div 100; b:=x mod 100 div 10; c:=x mod 10; s:=a+b+c; writeln('s= ', s) end. A three-digit number can be represented as the following sum: x = a ·100 + b ·10 + c, where a, b, c are the digits of the number. A program for finding the sum of the digits of a three-digit integer number entered from the keyboard.

Character and string data types ord The ord function converts a letter to its numeric code. char. Symbols are all the letters and icons that are on the keyboard. To enter character variables into a program, you must specify the character data type char for them. chr The chr function converts the numeric code of a character into the character itself. string The value of a string value (type string ) is an arbitrary sequence of characters enclosed in apostrophes. W chr 87ord W%37%4524S83S var c: string c:= chr(52)+chr(37) with 4%

Character and string data types program n_5; var a: char; code:integer; b:string; begin writeln('Code and line'); write('Enter initial letter>>'); readln(a); kod := ord ( a ); b:=chr(kod–1)+a+chr(kod+1); writeln('Letter code', a, '-', kod); writeln('Line: ', b) end. Displaying the code of a letter entered from the keyboard Displaying a string of three letters on the screen. Which ones?


Boolean data type falsetrue ; Boolean values ​​take only two values: false and true ; falsetrue false

Boolean data type ans Let ans be a logical variable, n an integer variable. As a result of executing the assignment operator ans:=n mod 2=0, the ans variable will be assigned the value true for any even n and false otherwise. program n_6; var n: integer; ans: boolean; begin writeln ('Determining the truth of a statement about the parity of a number'); write('Enter original number>>'); readln(n); ans:=n mod 2=0; writeln('The number ',n,' is even - ', ans) end.

Boolean data type and)ornot Boolean variables can be assigned the values ​​of logical expressions constructed using the logical functions and ( and), or ( or), not ( not). Logical operation in Pascal Name of the operation and conjunction (logical multiplication) or disjunction (logical addition) not negation (inversion)


program n_7; var a, b, c: integer; ans: boolean; begin writeln('Determining the truth of a statement about an isosceles triangle'); write('Enter values ​​a, b, c >>'); readln(a, b, c); ans:=(a=b) or (a=c) or (b=c); writeln ('A triangle with side lengths ', a, ',', b, ',', c, ' is isosceles - ', ans ) end. Boolean data type


The most important data types in the Pascal language: real integer character string logical and others. The corresponding operations and functions are defined for them.

Questions and tasks For a given x, calculate y using the formula y = x 3 + 2.5 x 2 – x +1. In this case: a) the operation of exponentiation is prohibited; b) in one assignment operator you can use no more than one arithmetic operation (addition, multiplication, subtraction); c) no more than five assignment operators can be used in a program. Hint: transform the expression to the following form: y =((x + 2.5 )x – 1 )x + 1. Given the coordinates of points A and B, calculate the length of the segment AB. Example Input Example Output xa = 2 ya = 1 xb = 10 yb = 7 | AB | = 10.0 The lengths of the sides of the triangle a, b, c are known. Write a program to calculate the area of ​​this triangle. Example of input data Example of output data a = 3 b = 4 c = 5 s = 6.0 The coordinates of the vertices A, B, C of the triangle are known. Write a program to calculate the area of ​​this triangle. Example of input data Example of output data xa = 2 ya = 1 xb = 6 yb = 5 xc = 10 yc = 1 s = 16.0 If the tax amount is calculated in rubles and kopecks, then the tax service rounds it to the nearest ruble (up to 50 kopecks - from deficiency, over 50 kopecks (including 50 - in excess). Use your computer to enter the exact tax amount and display how much you owe. Explore the operation of the random function by running the program repeatedly: program n_8; var x, n: integer; begin writeln('Exploring the random function'); randomize (*to generate different random numbers each time the program is run*); write('Enter x>>'); readln(x); write('Enter n>>'); readln(n); writeln('random(', x, ')=', random(x)); writeln ('random(', x, ')+', n, '=', random(x)+n) end. How can you get a random number from the interval (0; x)? How can you get a random number from the interval (0; x]? How can you get a random number from the interval (n; x + n)? One company has issued three categories of lottery tickets: for youth, adults and old people. Ticket numbers for each category range from: for youth - from 1 to 100; for adults - from 101 to 200; for old people - from 201 to 250. Using a computer, select a random lottery ticket in each digit.Write a program in Pascal that, for an arbitrary two-digit number, determines: a) the sum and product of its digits; b) a number formed by rearranging the digits of the original number. Example of input data Example of output data 845To be handed over: banknotes of 500 rubles. - 1 PC. banknotes of 100 rubles. - 3 pcs. banknotes of 50 rubles. – 0 pcs. 10 ruble banknotes - 4 things. Write a program in Pascal that calculates the sum of letter codes in the word BYTE. Write a program in Pascal that displays a string of characters whose codes are 66, 69, 71, 73, 78. Develop a program that requests three string values ​​- the interrelated adjective, noun and verb, and then prints all the variants of phrases using entered words. Example input data Example output data GREEN LEAVES BLOWING GREEN LEAVES BLOWING GREEN LEAVES BLOWING LEAVES GREEN BLOWING LEAVES BLOWING GREEN BLOWING GREEN LEAVES BLOWING LEAVES GREEN Given the values ​​of integer variables: a = 10, b = 20. What will be the value of the logical variable rez after performing the operation assignments? a) rez:=(a=10) or (b>10) b) rez:=(a>5) and (b>5) and (a

Basic summary Data type in Pascal Data types in the Pascal language: real, integer, character, string, logical. Integer Logical abs (x), sqr (x), sqrt (x), +, -, *, / Numeric ord, char Character and, or, not Real

Test "Linear algorithm"

Time limit: 0

Navigation (job numbers only)

0 out of 5 tasks completed
Questions:

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5

Information

Test your knowledge on the topic “Linear Algorithm”

You have already taken the test before. You can't start it again.

The test is loading...

You must log in or register in order to begin the test.

You must complete the following tests to start this one:

results

Correct answers: 0 out of 5
Your time:

Time is over

You scored 0 out of 0 points (0)

Average result
Your result

Categories

  1. Linear algorithm 0%

maximum out of 5 points

PlaceNameRecordedPointsResult
Table is loading
No data

Your result has been recorded in the leaderboard Loading

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  1. With answer
  2. With a viewing mark
  1. Task 1 of 5
    1.

    Category: Linear algorithm

    What is a linear algorithm?

    Right

    Wrong

  2. Task 2 of 5
    2.

    Category: Linear algorithm

    Which command allows you to enter text or numeric data from the keyboard?

    Right

    Wrong

  3. Task 3 of 5
    3.

    Category: Linear algorithm

    Provide all correct write options for the output statement

    Right

    Wrong

  4. Task 4 of 5
    4.

    Category: Linear algorithm

    Specify the correct sequence of commands in the program to calculate the sum of two numbers

    • writeln('Calculating the sum of two numbers');
    • write('Enter two integers separated by spaces');
    • readln(x,y); { entering x and y values ​​from the keyboard }
    • z := x + y; {sum calculation}
    • write('Sum = ',z); {output the calculation result to the screen}

    Right

    Wrong

  5. Task 5 of 5
Rating
( 2 ratings, average 4.5 out of 5 )
Did you like the article? Share with friends: