What is a loop and how we can use them?


1.   What are loops and how we can use them?

In general a loop is a sequence of statements which is specified once but which may be carried out several times in succession. The function of the loop is to repeat the calculation a given number of times until it reaches a certain value. The code inside the loop is obeyed a specified number of times, or once for each of a collection of items, or until some condition is met, or indefinitely. We can divide loops into:
1)      Count-controlled loops,
2)      Condition – controlled loops,
3)      Collection  - controlled loops,
4)      General iteration,
5)      Infinite loops,
6)      Continuation with the next iteration,
7)      Redo the current interation and
8)      Restart loop

1.1.Count- controlled loops

Most programming languages have constructions for repeating a loop a certain number of times. Note that if N is less than 1 in these examples then the language may specify that the body is skipped completely, or that the body is executed just once with N = 1. In most cases counting can go downwards instead of upwards and step sizes other than 1 can be used.
   FOR I = 1 TO N            for I := 1 to N do begin
       xxx                       xxx
   NEXT I                    end;

   DO I = 1,N                for ( I=1; I<=N; ++I ) {
       xxx                       xxx
   END DO                    }

In many programming languages, only integers can be reliably used in a count-controlled loop. Floating-point numbers are represented imprecisely due to hardware constraints, so a loop such as for X := 0.1 step 0.1 to 1.0 do might be repeated 9 or 10 times, depending on rounding errors and/or the hardware and/or the compiler version. Furthermore, if the increment of X occurs by repeated addition, accumulated rounding errors may mean that the value of X in each iteration can differ quite significantly from the expected sequence 0.1, 0.2, 0.3,…, 1.0.

1.2.Condition controlled loops

Most programming languages have constructions for repeating a loop until some condition changes. Note that some variations place the test at the start of the loop, while others have the test at the end of the loop. In the former case the body may be skipped completely, while in the latter case the body is always executed at least once.
   DO WHILE (test)           repeat
       xxx                       xxx
   LOOP                      until test;

   while (test) {            do
       xxx                       xxx
   }                         while (test);

A control break is a value change detection method used within ordinary loops to trigger processing for groups of values. A key changeable value or values are monitored within the loop and a change diverts program flow to the handling of the group event associated with the changeable value.
   DO UNTIL (End-of-File)
      IF new-zipcode <> current-zipcode
         display_tally(current-zipcode, zipcount)
         current-zipcode = new-zipcode
         zipcount = 0
      ENDIF
      zipcount++
   LOOP

1.3.Collection – Controlled loops

Several programming languages (e.g. Ada, D, Smalltalk, PHP, Perl, Object Pascal, Java, C#, Mythryl, Visual Basic, Ruby, Python, JavaScript, Fortran 95 and later) have special constructs which allow implicitly looping through all elements of an array, or all members of a set or collection.
   someCollection do: [:eachElement |xxx].
   for Item in Collection do begin xxx end;
   foreach (item; myCollection) { xxx }
   foreach someArray { xxx }
   foreach ($someArray as $k => $v) { xxx }
   Collection<String> coll; for (String s : coll) {}
   foreach (string s in myStringCollection) { xxx }
   $someCollection | ForEach-Object { $_ }
   forall ( index = first:last:step... )

1.4. General iteration

General iteration constructs such as C's for statement and Common Lisp's do form can be used to express any of the above sorts of loops, as well as others—such as looping over a number of collections in parallel. Where a more specific looping construct can be used, it is usually preferred over the general iteration construct, since it often makes the purpose of the expression more clear.

1.5. Infinite loops

Infinite loops are used to assure a program segment loops forever or until an exceptional condition arises, such as an error. For instance, an event-driven program (such as a server) should loop forever handling events as they occur; only stopping when the process is terminated by an operator. Often, an infinite loop is unintentionally created by a programming error in a condition-controlled loop, wherein the loop condition uses variables that never change within the loop.

1.6.Continuation with next iteration

Sometimes within the body of a loop there is a desire to skip the remainder of the loop body and continue with the next iteration of the loop. Some languages provide a statement such as continue (most languages), skip, or next (Perl and Ruby), which will do this. The effect is to prematurely terminate the innermost loop body and then resume as normal with the next iteration. If the iteration is the last one in the loop, the effect is to terminate the entire loop early.

1.7.Redo current iteration

Some languages, like Perl and Ruby, have a redo statement that restarts the current iteration from the beginning.

1.8.Restart the loop

Ruby has a retry statement that restarts the entire loop from the initial iteration.

1.9.Early exit from loops

When using a count-controlled loop to search through a table, it might be desirable to stop searching as soon as the required item is found. Some programming languages provide a statement such as break (most languages), exit, or last (Perl), whose effect is to terminate the current loop immediately and transfer control to the statement immediately following that loop. One can also return out of a subroutine executing the looped statements, breaking out of both the nested loop and the subroutine. Things can get a bit messy if searching a multi-dimensional table using nested loops (see #Proposed control structures below).
The following example is done in Ada which supports both early exit from loops and loops with test in the middle. Both features are very similar and comparing both code snippets will show the difference: early exit needs to be combined with an if statement while a condition in the middle is a self-contained construct.
with Ada.Text IO;
with Ada.Integer Text IO;

procedure Print_Squares is
    X : Integer;
begin
    Read_Data : loop
        Ada.Integer Text IO.Get(X);
    exit Read_Data when X = 0;
        Ada.Text IO.Put (X * X);
        Ada.Text IO.New_Line;
    end loop Read_Data;
end Print_Squares;
Python supports conditional execution of code depending on whether a loop was exited early (with a break statement) or not by using a else-clause with the loop. For example,
for n in set_of_numbers:
    if isprime(n):
        print "Set contains a prime number"
        break
else:
    print "Set did not contain any prime numbers"
Note that the else clause in the above example is attached to the for statement, and not the inner if statement. Both Python's for and while loops support such an else clause, which is executed only if early exit of the loop has not occurred.
XKF2YUZSQRF7
Share on Google Plus