Loop for vba excel description. "VBA Loop Statements

Loops allow you to execute one or more lines of code multiple times. VBA supports the following loops:

For...Next For Each...Next Do... Loop

The For construct. . . next. When the number of repetitions is known in advance, a For loop is used. . . next. A For loop uses a variable called a loop variable or loop counter that increments or decrements by a specified amount each time the loop repeats. The syntax for this construct is:

For counter = start To end Next statements

The parameters counter (counter), start (cycle start), end (cycle end) and increment (increment) are numeric.

Note. The increment parameter can be either positive or negative. If it is positive, the start parameter must be less than or equal to the end parameter, otherwise the loop will not execute. If the increment parameter is negative, then the start parameter must be greater than or equal to the value of the end parameter in order to execute the body of the loop. If the Step parameter is not set, then the default value of the increment parameter is 1.

VBA executes the For loop in the following sequence:

1. Sets the loop variable counter to start.

2. Compares the value of the loop variable counter and the value of the end parameter. If the counter variable is greater, VBA terminates the loop. (If the value of the increment parameter is negative, then VBA terminates the loop if the value of the loop variable counter is less than the value of the end parameter.)

3. Executes the statements of the loop body statements.

4. Increases the value of the loop variable counter by 1, or by the value of the increment parameter, if one is given.

5. Repeat steps 2 to 4.

Consider an example: Calculate the value of the function f(t)

given a, b, n, if t changes from a to b in increments of Dt=(b-a)/(n-1).

Sub example3() Dim f() As Single Dim a As Single, b As Single, t As Single, dt As Single Dim i As Integer, n As Integer Call read("a1", a) : Call read("b1" , b) : Call read("c1", n) ReDim f(1 To n - 1) dt = (b - a) / (n - 1) : t = a Call out("a2", "i") : Call out("b2", "t") : Call out("c2", "f(t)") For i = 1 To n - 1 t = t + dt If t<= -1 Then f(i) = -1 ElseIf t >1 Then f(i) = 1 Else f(i) = t End If Call out("a" & (2 + i), i) : Call out("b" & (2 + i), t) : Call out("c" & (2 + i), f(i)) Next i End Sub

The For Each construct. . . Next

For Each loop. . . Next is like a For loop. . . Next, but it repeats a group of statements for each element from a set of objects or from an array, instead of repeating the statements a given number of times. It is especially useful when you don't know how many elements are in the set.

Syntax of the For Each loop construct. . . Next is:

For Each element In group statements Next element

Be aware of the following restrictions when using a For Each loop. . . Next:

For sets, the element parameter can only be a variable of type variant, a general variable of type object, or an object listed in the Object Browser

For arrays, the element parameter can only be a variable of type Variant

You cannot use a For Each loop. . . Next with an array of user-defined type because a variable of type variant cannot contain a value of user-defined type

Do...Loop design

The Do loop is used to execute a block of statements an unlimited number of times. There are several variations of the Do construct. . . Loop, but each of them evaluates a conditional expression to determine when to exit the loop. As in the case of the If construct. . . Then the condition must be a value or an expression that evaluates to False (zero) or True (non-zero).

In the following construction, Do . . . Loop statements are executed as long as the value of the condition is True (True):

Do While Condition Loop Statements

When executing this loop, VBA first checks the condition. If the condition is False, it skips all loop statements. If it is True, VBA executes the loop statements, returns to the Do While statement again, and tests the condition again.

Therefore, the loop represented by this construct can be executed any number of times as long as the condition value is not zero or True. Note that the statements of the loop body are never executed if the first time the condition is checked, it turns out to be false (False).

Consider an example: Calculate the sum of a series

with a given accuracy.

Sub example4() Dim e As Single, x As Single, s As Single Dim m As Single, p As Single, i As Single Call read("a1", x) : Call read("b1", e) s = 0 : i = 1: m = 1: p = -1 Call out("a2", "i") : Call out("b2", "m") : Call out("c2", "s") Do While Abs(m) >= e p = -p * x m = p / i s = s + m Call out("a" & (2 + i), i) : Call out("b" & (2 + i), Abs (m)) : Call out("c" & (2 + i), s) i = i + 1 Loop End Sub

Another variation of the Do construct. . . Loop first executes the statements of the body of the loop, and then checks the condition after each execution. This variation ensures that the statements in the loop body are executed at least once:

Do statements Loop While condition

The other two varieties of the loop construct are similar to the previous ones, except that the loop is executed while the condition is false (False):

The loop is not executed at all or is executed many times:

Do until condition

Loop statements

The loop is executed at least once:

operators

Loop Until condition

7.2 Nested loops.

You can put control structures inside other control structures (for example, an If . . . Then block inside a For . . . Next loop). A control structure placed inside another control structure is said to be nested.

The depth of nesting of control structures in VBA is not limited. To improve the readability of the code, it is common practice to shift the body of a decision construct or loop in the program when nested control structures are used.

When nesting one or more other loops in a loop, one speaks of nested loops, which distinguish between outer (enclosing) and inner (nested) loops.

Consider an example of summing the elements Aij of the matrix A(n,m) row by row.

Sub example5() Dim a() As Single, s() As Single Dim n As Integer, m As Integer Dim i As Integer, j As Integer Call read("a1", n): Call read("b1", m ) ReDim a(1 To n, 1 To m), s(1 To n) "Read matrix For i = 1 To n For j = 1 To m Call readcell(i + 1, j, a(i, j)) Next j Next i "Calculation For i = 1 To n s(i) = 0 For j = 1 To m s(i) = s(i) + a(i, j) Next j Call outcell(i + 1, m + 1 , s(i)) Next i End Sub

Note that the first Next closes the inner For loop, and the last Next closes the outer For loop. Similarly, for nested If statements, End If statements are automatically applied to close the nearest If statement. Nested structures Do . . . Loops work in a similar way: the farthest Loop statement corresponds to the farthest Do statement.

When input/output of elements of a two-dimensional array on a Microsoft Excel worksheet, it is convenient to use custom input/output procedures:

Sub readcell(i As Integer, j As Integer, val As Variant) val = Leaf1.Cells(i, j).Value End Sub Sub outcell(i As Integer, j As Integer, val As Variant) Leaf1.Cells(i, j).Value = val End Sub

where I is the row number, j is the worksheet column number.

Leaving control structures

The Exit statement allows you to exit directly from a For loop, a Do loop, a Sub procedure, or a Function procedure. The syntax of the Exit statement is simple:

For counter = start To end [statement block] [statement block] Next Do [(While | Until) condition] [statement block] [statement block] Loop

Exit For inside a For loop and Exit Do inside a Do loop can appear any number of times.

The Exit Do statement works with all variations of the Do loop syntax.

The Exit For and Exit Do statements are used when it is necessary to end the loop immediately, without continuing further iterations or without waiting for the execution of a block of statements in the loop body.

When you use the Exit statement to exit a loop, the values ​​of the loop variable depend on how the loop terminates:

When the loop terminates normally, the value of the loop variable is one more than the upper bound on the number of loops

When the loop terminates prematurely, the loop variable retains its value, which it received, taking into account the usual rules

When the loop terminates at the end of the set, the loop variable is Nothing if it is an object variable, or Empty if it is a Variant

Last update: 10/30/2015

Another type of control structures are loops. VB.NET uses several kinds of loops.

For...Next Loop

This loop is executed a certain number of times, and this number is set by the counter:

For i As Integer = 1 To 9 Console.WriteLine("The square of (0) is (1)", i, i * i) Next

Here the variable i plays the role of a counter. After the word To we put the maximum value of the counter. With each cycle, the counter value is incremented by one. And this value is compared with the value after To. If these two values ​​are equal, then the loop terminates.

When working with loops, we can increase the value of the counter with each pass, not only by one, but by any number in general. To do this, you must either use the keyword step and after it, specify the step of the loop by which the counter value will increase, or you can increase the counter directly in the loop:

For i As Integer = 1 To -9 Step -1 For j As Integer = 1 To 9 Console.WriteLine("The product of i and j is (0)", i * j) j += 1 Next Next

Note that a negative value is chosen as the step in the first loop, and the value of the counter decreases by one with each pass. In the inner loop, the counter j is incremented by 2 on each iteration, because it increments by one by default, and we also explicitly increment it in the loop by one. As a result, the inner loop works five times, and the outer one nine, that is, in fact, 45 cycles are obtained.

For Each...Next Loop

The For Each loop iterates over the elements in a particular group, such as an array or a collection. Suppose we have some array of type Integer and we need to initialize this array with random values ​​and then display all its elements on the screen:

"Create an array of five numbers Dim nums(4) As Integer Dim r As New Random() "initialize the array For i As Integer = 0 To nums.Length - 1 nums(i) = r.Next(100) Next "Display elements array For Each i As Integer In nums Console.Write("(0) ", i) Next

In the For Each statement, we first specify a variable that will take the values ​​of the array elements. And after the keyword In Specify the group in which you want to sort through all the elements.

while loop

In a While loop, it executes as long as a certain condition, specified after the While word, is met:

Dim j As Integer = 10 While j > 0 Console.WriteLine(j) j -= 1 End While

Do loop

A Do loop, like a While loop, executes as long as a certain condition is met. However, it has different forms. So, in the following example, the condition is checked first, and then the block of code defined in the loop is executed:

Dim j As Integer = 10 Do While j > 0 Console.WriteLine(j) j -= 1 Loop

In this case, the loop is executed while the value of j is greater than zero. But there is another entry where the word While is used instead of the word Until, and the loop is executed until a certain condition is met, that is, until the value of j becomes less than zero:

Dim j As Integer = 10 Do Until j< 0 Console.WriteLine(j) j -= 1 Loop

If initially the condition specified in the loop is false, then the loop will not work. But we can define a check at the end of the loop, and thus our loop will run at least once:

Dim j As Integer = -1 Do Console.WriteLine(j) j -= 1 Loop Until j< 0 "либо Do Console.WriteLine(j) j -= 1 Loop While j > 0

Continue and Exit Statements

Often there is a need not to wait for the end of the cycle, but to immediately exit the cycle, if a certain condition is met. To do this, use the operator exit, followed by the type of loop to exit from, for example, Exit Do (Exit While) :

Dim r As New Random() Dim num As Integer = r.Next(100) For i As Integer = 0 To 100 num -= 1 If num< 50 Then Exit For Next Console.WriteLine(num)

There is another task - to exit not from the loop, but from the current pass or iteration and go to the next one. To do this, use the Continue statement, after which they indicate the type of loop from which the exit is made, for example, Continue While:

Dim r As New Random() Dim num As Integer = r.Next(100) For i As Integer = 0 To 10 num -= 7 If num< 50 AndAlso num >25 Then Continue For End If Console.WriteLine(num) Next

In this case, in each pass of the loop, we subtract the number 7 from num and then see if the number num belongs to the interval from 25 to 50. And if it does, we go to a new iteration of the loop, and if not, we display it on the screen.

Laboratory work on the basics of programming

2.1. Tabulation of functions represented analytically
and converging nearby

Objective

· Consolidation of theoretical knowledge on the basics of the organization of branching and cyclic structures.

· Acquisition of practical programming skills using branching and cyclic structures in the Visual Basic system.

There are three kinds of loop statements in VB:

counting cycle: For…To…Next

Loops with preconditions: Do While...Loop, Do Until...Loop, While…WEnd

Loops with postconditions: Do...Loop While, Do...Loop Until.

Counting cycle - allows you to cycle through a set of statements a specified number of times. Its syntax is the following:

For counter = Start To the end

[operators]

[operators]

Next[ counter]

Parameter counter is a numeric variable (integer, real, or Date, Variant, Currency) that is automatically incremented after each iteration. Initial value counter equal to the parameter Start, and the final parameter is the end. If not specified, then the step is considered equal to 1, the step value can be changed. It can be a positive or negative number.

There are four syntactic constructs for the Do….Loop:

The statements between the Do...Loop keywords are executed a specified number of times depending on the condition. For example, in the following program fragment, when C = 100, the condition will be met and the loop will enter. Inside the loop, the procedure is called and the value of C decreases by 1. Then the condition is checked again (C > 0) and the loop statements are executed again (they will be executed 100 times in total), up to C = 0. When the condition C > 0 becomes false and the loop stops.

Do While C > 0

The same program fragment executed using a precondition loop in syntax 2:

In this case, the loop is executed while the condition is False, in contrast to the previous case, that is, it continues before fulfillment of the condition C = 0.

Loop statements in syntax 3 and 4 are very similar to the first two, except that the condition not is evaluated until the loop has executed at least once.

In the syntaxes of these loops, you can use the operators of unconditional exit from the loop Exit For and Exit Do, which allow you to transfer control to the operator behind the loop. For example, in the following program fragment, if the initial value of C is >50, then the loop will immediately stop.



Do Until C<= 0

MsgBox "Start. value is greater than allowed”, “Input error”

The While...Wend loop was used in early versions of Visual Basic. Its syntax is the following:

While<условие>

<Операторы>

Unlike the Do..Loop, the While ..Wend loop does not have a second option, in which the condition test is performed at the end of the loop. In addition, it does not have a loop exit statement like Exit Do.

VBA. Organization of cycles.

Loop statements are used to repeat the execution of an action or group of actions a given number of times. The number of repetitions (loop iterations) can be predefined or calculated.

VBA supports two kinds of looping constructs:

  1. Loops with a fixed number of repetitions ( cycles with counter).
  2. Loops with an indefinite number of repetitions ( conditional loops).

For all types of cycles, the concept is used loop body A that defines a block of statements enclosed between the start and end statements of the loop. Each repetition of the statements in the loop body is called iteration .

Fixed Cycles

VBA provides two control structures for organizing a fixed loop: For ... Next (a loop with a counter) and For Each ... Next (a loop with an enumeration).

For…Next statement it is a typical loop with a counter that performs a given number of iterations. The syntax of the For … Next statement is:

For<счетчик> = <начЗначение>That<конЗначение>

<блок операторов>

Next[<счетчик>]

An example of using the For … Next statement.

Listing 1. For … Next statement

‘ OBJECTIVE: Write a program that receives two numbers from the user.

‘ Adds all the numbers in the range given by those two numbers, and then

‘ Displays the resulting sum.

Sub sample7()

Dim i As Integer ‘loop counter

Dim sStart ‘start counter value

Dim sEnd ' end value of the counter

Dim sSum As Long ‘resulting sum

sStart = InputBox("Enter the first number:")

sEnd = InputBox("Enter second number:")

sSum = 0

For i = CInt(sStart) To CInt(sEnd)

sSum = sSum + i

Next i

MsgBox “The sum of numbers from ” & sStart & ” to ” & sEnd & ” is: ” & sSum

end sub

For Each … Next Loop Statementbelongs to the category of object type operators, i.e. applies primarily to collections objects as well as arrays . The body of the loop is executed a fixed number of times, corresponding to the number of elements in the array or collection. The format of the For Each … Next statement is:

For Each<элемент>In<группа> <блок операторов>Next[<элемент>]

Conditional loops (indefinite loops)

Conditional loops are used when repeated actions need to be performed only under certain conditions. The number of iterations is not defined and in the general case can be equal to zero (in particular, for loops with a precondition). VBA offers developers several control structures for organizing conditional loops:

  • Four types of loops Do..Loop, which differ in the type of condition being checked and the time of execution of this check.
  • An uninterrupted While … Wend loop.

Do While... Loop - Typical loop with precondition. The condition is checked before the body of the loop is executed. The cycle continues its work until it<условие>is executed (i.e. is True). Since the check is performed at the beginning, the body of the loop may never be executed. Format of the Do While … Loop:

Do While<условие>

<блок операторов>

loop

Listing 2. Do While … Loop

‘ OBJECTIVE: Write a program that accepts user input

‘ an arbitrary sequence of numbers. Entry must be terminated

‘ only after the sum of the entered odd numbers exceeds 100.

Sub sample8()

Dim OddSum As Integer

Dim OddStr As String 'string with odd numbers

Dim Num 'to accept input numbers

OddStr = "" 'initialization of the output string

OddSum = 0 ‘initialization of OddSum sum

Do While OddSum< 100 ‘начало цикла

Num = InputBox("Enter number: ")

If (Num Mod 2)<>0 Then ‘even parity

OddSum = OddSum + Num ‘accumulation of the sum of odd numbers

OddStr = OddStr & Num & ” ”

End if

loop

‘output a string with odd numbers

MsgBox prompt:=”Odd numbers: ” & OddStr

end sub

Do...Loop While Statementintended for organizationloop with postcondition. The condition is checked after the loop body is executed at least once. The cycle continues until<условие>remains true. Do...Loop While format:

Do<блок операторов>loop while<условие>

Listing 3. Loop with postcondition

‘ OBJECTIVE: Make a program for the game “Guess the Number”. The program should random

‘ in a way to generate a number in the range from 1 to 1000, the user must

‘Guess this number. The program displays a hint for each number entered.

' "more or less".

Sub sample8()

Randomize Timer ‘ initialization of the random number generator

Dim msg As String ‘ message string

