Shortcuts: C C++ Java PHP Python Ruby
C:
/* Prints 0, 1, 2, ... 9 */ int i; for (i = 0; i < 10; ++i) { printf("%d\n", i); }C++:
// Prints 0, 1, 2, ... 9 for (int i = 0; i < 10; ++i) { cout << i << endl; }Java:
// for-loop // Prints 0, 1, 2, ... 9 for (int i = 0; i < 10; ++i) { System.out.println(i); } // foreach-loop (since Java 5.0) // This works for arrays and classes that implement Iterable. String[] a = {"Alpha", "Beta", "Gamma", "Delta"}; for (String elem : a) { System.out.println(elem); }PHP:
# for-loop (normal syntax) for ($i = 0; $i < 10; ++$i) { echo $i, "\n"; } # for-loop (alternate syntax) for ($i = 0; $i < 10; ++$i): echo $i, "\n"; endfor; # foreach-loop (since PHP 4) # In PHP 4, this only works for arrays. # In PHP 5, this also works for iterating objects. # foreach-loop (normal syntax) $a = array('Alpha', 'Beta', 'Gamma', 'Delta'); foreach ($a as $elem) { echo $elem, "\n"; } # foreach-loop (alternate syntax) $a = array('Alpha', 'Beta', 'Gamma', 'Delta'); foreach ($a as $elem): echo $elem, "\n"; endforeach; # foreach-loop (normal syntax) $a = array( 'A' => 'Alpha', 'B' => 'Beta', 'C' => 'Gamma', 'D' => 'Delta' ); foreach ($a as $key => $value) { echo $key, "\t", $value, "\n"; } # foreach-loop (alternate syntax) $a = array( 'A' => 'Alpha', 'B' => 'Beta', 'C' => 'Gamma', 'D' => 'Delta' ); foreach ($a as $key => $value): echo $key, "\t", $value, "\n"; endforeach;Python:
# for-loop (with range(), ascending) # Prints 0, 1, 2, ... 9 for i in range(10): print i # for-loop (with range(), ascending) # Prints 0, 1, 2, ... 9 for i in range(0, 10): print i # for-loop (with range(), descending) # Prints 10, 9, 8, ... 1 for i in range(10, 0, -1): print i # foreach-loop a = ['Alpha', 'Beta', 'Gamma', 'Delta'] for elem in a: print elemRuby:
# for-loop (inclusive range) # Prints 0, 1, 2, ... 9 for i in 0..9 do puts i end # for-loop (exclusive range) # Prints 0, 1, 2, ... 9 for i in 0...10 do puts i end # for-loop (with upto()) # Prints 0, 1, 2, ... 9 0.upto(9) do |i| puts i end # for-loop (with downto()) # Prints 10, 9, 8, ... 1 10.upto(1) do |i| puts i end # for-loop (brace style) # Prints 10, 9, 8, ... 1 # "{}" style to write "do ... end" 10.upto(1) { |i| puts i }
No comments:
Post a Comment