Loop structures: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎[[SmallTalk]]: Fixed capitalization)
(This task was getting no love, squirreled away in the Language Features category. Moved back to the Programming Tasks section until most of the tasks get a better categorization system.)
Line 1: Line 1:
{{Task}}
{{Language Feature}}


In this task, we document loop structures offered by different languages.
In this task, we document loop structures offered by different languages.

Revision as of 02:34, 1 February 2007

Task
Loop structures
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, we document loop structures offered by different languages.

AppleScript

repeat-until

set i to 5
repeat until i is less than 0
	set i to i - 1
end repeat
repeat
	--endless loop
end repeat

repeat-with

       repeat with i from 1 to 20
               --do something
       end repeat
       set array to {1,2,3,4,5}
       repeat with i in array
               display dialog i
       end repeat

C

while

Compiler: GCC 4.1.2

int main (int argc, char ** argv) {
  int condition = 1;

  while ( condition ) {
    // Do something
    // Don't forget to change the value of condition.
    // If it remains nonzero, we'll have an infinite loop.
  }
}

do-while

int main (int argc, char ** argv) {
  int condition = ...;
 
  do {
    // Do something
    // The difference with the first loop is that the
    // code in the loop will be executed at least once,
    // even if the condition is 0 at the beginning,
    // because it is only checked at the end.
    // Don't forget to change the value of condition.
    // If it remains nonzero, we'll have an infinite loop.
  } while ( condition );
}

for

int main (int argc, char ** argv) {
  int i;
 
  for {i=0; i<10; ++i) {
    // The code here will be performed 10 times.
    // The first part in the for-statement (i=0) is the initialization,
    // and is executed once before the loop begins.
    // The second part is the end condition (i<10), which is checked
    // every time the loop is started, also the first time;
    // the loop ends if it is false.
    // The third part (++i) is performed every time the code in the loop
    // is at the end, just before the end condition is checked.
  }
}

while with continue

The continue statement allows you to continue execution at the beginning of the loop, skipping the rest of the loop. In C you can only do this with the most inner loop. You can also do this with do-while and for.

int main (int argc, char ** argv) {
  int condition = 1;

  while ( condition ) {
    // Do something

    if (other condition)
      continue; // Continue at the beginning of the loop

    // Do something else
    // This part is not executed if other condition was true
  }
}

while with break

The break statement allows you to stop a loop. In C you can only break from most inner loop. You can also do this with do-while and for.

int main (int argc, char ** argv) {
  int condition = 1;

  while ( condition ) {
    // Do something

    if (other condition)
      break; // Continue after the the loop

    // Do something else
    // This part is not executed if other condition was true
  }
}

C++

Run-Time Control Structures

for

Compiler: GCC 3.3.4

#include <iostream>

int main()
{
 int i = 1;

 // Loops forever:
 for(; i == 1;)
  std::cout << "Hello, World!\n";
}

do-while

Compiler: GCC 4.1.2

int main (void) {
  int condition = 1;

  do {
    // Do something
    // Don't forget to change the value of condition.
    // If it remains nonzero, we'll have an infinite loop.
  } while ( condition );
}

Run-Time Control Structures

while

Compiler: GCC 4.1.2

int main (void) {
  int condition = 1;

  while ( condition ) {
    // Do something
    // Don't forget to change the value of condition.
    // If it remains nonzero, we'll have an infinite loop.
  }
}

do-while

Compiler: GCC 4.1.2

int main (void) {
 int condition = 1;

 do {
   // Do something
   // Don't forget to change the value of condition.
   // If it remains nonzero, we'll have an infinite loop.
 } while ( condition );
}

Java

while

   while(true)
   {
       foo();
   }

do-while

   do
   {
       foo();
   }
   while (true)

for

   for(int i = 0; i < 5; i++)
   {
       foo();
   }

foreach

Platform: J2SE 1.5.0

 Object[] objects;
 // ...
 for (Object current : objects[]) {
   // ...
 }
 int[] numbers;
 // ...
 for (int i : numbers) {
   // ...
 }

JavaScript

while

   while(true) {
       foo();
   }

do while

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

for

   for(var i = 0; i < 5; i++) {
       foo();
   }

for in

//iterate through property names of an object

var obj = {prop1:"a", prop2:"b", prop3:"c"};
for (var key in obj)
  alert( key + ' is set to ' + obj[key] );

for each in

//iterate through property values of an object

var obj = {prop1:"a", prop2:"b", prop3:"c"};
for each(var element in obj)
  alert( element );

Pascal

while

Compiler: Turbo Pascal 7.0

 WHILE condition1 DO
   BEGIN
     procedure1;
     procedure2;
   END;

repeat-until

Compiler: Turbo Pascal 7.0

 REPEAT
   procedure1;
   procedure2;
 UNTIL condition1;

for

Compiler: Turbo Pascal 7.0

 FOR counter=1 TO 10 DO
   BEGIN
     procedure1;
     procedure2;
   END;