Dim SecretNumber As Long, UserNumber As Variant

Begin: SecretNumber = Round(Rnd * 1000) ‘ computer generated number

UserNumber = Empty ‘ the number entered by the user

Do' gameplay

Select Case True

Case IsEmpty(UserNumber): msg = "Please enter a number"

Case UserNumber > SecretNumber: msg = “Too many!”

Case UserNumber< SecretNumber: msg = “Слишком мало!”

End Select

UserNumber = InputBox(prompt:=msg, Title:=”Guess the Number”)

Loop While UserNumber<>secret number

' examination

If MsgBox("Do you want to play again?", vbYesNo + vbQuestion, "You guessed right!") = vbYes Then

Go To Begin

End if

end sub

Do Until … Loop and Do … Loop Until Loops are inversions of previously considered conditional loops. In general, they work similarly, except that the loop body is executed under a false condition (i.e.<условие>=False). The format of the Do Until ... Loop is:

Do Until<условие> <блок операторов>loop

The format of the Do … Loop Until loop is:

<блок операторов>

Loop Until<условие>

Practical task:Rewrite the programs in Listings 10 and 11 using inverted loop statements.

While Loop ... Wend also applies to conditional loops. This statement fully corresponds to the Do While … Loop structure. The format of the While … Wend loop is:

While<условие>

<блок операторов>

Wend

A distinctive feature of this statement is the impossibility of forced termination (interruption) of the loop body (the Exit Do statement does not work in the While ... Wend loop).

Loop interruption

The Exit statement is used to end the iteration and exit the loop. This statement is applicable in any cyclic structure, except While ... Wend. The general syntax for using Exit to break a loop is:

<начало_цикла>

[<блок операторов1>]

Exit (For | Do)

[<блок операторов2>]

<конец_цикла>

When the Exit statement is executed, the loop is interrupted and control is transferred to the statement following the statement<конец_цикла>. The loop body can contain multiple Exit statements.

Listing 4. Forced loop exit

Sub sample9()

For i = 1 To 10000000

If i = 10 Then Exit For ' exit the loop when the counter reaches 10

Next

Operator syntax:

ForCounter= Start ToEnd[stepStep]

Statement_Block

NextCounter

It is marked here:

For for (mandatory VB keyword);

To before (mandatory VB keyword);

Statement_Block one or more operators called cycle body;

Counter - an integer variable that counts the number of cycles to be executed;

Beginning, End - initial and final values ​​of the counter;

step step (keyword VB);

Step - counter change step; may be negative; the parameter is optional, because if the step is 1, you can Step Step lower;

Next - next (mandatory VB keyword, end of loop statement record).

Counter value (Start, End) can be numerical constants or variables of integer or real type, can be negative or positive numbers. For the body of the loop to be executed at least once, it must be Start ≤ End, if Step> 0, and Start ≥ End, if Step< 0. As soon as it turns out that Counter>End ( if Start< Конец), loop execution ends. If a Start =End, the loop will be executed once;

Example 9.1 .Function evaluationY = 2 – 1.5 sinxwhen changing X in increments of 0.2 in the range .

A fragment of the program for calculating Y and outputting the argument X and function Y:

For X = 0 To 2.4 Step 0.2

Y = 2 - 1.5*Sin(X)

To understand how this loop works, here is a program for a similar loop created using operatorgoto, labels, operatorIfThen.

M1:X=X+0.2

If X<= 2.4 Then

Y = 2 - 1.5*Sin(X)

Let's analyze how this program works. The first calculation Y is non-standard, as it were, falls out of the loop. The loop starts after the first transfer of control GoToM1 to label M1. In the line labeled M1, the argument X is increased by a step of 0.2 and immediately a check is made whether the new value of X does not exceed the final value 2.4. If it does not exceed, then the calculation of Y is repeated with this new X. Then the operator GoToM1 is executed again - transferring control to the line with the label M1. These repetitions (cycles) of calculating Y will end as soon as X exceeds 2.4.

Now the If program is comparable to the For…Next loop.

For X = 0 To 2.4 Step 0.2

replaces two lines

M1:X=X+0.2

If X<= 2.4 Then

It is the last two lines of code that are executed in the For loop, but we do not see this. We encoded them with the string cFor... The code line GoTo M1 is encoded with the word Next X (literally: next X). This results in a compact design.

When using the For…Next loop, you need to learn how to use the loop counter when solving various problems. To figure out how you can use the counter to solve the problem, you need to to analyze the problem statement, to find patterns of change in some parameters of the problem.

Example 9.2 . Determining the sum of elements of a series: .

Program fragment:

S = 0 ‘S is the sum of the series

For i = 1 To 16 ‘ counter i is the denominator of the fraction

S = S + 1/i ‘ accumulation sum

Print "S="; S ‘ the output of the sum S to the form

For each value of the counter i, the expression 1/i sequentially forms the elements of the series, starting from 1.

Example 9.3 . Calculating the sum of a series of elements
.

Program fragment:

S = 0 ‘S is the sum of the series

For i = 1 To 18 ‘ counter i - numerator

S = S + i/(i + 1) ‘ the denominator is greater than the numerator by 1

Print "S="; S ‘ the output of the sum S to the form

Example 9.4 . Sum calculation: 5 + 8 + 11 + ... + 32 + 35

Program fragment:

S = 0 ‘S is the sum of the series

For i = 5 To 35 Step 3 ‘ get arithmetic _

progression with denominator 3

Print "S="; S

Example 9.5. Calculating the sum for a given x:

Analysis of the problem shows that the degree at X changes from 1 to 10. In this case, the numerator in the coefficient at X is greater than the degree by 1, and the denominator is by 2. The value of the degree will be formed using the counter i. Then you can write the following program (fragment):

S = 1 ‘S is the sum of the series

For i = 1 To 10 ‘ as counter i, the degree changes at X

S = S + (-1)^i*(i + 1)*x^i / (i + 2)

Print "S="; S

CyclesForNextused ininput, output andarray processing .

Example 9.6. Input and output of values ​​of array elements B(N).

Program fragment:

‘ Omit the assignment of the value N to the variable, _

entered on the form in the text field txtN:

B(i) = InputBox("Enter element B(" & i & ")", _

"Input array B(" & N & “)”))

print " "; B(i);

Function InputBox() displays a dialog box with a close button, a given message, an input field, buttons OK,Cancel, header (or without it). If the number 12 is entered - the size of the array N, then in our example, at the first appearance, this window will look like:

As you can see, the message Enter element B(1) prompts you to enter the value of the 1st element in the text box. This window will appear 12 times since the array contains 12 elements. This follows from the form header. The index of element B(i) in the prompt will vary from 1 to 12.

If it is required to display only the values ​​of the elements of the B(N) array on the form, then the loop body will consist of one statement:

Viewing the elements of an array to perform some action on them also occurs using the For…Next loop operator.

Let's bring examples of processing one-dimensional arrays.

Example 9.7 . Determination of the maximum element in the array B(M).

Excluding input of initial data and output of results, we briefly describe the algorithm:

    Let's declare the variable Bmax, in which we will enter the value of the first element of the array, and the variable Imax, to which we will assign 1 - the index of the first element of the array.

    In the loop, using the For…Next operator, we look through all the elements of the array, starting from the 2nd. Using the If…Then operator, we compare their values ​​with the value stored in the Bmax variable.

    If it turns out that the value of an array element is greater than Bmax, then Bmax is assigned the value of this element, and the value of Imax is the index of this array element.

After the end of the loop, the variable Bmax will contain the value of the maximum element, and Imax will contain its index (number).

The program of this part of the algorithm.

Bmax = B(1): Imax = 1

If B(i) > Bmax Then Bmax = B(i): Imax = i

Example 9.8. Determining the sum, product, and number of positive array elementsD(M).

Variables: S, P, K are the sum, product and number of positive elements, respectively.

Algorithm this definition:

    We assign zero to the variable S and K, assign 1 to the variable P. As a rule, the variables where the sum is accumulated, here it is S and k, are reset to zero before the cycle, and 1 is assigned to the variables in which the product is calculated.

    Using the For…Next loop, we go through all the elements of the array and check if they are positive (D(i) > 0).

    If it turns out that the element is positive, then we add its value to the value of the sum S and store the new sum in the same variable. We multiply the variable P by the positive value of the element and store it in the variable P as well. And we add 1 to the variable K and store the new value in the same variable

Program this part of the algorithm looks like:

S=0: P=1: K=0

If D(i) > 0 Then

S = S + D(i) ‘ this is how the accumulation of the sum _

positive values ​​of array elements D(i)

P = P*D(i) ‘ definition of the product of positive

‘ array elements

