Control Structures: Difference between revisions
Content added Content deleted
(→[[Pascal]]: Moved to other articles) |
(Beefed up a bit...encyclopedia articles should have more information) |
||
(63 intermediate revisions by 9 users not shown) | |||
Line 1: | Line 1: | ||
[[Category:Encyclopedia]]'''Control structures''' are features of programming languages that influence the code flow. Examples of control structures are: |
|||
{{task}} |
|||
*loops, which repeat sections of code |
|||
*conditions, which selectively execute sections of code |
|||
*exceptions, which help in error handling and avoid causing more problems when there is another problem |
|||
*jumps (a.k.a. "branches" or "gotos"), which explicitly and usually unconditionally set the next instruction to be executed by the program |
|||
Examples of these structures can be found on the following pages: |
|||
Control structures are features of programming languages that influence the code flow. Two common examples are loops and conditions. The task here is to demonstrate control structures supported by different programming languages. |
|||
<font color="#33CC33">This page is being split into multiple articles. Please help move code into these articles, instead: |
|||
* [[Conditional Structures]] |
* [[Conditional Structures]] |
||
* [[Flow Control Structures]] |
* [[Flow Control Structures]] |
||
* [[Loop Structures]] |
* [[Loop Structures]] |
||
* [[Exceptions]] |
* [[Exceptions]] |
||
* [[Help:Orphaned code]] |
|||
=Conditional= |
|||
These control structures depend on conditions to control their behavior. |
|||
==[[Perl]]== |
|||
[[Category:Perl]] |
|||
===if-then-else=== |
|||
'''Interpreter:''' [[Perl]] 5.8.8 |
|||
#!/usr/bin/perl -w |
|||
use strict; |
|||
my $condition1 = 0; |
|||
my $condition2 = 1; |
|||
if ( $condition1 ) { |
|||
# Do something |
|||
} |
|||
# post-conditional if |
|||
do_something() if $condition1; |
|||
#!/usr/bin/perl -w |
|||
use strict; |
|||
my $condition1 = 0; |
|||
my $condition2 = 1; |
|||
if ( $condition1 ) { |
|||
# Do something |
|||
} elsif ( $condition2 ) { |
|||
# Do somethine else |
|||
} |
|||
#!/usr/bin/perl -w |
|||
use strict; |
|||
my $condition1 = 0; |
|||
my $condition2 = 1; |
|||
if ( $condition1 ) { |
|||
# Do something |
|||
} else { |
|||
# Do something else |
|||
} |
|||
#!/usr/bin/perl -w |
|||
use strict; |
|||
my $condition1 = 0; |
|||
my $condition2 = 1; |
|||
if ( $condition1 ) { |
|||
# Do something |
|||
} elsif ( $condition2 ) { |
|||
# Do something else |
|||
} else { |
|||
# Do that other thing |
|||
} |
|||
($condition) ? print "Then\n" : print "Else\n"; |
|||
# or |
|||
my $var = ($condition) ? "Then" : "Else"; |
|||
===unless=== |
|||
'''Interpreter:''' [[Perl]] 5.8.8 |
|||
#!/usr/bin/perl -w |
|||
use strict; |
|||
my $condition1 = 0; |
|||
unless ( $condition1 ) { |
|||
# Do something |
|||
} |
|||
# post-conditional unless |
|||
do_something() unless $condition1; |
|||
unless ( $condition1 ) { |
|||
# Do something |
|||
} else { |
|||
# Do something else |
|||
} |
|||
===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 ); |
|||
===switch=== |
|||
'''Interpreter:''' [[Perl]] 5.8.8 |
|||
#!/usr/bin/perl -w |
|||
use strict; |
|||
use Switch; |
|||
$input = 42; |
|||
switch ($input) { |
|||
case 0 { |
|||
# Do something, because input = 0 |
|||
} |
|||
case 1 { |
|||
# Do something, because input = 1 |
|||
} |
|||
case "coffee" { |
|||
# Do something, because input = coffee |
|||
} |
|||
else { |
|||
# Do something else. |
|||
} |
|||
} |
|||
===goto=== |
|||
'''Interpreter:''' [[Perl]] 5.8.8 |
|||
Typically dispised by most Perl programmers |
|||
goto LABELB; |
|||
LABELA: # note labels end with a colon not semi-colon |
|||
goto END; |
|||
LABELB: |
|||
goto LABELA; |
|||
END: |
|||
exit(0); |
|||
==[[Python]]== |
|||
[[Category:Python]] |
|||
===if-then-else=== |
|||
if x == 0: |
|||
foo() |
|||
elif x == 1: |
|||
bar() |
|||
elif x == 2: |
|||
baz() |
|||
else: |
|||
boz() |
|||
===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() |
|||
===try-except-finally-else=== |
|||
'''Interpreter''': Python 2.5 |
|||
Before Python 2.5 it was not possible to use finally and except together. |
|||
try: |
|||
foo() |
|||
except TypeError: |
|||
bar() |
|||
finally: |
|||
baz() |
|||
else: |
|||
# no exception occurred |
|||
quux() |
|||
===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) |
|||
==[[PHP]]== |
|||
[[Category:PHP]] |
|||
===if-then-else=== |
|||
if ($x == 0) { |
|||
foo(); |
|||
} else if ($x == 1) { |
|||
bar(); |
|||
} else if ($x == 2) { |
|||
baz(); |
|||
} else { |
|||
boz(); |
|||
} |
|||
===while=== |
|||
while(ok()) { |
|||
foo(); |
|||
bar(); |
|||
baz(); |
|||
} |
|||
===for=== |
|||
for($i = 0; $i < 10; ++$i) { |
|||
echo $i; |
|||
} |
|||
===foreach=== |
|||
foreach(range(0, 9) as $i) { |
|||
echo $i; |
|||
} |
|||
===switch=== |
|||
switch($c) |
|||
{ |
|||
case 'a': |
|||
foo(); |
|||
break; |
|||
case 'b': |
|||
bar(); |
|||
default: |
|||
foobar(); |
|||
} |
|||
==[[Ruby]]== |
|||
[[Category:Ruby]] |
|||
===if-then-else=== |
|||
if s == 'Hello World' |
|||
foo |
|||
elsif s == 'Bye World' |
|||
bar |
|||
else |
|||
deus_ex |
|||
end |
|||
===while=== |
|||
while true do |
|||
foo |
|||
end |
|||
===for=== |
|||
for i in [0..4] do |
|||
foo |
|||
end |
|||
===case-when-else=== |
|||
case cartoon_character |
|||
when 'Tom' |
|||
chase |
|||
when 'Jerry' |
|||
flee |
|||
else |
|||
nil |
|||
end |
|||
===ternary=== |
|||
s == 'Hello World' ? foo : bar |
|||
==[[Java]]== |
|||
[[Category:Java]] |
|||
===if-then-else=== |
|||
if(s.equals("Hello World")) |
|||
{ |
|||
foo(); |
|||
} |
|||
else if(s.equals("Bye World")) |
|||
{ |
|||
bar(); |
|||
} |
|||
else |
|||
{ |
|||
deusEx(); |
|||
} |
|||
===while=== |
|||
while(true) |
|||
{ |
|||
foo(); |
|||
} |
|||
===do-while=== |
|||
do |
|||
{ |
|||
foo(); |
|||
} |
|||
while (true) |
|||
===for=== |
|||
for(int i = 0; i < 5; i++) |
|||
{ |
|||
foo(); |
|||
} |
|||
===ternary=== |
|||
s.equals("Hello World") ? foo : bar |
|||
===switch=== |
|||
switch(c) { |
|||
case 'a': |
|||
foo(); |
|||
break; |
|||
case 'b': |
|||
bar(); |
|||
default: |
|||
foobar(); |
|||
} |
|||
==[[JavaScript]]== |
|||
[[Category:JavaScript]] |
|||
===if-then-else=== |
|||
if(s=="Hello World") |
|||
{ |
|||
foo(); |
|||
} |
|||
else if(s=="Bye World") |
|||
{ |
|||
bar(); |
|||
} |
|||
else |
|||
{ |
|||
deusEx(); |
|||
} |
|||
===while=== |
|||
while(true) |
|||
{ |
|||
foo(); |
|||
} |
|||
===for=== |
|||
for(var i = 0; i < 5; i++) |
|||
{ |
|||
foo(); |
|||
} |
|||
==[[SmallTalk]]== |
|||
[[Category:SmallTalk]] |
|||
===ifTrue/ifFalse=== |
|||
"Conditionals in Smalltalk are really messages sent to Boolean objects" |
|||
(( balance) > 0) |
|||
ifTrue: [Transcript cr; show: 'still sitting pretty!'.] |
|||
ifFalse: [Transcript cr; show: 'No money till payday!'.]. |
|||
===whileTrue/whileFalse=== |
|||
x := 0. |
|||
[ x < 100 ] |
|||
whileTrue: [ x := x + 10.]. |
|||
[ x = 0 ] |
|||
whileFalse: [ x := x - 20.]. |
|||
=Iterative= |
|||
These control structure operate on datasets. |
|||
==[[AppleScript]]== |
|||
[[Category:AppleScript]] |
|||
===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 plus plus|C++]]== |
|||
[[Category:C plus plus]] |
|||
===for_each === |
|||
'''Compiler:''' [[GCC]] 4.1.1 |
|||
#include <iostream> // std::cout, std::endl |
|||
#include <vector> // std::vector |
|||
#include <algorithm> // std::for_each |
|||
struct sum |
|||
{ |
|||
int _sum; |
|||
sum() : _sum(0) {}; // Initialize sum with 0; |
|||
void operator() (int a) { _sum += a; } // this function will be called for every element |
|||
}; |
|||
int main() |
|||
{ |
|||
std::vector<int> v; |
|||
v.push_back(10); |
|||
v.push_back(23); |
|||
v.push_back(34); |
|||
/* Note that for_each gets a fresh instance of sum passed, |
|||
* applies every element beginning with *v.begin() up to, |
|||
* but not including v.end() to the function object |
|||
* and returns a copy of it. |
|||
*/ |
|||
sum the_sum = std::for_each(v.begin(), v.end(), sum()); |
|||
std::cout << "The sum is " << the_sum._sum << std::endl; |
|||
return 0; |
|||
} |
|||
==[[Java]]== |
|||
[[Category:Java]] |
|||
===foreach=== |
|||
'''Platform:''' [[J2SE]] 1.5.0 |
|||
Object[] objects; |
|||
// ... |
|||
for (Object current : objects[]) { |
|||
// ... |
|||
} |
|||
int[] numbers; |
|||
// ... |
|||
for (int i : numbers) { |
|||
// ... |
|||
} |
|||
==[[Javascript]]== |
|||
[[Category:Javascript]] |
|||
===foreach=== |
|||
//iterate through properties of an object as if through a collection |
|||
var obj = {prop1:"a",prop2:"b",prop3:"c"}; |
|||
for (var key in obj) |
|||
alert(obj[key]); |
|||
==[[Perl]]== |
|||
[[Category:Perl]] |
|||
===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; |
|||
==[[Python]]== |
|||
[[Category:Python]] |
|||
=== for === |
|||
for x in ["foo", "bar", "baz"]: |
|||
print x |
|||
==[[Ruby]]== |
|||
[[Category:Ruby]] |
|||
=== 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 |
|||
s |
|||
end |
|||
sum = ['foo', 'bar', 'baz'].inject(0) do |s,x| |
|||
s + x.size |
|||
s |
|||
end |
|||
product = ['foo', 'bar', 'baz'].inject(1) do |p,x| |
|||
p * x.size |
|||
p |
|||
end |
|||
hash = ['foo', 'bar', 'baz'].inject({}) do |h,x| |
|||
h[x] = x.size |
|||
h |
|||
end |
|||
boolean = ['foo', 'bar', 'baz'].inject(true) do |b,x| |
|||
b &&= x != 'bar' |
|||
b |
|||
end |
|||
==[[Tcl]]== |
|||
[[Category:Tcl]] |
|||
=== foreach === |
|||
foreach i {foo bar baz} { |
|||
puts "$i" |
|||
} |
|||
==[[UNIX Shell]]== |
|||
[[Category: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 |
Latest revision as of 20:37, 22 October 2008
Control structures are features of programming languages that influence the code flow. Examples of control structures are:
- loops, which repeat sections of code
- conditions, which selectively execute sections of code
- exceptions, which help in error handling and avoid causing more problems when there is another problem
- jumps (a.k.a. "branches" or "gotos"), which explicitly and usually unconditionally set the next instruction to be executed by the program
Examples of these structures can be found on the following pages: