Loops/For with a specified step: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added AutoHotkey.)
(Refined AHK.)
Line 55: Line 55:
=={{header|AutoHotkey}==
=={{header|AutoHotkey}==
<lang AutoHotkey>SetBatchLines, -1
<lang AutoHotkey>SetBatchLines, -1
iterations := 5
Loop, 50
step := 10
iterations *= step
Loop, % iterations
{
{
If Mod(A_Index, 10)
If Mod(A_Index, step)
Continue
Continue
MsgBox, % A_Index
MsgBox, % A_Index

Revision as of 22:04, 17 September 2009

Task
Loops/For with a specified step
You are encouraged to solve this task according to the task description, using any language you may know.

Demonstrate a for loop where the step value is greater than one.

Ada

The FOR loop construct in Ada does not give the programmer the ability to directly modify the loop control variable during the execution of the loop. Instead, Ada automatically takes care of the modification of the loop control variable by incrementing it or decrementing it to be the next value in a specified discrete sequence. For this reason, in a "real" program, an Ada programmer would use a WHILE loop, or more likely a general LOOP, construct to perform this particular task. For the sake of this task, however, the following code demonstrates a way the task could be performed, when the range of loop control values is sufficiently small, through the definition of an enumeration type.

In the declarative section: <lang ada>type Loop_Steps is (2, 4, 6, 8);</lang> In the body section: <lang ada>for Step in Loop_Steps loop

  put(Step, 0);
  put(", ");

end loop; put("who do we appreciate?");</lang> Another way to do this, which would be more practical for larger ranges, is to loop through all of the values in a range (even the ones we weren't interested in using) and use a conditional check to determine whether or not to use the current loop control variable at each iteration. This is rather inefficient, growing more so as the step values get larger, but it's still order of O(n). Again, this is purely academic, since an actual Ada programmer would rarely do something like this.

The following code prints multiples of three from 3 to 12: <lang ada>for Value in 3 .. 12 loop

  if Value mod 3 = 0 then
     put(Value, 0);
     put(", ")
  end if;

end loop; put("what's a word that rhymes with ""twelve""?");</lang>

ALGOL 68

The ALGOL 68 "universal" for/while loop: <lang algol68>[ for index ] [ from first ] [ by increment ] [ to last ] [ while condition ] do statements od</lang> The minimum form of a "loop clause" is thus: <lang algol68>do statements od # an infinite loop #</lang> The formal specification of ALGOL 68 states: <lang algol68>for i from u1 by u2 to u3 while condition do action od</lang> "is thus equivalent to the following void-closed-clause:" <lang algol68>begin int f:= u1, int b = u2, t = u3;

  step2:
    if (b > 0 ∧ f ≤ t) ∨ (b < 0 ∧ f ≥ t) ∨ b = 0
    then int i = f;
        if condition
        then action; f +:= b; go to step2
        fi
    fi

end</lang> There are several unusual aspects of the construct:

    • only the 'do ~ od' portion was compulsory, in which case the loop will iterate indefinitely.
    • thus the clause 'to 100 do ~ od', will iterate only 100 times.
    • the while "syntactic element" allowed a programmer to break from a for loop early. eg

<lang algol68>int sum sq:=0; for i while

 sum sq ≠ 70 × 70

do

 sum sq +:= i ↑ 2

od</lang> Subsequent "extensions" to the standard Algol68 allowed the to syntactic element to be replaced with upto and downto to achieve a small optimisation. The same compilers also incorporated:

  • until(C) - for late loop termination.
  • foreach(S) - for working on arrays in parallel.

{{header|AutoHotkey}

<lang AutoHotkey>SetBatchLines, -1 iterations := 5 step := 10 iterations *= step Loop,  % iterations {

  If Mod(A_Index, step)
     Continue
  MsgBox, % A_Index

} ExitApp</lang>

BASIC

Works with: QuickBasic version 4.5

<lang qbasic>for i = 2 to 8 step 2

  print i; ", ";

next i print "who do we appreciate?"</lang>

C

This prints all odd digits: <lang c> int i; for(i = 1; i < 10; i += 2)

 printf("%d\n", i);

</lang>

C++

This prints all odd digits: <lang cpp> for (int i = 1; i < 10; i += 2)

 std::cout << i << std::endl;

</lang>

Common Lisp

<lang lisp>(loop for i from 2 to 8 by 2 do

 (format t "~d, " i))

(format t "who do we appreciate?~%")</lang>

D

Print odd numbers up to 9. <lang d> for (int i = 1; i < 10; i += 2)

 std.stdio.writefln("%d\n",i);

</lang>

E

There is no step in the standard numeric range object (a..b and a..!b) in E, which is typically used for numeric iteration. An ordinary while loop can of course be used:

<lang e>var i := 2 while (i <= 8) {

   print(`$i, `)
   i += 2

} println("who do we appreciate?")</lang>

A programmer frequently in need of iteration with an arbitrary step should define an appropriate range object:

<lang e>def stepRange(low, high, step) {

   def range {
       to iterate(f) {
           var i := low
           while (i <= high) {
               f(null, i)
               i += step
           }
       }
   }
   return range

}

for i in stepRange(2, 9, 2) {

 print(`$i, `)

} println("who do we appreciate?")</lang>

The least efficient, but perhaps convenient, solution is to iterate over successive integers and discard undesired ones:

<lang e>for i ? (i %% 2 <=> 0) in 2..8 {

   print(`$i, `)

} println("who do we appreciate?")</lang>

FALSE

<lang false> 2[$9\>][$.", "2+]#"who do we appreciate!" </lang>

Forth

<lang forth>

test
 9 2 do
   i .
 2 +loop
 ." who do we appreciate?" cr ;

</lang>

Fortran

Works with: Fortran version 90 and later

<lang fortran> do i = 1,10,2

    print *, i
 end do</lang>

Haskell

<lang haskell>import Control.Monad (forM_) main = do forM_ [2,4..8] (\x -> putStr (show x ++ ", "))

         putStrLn "who do we appreciate?"</lang>

J

  <lang J>    ' who do we appreciate?' ,~ ":  2 * >: i.4

2 4 6 8 who do we appreciate? </lang>

Java

<lang java>for(int i = 2; i <= 8;i += 2){

  System.out.print(i + ", ");

} System.out.println("who do we appreciate?");</lang>

Lisaac

<lang Lisaac> 1.to 9 by 2 do { i : INTEGER;

 i.print;
 '\n'.print;

}; </lang>

<lang logo> for [i 2 8 2] [type :i type "|, |] print [who do we appreciate?] </lang>

Modula-3

<lang modula3>FOR i := 1 TO 100 BY 2 DO

 IO.Put(Fmt.Int(i) & " ");

END;</lang>

OCaml

<lang ocaml># let for_step a b step fn =

   let rec aux i =
     if i <= b then begin
       fn i;
       aux (i+step)
     end
   in
   aux a
 ;;

val for_step : int -> int -> int -> (int -> 'a) -> unit = <fun>

  1. for_step 0 8 2 (fun i -> Printf.printf " %d\n" i) ;;
0
2
4
6
8

- : unit = ()</lang>

Octave

<lang octave>for i = 1:2:10

 disp(i)

endfor</lang>

M4

<lang M4> define(`for',

  `ifelse($#,0,``$0,
  `ifelse(eval($2<=$3),1,
  `pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl

for(`x',`1',`5',`3',`x ') </lang>

Output:

1
4

Perl

<lang perl>for($i=2; $i <= 8; $i += 2) {

 print "$i, ";

} print "who do we appreciate?\n";</lang>

PHP

<lang php><?php foreach (range(2, 8, 2) as $i)

   echo "$i, ";

echo "who do we appreciate?\n"; ?></lang> Output

2, 4, 6, 8, who do we appreciate?

PowerShell

<lang powershell>for ($i = 0; $i -lt 10; $i += 2) {

   $i

}</lang>

Python

Works with: Python version 2.x

<lang python>for i in xrange(2, 9, 2):

   print "%d," % i,

print "who do we appreciate?"</lang>

Works with: Python version 3.x

<lang python>for i in range(2, 9, 2):

   print("%d, " % i, end="")

print("who do we appreciate?")</lang> Output

2, 4, 6, 8, who do we appreciate?

R

<lang R>for(a in seq(2,8,2)) {

 cat(a, ", ")

} cat("who do we appreciate?\n")</lang>

Ruby

<lang ruby>2.step(8,2) {|n| print "#{n}, "} puts "who do we appreciate?"</lang> or: <lang ruby>(2..8).step(2) {|n| print "#{n}, "} puts "who do we appreciate?"</lang> Output

2, 4, 6, 8, who do we appreciate?

Slate

<lang slate>2 to: 8 by: 2 do: [| :i | Console ; i printString ; ', ']. inform: 'enough with the cheering already!'.</lang>

Smalltalk

<lang smalltalk>2 to: 8 by: 2 do: [ :i |

 Transcript show: i; show ', '

]. Transcript showCr: 'enough with the cheering already!'</lang>

Tcl

<lang tcl>for {set i 2} {$i <= 8} {incr i 2} {

   puts -nonewline "$i, "

} puts "enough with the cheering already!"</lang>

TI-89 BASIC

Prints numbers from 0 to 100 stepping by 5.

Local i
For i, 0, 100, 5
    Disp i
EndFor

UNIX Shell

Works with: Bourne Again SHell version 3

<lang bash>for (( x=2; $x<=8; x=$x+2 )); do

 printf "%d, " $x

done echo "blah blah blah"</lang>

Vedit macro language

This prints all odd digits in range 1 to 9: <lang vedit> for (#1 = 1; #1 < 10; #1 += 2) {

   Num_Type(#1)

} </lang>