Control Structures: Difference between revisions

From Rosetta Code
Content added Content deleted
(Beefed up a bit...encyclopedia articles should have more information)
 
(126 intermediate revisions by 29 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.


=Conditional=
* [[Conditional Structures]]
* [[Flow Control Structures]]

* [[Loop Structures]]
These control structures depend on conditions to control their behavior.
* [[Exceptions]]

* [[Help:Orphaned code]]
==[[C]]==

===if-then-else===
'''Compiler:''' [[GCC]] 4.1.2
int main (int argc, char ** argv) {
int input = 2;
if ( 3 == input ) {
// Do something
}



if ( 3 == input ) {
// Do something
} else {
// Do something else
}
}

===switch===
'''Compiler:''' [[GCC]] 4.1.2
int main (int argc, char ** argv) {
int input = 42;

switch (input) {
case 0:
// Do something, because input = 0
break;
case 1:
// Do something, because input = 1
break;
case 2:
// Do something, because input = 2
default:
// Do something else.
break; // Optional
}
}

===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===
'''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 );
}

==[[C plus plus|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";
}

==== goto ====
'''Compiler:''' [[GCC]] 3.3.4
#include <iostream>
int main()
{
LOOP:
std::cout << "Hello, World!\n";
goto LOOP;
}

Note that this may also be used in conjunction with other forms of branching.

====if-then-else====
'''Compiler:''' [[GCC]] 4.1.2
int main (void) {
int input = 2;
if ( 3 == input ) {
// Do something
}



if ( 3 == input ) {
// Do something
} else {
// Do something else
}
}

====switch====
'''Compiler:''' [[GCC]] 4.1.2

int main (void) {
int input = 42;

switch (input) {
case 0:
// Do something, because input = 0
break;
case 1:
// Do something, because input = 1
break;
case 2:
// Do something, because input = 2
default:
// Do something else.
break; // Optional
}
}


====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 );
}

=== Compile-Time Control Structures ===

==== Preprocessor Techniques ====

#ifdef, #ifndef, etc..

==== Template Metaprogramming Techniques ====

Template metaprogramming techniques.

==[[ColdFusion]]==

===if-elseif-else===
'''Compiler:''' [[ColdFusion]] any version
<cfif x eq 3>
do something
<cfelseif x eq 4>
do something else
<cfelse>
do something else
</cfif>

===switch===
'''Compiler:''' [[ColdFusion]] any version
<cfswitch expression="#x#">
<cfcase value="1">
do something
</cfcase>
<cfcase value="2">
do something
</cfcase>
<cfdefaultcase>
do something
</cfdefaultcase>
</cfswitch>

==[[OCaml]]==
===if-then-else===
'''Compiler:''' [[OCaml]] 3.09
let condition = true
if condition then
()//do something
else
()//do something else

===match-with===
match expression with
| 0 -> ()//do something
| 1 -> ()//do something
| n when n mod 2 = 0 -> ()//do something
| _ -> ()//do something

==[[Pascal]]==

===if-then-else===
'''Compiler:''' [[Turbo Pascal]] 7.0
IF condition1 THEN
procedure1
ELSE
procedure3;
IF condition1 THEN
BEGIN
procedure1;
procedure2;
END
ELSE
procedure3;
IF condition 1 THEN
BEGIN
procedure1;
procedure2;
END
ELSE
BEGIN
procedure3;
procedure4;
END;

===while===

'''Compiler:''' [[Turbo Pascal]] 7.0

WHILE condition1 DO
BEGIN
procedure1;
procedure2;
END;

===do-while===

'''Compiler:''' [[Turbo Pascal]] 7.0
DO
BEGIN
procedure1;
procedure2;
END
WHILE condition1;

===for===

'''Compiler:''' [[Turbo Pascal]] 7.0

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

==[[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
}


#!/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
}

===unless===

'''Interpreter:''' [[Perl]] 5.8.8
#!/usr/bin/perl -w
use strict;
my $condition1 = 0;
unless ( $condition1 ) {
# Do something
}
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 );

===for===
'''Interpreter:''' [[Perl]] 5.8.8

#!/usr/bin/perl -w
use strict;
my $limit = 5;
for ( my $iterator = 0; $iterator < $limit; $iterator++ ) {
# Do something
}


==[[Python]]==

===if-then-else===

if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
boz()

===while===

while ok():
foo()
bar()
baz()
===for===

for i in range(10):
print i
===try-except-else===

try:
foo()
except TypeError:
bar()
else:
baz()

==[[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;
}


==[[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]]==

===if-then-else===

if(s.equals("Hello World"))
{
foo();
}
else if(s.equals("Bye World"))
{
bar();
}
else
{
deusEx();
}

===while===

while(true)
{
foo();
}
===for===

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

=Iterative=

These control structure operate on datasets.

==C++==
===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==
===foreach===
'''Platform:''' [[J2SE]] 1.5.0

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

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

==Perl==
===foreach===
'''Interpreter:''' [[Perl]] 5.8.8

#!/usr/bin/perl -w

use strict;

my @array = ("Value1", "Value2", "Value3", "Value4", "Value5");

foreach ( @array ) {
my $item = $_
# Do something with $_.
}

==[[Python]]==

=== for ===

for x in ["foo", "bar", "baz"]:
print x

==[[Tcl]]==

=== foreach ===

foreach i {foo bar baz} {
puts "$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

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: