Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Write down and run this program on your computer

Programs and algorithms | Algorithms and programming languages | Fundamentals of programming I | Student is obliged to write down and run this program by himself | Data in a program (variables and literals) | Operations on data (operators and expressions) | Introduction to objects | The first program | Types. Primitive types. | Types of variables. Declarations. |


Читайте также:
  1. A FIRST LOOK AT COMPUTERS
  2. A friend of yours wants to develop a programme to protect the city where he lives. Give him a piece of advice.
  3. A writer’s life
  4. A writer’s life
  5. A) write a letter to Peter;
  6. Active Directory Users and Computers
  7. Algorithms and programming languages

Iteration loops (do, do while), as well as the if instructions may be nested.

Nesting of language structures is done by putting one inside another.


For example, the following code is correct:

do while (a > b) do i = 1 to N.... do j = 1 to M..... do while (s = "")... end end endend

When nesting statements, one must remember to match their beginnings and ends (in this case to each opening do must correspond the closing end).
Suitable code formatting (indentation of lines) helps in matching the start and end of a statement.
The above example demonstrates one of the possible manners of code formatting.

Source code formatting (indentation) makes it readable and allows easier error detection.

 

The usual operation of an iteration loop may be changed with the help of:

In the Java language the break statement is used for breaking loops.

Breaking a normal loop operation in REXX is done using the leave statement. The innermost lexically enclosing instance of a loop is then left. If a label is used together with the leave statement: leave aLabel - the loop designated with this label is left.
For example:

do i = 1 to 100000 n = i * i; if (n > 20000) then leave;endsay i n;

Result:
142 20164

The loop was executed 142 times (not 100000 as the upper limit of the counter suggests), because control leaves it (after executing the leave statement) when the value of the variable n becomes greater than 20000. The execution of the program continues starting with the instruction following the end closing the loop.


The continuation of a loop operation consists in the immediate transfer of control to the end of the loop, which causes a new iteration to begin.

In Java the continue statement is used for this.

In REXX the iterate statement is used for continuing execution of a loop. Similarly to the leave statement, it is applied to the innermost lexically enclosing loop, or the loop designated with the given label.
As an example, the following program reads the strings typed by the user at the command prompt, ignoring empty lines. It concatenates them and then, after the user has typed the word "quit", displays the result at the command prompt, ending the operation of the program.

out = '';do forever txt = linein(); if (txt = "") then iterate; if (txt = "quit") then leave; out = out txt;endsay out;

 

In Java, the infinite loop is encoded as: while (true) {...}

Notice the notation do forever, specifying an infinite loop (executing infinitely; it must be broken somehow, of course).
In general, one has to pay special attention to properly terminate the execution of a loop. It is a common mistake and a source of severe runtime errors to define loops which iterate forever, without stopping. Often the only way to get out of such a situation is to terminate the running program at the operating system level.


 

Arrays

Data in a program are often grouped in sets which are treated as logical units, although they are composed of a number of elements. Such a set should have a single name (because it designates a logical unit). Its components should be accessible using this name plus some other information identifying a particular element in the set.
Special cases of such sets are arrays.

Arrays are sets of data elements. Each element is stored at the specified position in an array and is randomly accessible (without the need for looking over the rest of the array) by using the name of the array and index (position) of this element in the array.

 

Assume we want to use the set of names for days of the week.
Let us call this set - the array - days.
The consecutive elements of this array are numbered with integer indices (one corresponding to Monday, two corresponding to Tuesday and so on).
Yet we need some syntactic facility which allows to denote individual elements of an array.
In our simplified (based on the REXX) language - as in Java, C and C++ - square brackets with an integer index placed in between are used to access elements of an array (note that this is a modification of the original REXX syntax, required for the purpose of this lecture only).
So we can write:

days[1] = "Monday";
days[2] = "Tuesday";
days[3] = "Wednesday";
days[4] = "Thursday";
days[5] = "Friday";
days[6] = "Saturday";
days[7] = "Sunday";

Array elements may be treated as variables. To these variables the given values are assigned.
This is not the only way of setting values of the array elements.
Arrays may be initialized easier with the help of special syntactic facilities. In the simplified REXX the initialization of arrays is done (as in Java) with curly brackets:

days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

Note: in simplified REXX such an array initializer must occupy a single line of code and is suitable for one-dimensional arrays only.
One has to remember to put the empty braces [] after the array's name.

This notation has exactly the same meaning as the previous one: to the element of array days, under the position 1 the value "Monday" is assigned. To the element under position 2 - the value "Tuesday", and so on.

Of course, besides setting the value of the array element, one can get the value of an element as well.
The following program displays the current day of week using the built-in function date () for this purpose.

/* Displays the current day of the week */ days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};dayc = date('B') /* number of days since 1 of January 0001 */dayNum = dayc // 7 + 1say 'Today is:' days[dayNum]

The built-in function date called with the 'B' argument returns the number of days that elapsed since the 1 of January 0001 (Gregorian calendar) until yesterday inclusive. Just because on 01.01.0001 was Sunday, the remainder of division of the returned number of days by 7 gives: 0 for Mondays, 1 for Tuesdays,..., 6 for Sundays. Adding 1 to this result we get a suitable index in the array.


Дата добавления: 2015-11-16; просмотров: 70 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Fundamentals of programming II| Write down and run this program on your computer

mybiblioteka.su - 2015-2024 год. (0.007 сек.)