K = K + 1 ‘ this operator is called COUNTER, here it is

‘ determines the number of positive array elements

Example 9.9. Determination of the sum, product, number and average of odd array elementsD(M).

We present a fragment of the program of such a definition.

S=0: P=1: K=0

If D(i) Mod 2<>0 Then

Ssr = S/k ‘ calculation of the mean of odd elements

Compare this program fragment with the program in Example 9.8. This program almost completely repeats the previous one. Only the condition in the If statement has been changed. Condition D(i) Mod 2<>0 means that we are looking for elements of array D(i) that are not even divisible by 2, i.e. odd elements. If we check the condition D(i) Mod 2 = 0, then we will select even elements of the array.

As you know, division Mod gives as a result the remainder of the division in integers. For example, after executing the operator d= 34Mod4, the variable d will be equal to 2. Therefore, to select array elements that are multiples of 4, you need to check the condition D(i) Mod 4 = 0. The condition will be similar if we look for elements that are multiples of other numbers. Instead of 4, these other numbers will be written.

Example 9.10. Writing array elementsR(N) divisible by 5 into another array and displaying the new array on the form.

The other array will be denoted, for example, by R5(N). The size of this new array should be assumed to be the same as the original one, since in the limit case all elements can be multiples of 5.

Task algorithm:

    We reset the counter k. Using the For…Next loop operator, we look through all the elements of the R(N) array.

    We check each element for a multiplicity of 5 using the If…Then operator and division of the array element by Mod.

    If the element is a multiple of 5, then using a counter like k=k+ 1, we form the indices of the array R5(N), starting from 1, and write it to this other array –R5(N).

    If k is non-zero, output the arrayR5() to the form.

    If k is equal to zero, we output: "There are no elements that are multiples of 5".

Program fragment:

If R(i) Mod 5 Then k = k + 1: R5(k) = R(i)

If k<>0 Then

Print “No elements divisible by 5”

Loops can be nested within other loops.

Let's demonstrate the work nested loops . Below, the program organizes the output of the values ​​of the cycle counters i, j and k. From the output of i,j,k it becomes clear how the nested loops are executed.

Private Sub frmCycle_DblClick()

ScaleMode = 4 'units - symbols

For i = 1 To 3 ‘outer loop

Print "i = "; i;

For j = 1 To 4 ‘1st nested loop

CurrentX = TextWidth("i = 1") + 5

Print "j="; j;

CurrentX = TextWidth("i = 1 j = 1") + 7

For k = 1 To 5 ‘2nd nested loop

The displayed form (Fig. 1) shows the results of displaying the counters of all three loops: the outer loop - counter i, the first nested loop - counterj, and the second, innermost loop - counterk. As we see, the "slowest" counter of the outer loop(poi), and the “fastest” is the counter of the innermost loop (according tok).

The program is executed after double-clicking the frmCicli form with the left mouse button.

CurrentX, CurrentY - form properties that specify the X, Y coordinates of the start point for information output by the Print method (see the location of the X and Y axes on the form in Fig. 1).

TextWidth() is a function that returns the width of the text given in the function as an argument in double quotes.

Nested loops are used when processing two-dimensional arrays (matrices). But in some tasks, excluding the input and output of elements of a two-dimensional array, you can limit yourself to one cycle. Consider some examples of matrix programming.

Example 9.11. Input and output of a matrix (two-dimensional array) of integersintA(N).

You can enter a matrix by rows and by columns . It's easier - line by line, if the output of the array elements to the form will be programmed immediately after their input.

Matrix input and outputline by line - fragment 1.

Dim M As Integer, N As Integer, i As Integer, j As Integer

Dim intA() As Integer ‘ declare a dynamic array

M = Val(txtN.Text) ‘ M is the number of lines

N = Val(txtN.Text) ‘ N is the number of columns

ReDim intA(M, N) As Integer ‘ redefine the array

For i = 1 To M ‘ i will keep its value until completely

‘nested loop on j will not be executed

print " "; intA(i, j); ‘ line by line output

Print ‘ jump to the beginning of a new line

To enter a matrix by columns, it is necessary to make the outer loop on j (sets the column numbers), and the inner loop on i (sets the row numbers).

Matrix input and outputby columns fragment 2.

PrY = 2500: CurrentY = PrY ‘ PrY sets the Y coordinate of the start

‘ output the first element of each column on the form

For j = 1 To N ‘ j will keep its value until completely