Perl

while

Interpreter: Perl 5.8.8

#!/usr/bin/perl -w

use strict;

my $condition1 = 0;

while ( $condition1 ) {
 # Do something.
 # Remember to change the value of condition1 at some point.
}

do-while

Interpreter: Perl 5.8.8

#!/usr/bin/perl -w

use strict;

my $condition1 = 0;

do {
 # Do something.
 # Remember to change the value of condition1 at some point.
} while ( $condition1 );

until

Interpreter: Perl 5.8.8

#!/usr/bin/perl -w

use strict;

my $condition1 = 1;

until ( $condition1 ) {
 # Do something.
 # Remember to change the value of condition1 at some point.
}


do-until

Interpreter: Perl 5.8.8

#!/usr/bin/perl -w

use strict;

my $condition1 = 1;

do {
 # Do something.
 # Remember to change the value of condition1 at some point.
} until ( $condition1 );

for

Interpreter: Perl 5.8.8

#!/usr/bin/perl -w

use strict;

my $limit = 5;

for ( my $iterator = 0; $iterator < $limit; $iterator++ ) {
  # Do something
}

# for-variant, implicit iteration
for (0..$limit) {
  # Do something
}

do_something() for 0..$limit;

foreach

Interpreter: Perl 5.8.8

#!/usr/bin/perl -w

use strict;

my @numbers = (1, 2, 3);
my %names = (first => "George", last => "Jetson");

foreach my $number (@numbers) {
  # Do something with $number
}

foreach my $key (keys %names) {
  # Do something with $key (values are accessible as %names{$key} )
}

map

Interpreter: Perl 5.8.8

#!/usr/bin/perl -w

use strict;

my @numbers = (1, 2, 3);
my @target;

@target = map {
  # Do something with $_
} @numbers;

@target = map($_ + 1, @numbers);

sub a_sub {
  # Do something with $_
}

@target = map a_sub @numbers;

grep

Interpreter: Perl 5.8.8

#!/usr/bin/perl -w

use strict;

my @people = qw/Bobbie Charlie Susan/;
my @target;

@target = grep {
  # Discriminate based on $_
} @people;

# Feed grep into map, this picks out elements 1, 3, 5, etc.
@target = map($people[$_], grep($_ & 1, 0..$#people));

# Pick out the diminutive names
@target = grep(/ie$/, @people);

sub a_sub {
  # Do something with $_, and return a true or false value
}

@target = grep a_sub @people;

PHP

while

while(ok()) {
    foo();
    bar();
    baz();
}

for

for($i = 0; $i < 10; ++$i) {
    echo $i;
}

foreach

foreach(range(0, 9) as $i) {
    echo $i;
}

Python

with

Interpreter: Python 2.5

foo could for example open a file or create a lock or a database transaction:

with foo() as bar:
  baz(bar)


while

while ok():
    foo()
    bar()
    baz()
else:
    # break was not called
    quux() 

for

for i in range(10):
    print i
else:
    # break was not called
    foo()
for x in ["foo", "bar", "baz"]:
    print x

Does range(10) return an array? The above two examples may be redundant.

Ruby

while

while true do
  foo
end

for

for i in [0..4] do
  foo
end

each

['foo', 'bar', 'baz'].each do |x|
  puts x
end

collect

array = ['foo', 'bar', 'baz'].collect do |x|
  foo x
end

map

array = ['foo', 'bar', 'baz'].map {|x| foo x }

inject

string = ['foo', 'bar', 'baz'].inject("") do |s,x|
  s << x
end
sum = ['foo', 'bar', 'baz'].inject(0) do |s,x|
  s + x.size
end
product = ['foo', 'bar', 'baz'].inject(1) do |p,x|
  p * x.size
end
boolean = ['foo', 'bar', 'baz'].inject(true) do |b,x|
  b &&= x != 'bar'
end

Smalltalk

whileTrue/whileFalse

 x := 0.
 [ x < 100 ]
      whileTrue: [ x := x + 10.].
 [ x = 0 ]
      whileFalse: [ x := x - 20.].

Tcl

foreach

foreach i {foo bar baz} {
    puts "$i"
}

for

 for {set i 0} {$i < 10} {incr i} {
     puts $i
 }

while

 set i 0
 while {$i < 10} {
     puts [incr i]
 }

UNIX Shell

for

Interpreter: Bourne Again SHell

#!/bin/bash
ARRAY="VALUE1 VALUE2 VALUE3 VALUE4 VALUE5"

for ELEMENT in $ARRAY
do
 echo $ELEMENT # Print $ELEMENT
done

Interpreter: Debian Almquist SHell

#!/bin/sh
ARRAY="VALUE1 VALUE2 VALUE3 VALUE4 VALUE5"

for ELEMENT in $ARRAY
do
 echo $ELEMENT # Print $ELEMENT
done