‘nested loop on i will not be executed

intA (i, j) = InputBox("Enter element intA(" & i & “,” & j & ")", _

"Matrix input intA(" & M & “,” & N & ")")

Print Tab(6 * j); intA(i, j) ‘ display by columns

CurrentY = PrY ' to display the first element

' next column

This second fragment of the program does not repeat the first 5 lines from the first fragment. The Tab(6 * j) function sets the start of output on a line (in characters) starting from the left edge of the form. The PrY coordinate here is 2500 twips, but you can choose another value.

Example 9.12 . Ordering array element valuesV(N) Ascending.

There are several algorithms for ordering arrays. Here is one of them: using nested loopsForNextselect elements from the first to the penultimate, and compare each of them with subsequent elements; if it turns out that the next element is less than the selected one, swap them.

A fragment of a program that implements this algorithm:

For i = 1 To N - 1

For j = i + 1 To N

If V(j)< V(i) Then P = V(i): V(i) = V(j): V(j) = P

Let's explain this fragment of the program.

With the help of an outer loop with a counter i, we select the element V (i) for comparison with subsequent elements. The inner loop with counter j selects subsequent elements of V(j) for comparison. The initial value of j is i + 1. This is the first element of the following.

To exchange the values ​​of the elements V(i) and V(j), we introduce some variable P, into which we temporarily “hide” the value of one of the array elements (in the program, this is V(i)). Then the element V(i) is assigned the value of the element V(j), and the element V(j) is assigned the value V(i), which is stored in the variable P. If we “hide” the value of V(j) in P, then the value exchange code will be as follows: P = V(j): V(j) = V(i): V(i) = P. The result will not change.

To sort array in descending order, it is enough to write the condition for verification in the form V(j) > V(i), i.e. change the inequality sign to another one.

If the array is not numeric, but string, and the array elements are filled with last names, then using the program in Example 9.12, you can sort the list of last names alphabetically. The fact is that for the letters of the alphabet used in the computer, the inequalities are true: A< Б < В < Г….< Я и т. д., поскольку числовые коды букв алфавита последовательно увеличиваются, начиная с А и до конца алфавита. Это же справедливо и для букв английского алфавита.

Example 9.13 . Calculating the sum of positive elements for odd columns of a matrixF(M, N) and displaying the sums on the form.

Program algorithm:

    Using an outer loop with a step of 2, we form the index of the odd columns of the matrix, starting from the first column.

    We reset the sum S, in which the sum of positive elements will be accumulated.

    In the inner loop, we check the sign of the array element.

    If the array element is positive (> 0), calculate the sum S.

    After the end of the inner loop, output the sum S to the form.

Fragment programs:

For j = 1 To N Step 2

If F(i, j) > 0 Then S = S + F(i, j)

Print “Column sum”; j; ":"; S ‘ j is the column number!

Nested loops allow you to organize enumeration of options and solve problems that cannot be solved analytically. As a result of enumeration, solutions are obtained, among which one or more are selected that meet the condition of the problem.

Example 9.14. There is 1801 rubles. How many can you buy chocolates for 31 rubles. and a roll for 18 rubles in order to fully spend all the money.

Program:

Amount = 1801

AllChocolates = Sum \ 31: All Buns = Sum \ 18

For i = 1 To AllChocolates

For j = 1 To AllBulki

Price = i * 31 + j * 18 ‘total purchase price

If Price = 1801 Then

Print "Chocolate: "; i; Tab(19); "Bulok: "; j

Let us explain the program in which we use variables named in Russian.

First, we determine what is the maximum number of only chocolates or only rolls that can be bought for the entire amount. The obtained values ​​of VseChocolate and VseBulki are used to limit the number of searches by the number of chocolates and rolls. For each value of the number of chocolates (i) and the number of rolls (j), we determine the total Price for their purchase. If the calculated Price is 1801, then the selected option is one of the solutions to the problem.

The Tab() function specifies at what position from the edge of the form the information following this function will be displayed. If Tab(19), then from the 19th position.

The program displays 3 possible purchase options:

Chocolates 7, rolls 88

Chocolates 25, rolls 57

Chocolates 43, rolls 26

If you want to give an unambiguous answer, you must formulate an additional condition. For example, “less buns were bought than chocolates.” Then the only solution would be the 3rd option.

There are many mathematical problems that are simply solved by iterating through nested loop programming.