WeixiangYan/CodeTransOcean huggingface dataset:
Task: Draw a rotating cube





Java: import java.awt.*;
import java.awt.event.ActionEvent;
import static java.lang.Math.*;
import javax.swing.*;

public class RotatingCube extends JPanel {
    double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1},
    {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}};

    int[][] edges = {{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},
    {6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}};

    public RotatingCube() {
        setPreferredSize(new Dimension(640, 640));
        setBackground(Color.white);

        scale(100);
        rotateCube(PI / 4, atan(sqrt(2)));

        new Timer(17, (ActionEvent e) -> {
            rotateCube(PI / 180, 0);
            repaint();
        }).start();
    }

    final void scale(double s) {
        for (double[] node : nodes) {
            node[0] *= s;
            node[1] *= s;
            node[2] *= s;
        }
    }

    final void rotateCube(double angleX, double angleY) {
        double sinX = sin(angleX);
        double cosX = cos(angleX);

        double sinY = sin(angleY);
        double cosY = cos(angleY);

        for (double[] node : nodes) {
            double x = node[0];
            double y = node[1];
            double z = node[2];

            node[0] = x * cosX - z * sinX;
            node[2] = z * cosX + x * sinX;

            z = node[2];

            node[1] = y * cosY - z * sinY;
            node[2] = z * cosY + y * sinY;
        }
    }

    void drawCube(Graphics2D g) {
        g.translate(getWidth() / 2, getHeight() / 2);

        for (int[] edge : edges) {
            double[] xy1 = nodes[edge[0]];
            double[] xy2 = nodes[edge[1]];
            g.drawLine((int) round(xy1[0]), (int) round(xy1[1]),
                    (int) round(xy2[0]), (int) round(xy2[1]));
        }

        for (double[] node : nodes) 
            g.fillOval((int) round(node[0]) - 4, (int) round(node[1]) - 4, 8, 8);        
    }

    @Override
    public void paintComponent(Graphics gg) {
        super.paintComponent(gg);
        Graphics2D g = (Graphics2D) gg;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        drawCube(g);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("Rotating Cube");
            f.setResizable(false);
            f.add(new RotatingCube(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}
Task: Draw a rotating cube







Python: from visual import *
scene.title = "VPython: Draw a rotating cube"

scene.range = 2
scene.autocenter = True

print "Drag with right mousebutton to rotate view."
print "Drag up+down with middle mousebutton to zoom."

deg45 = math.radians(45.0)  

cube = box()    
cube.rotate( angle=deg45, axis=(1,0,0) )
cube.rotate( angle=deg45, axis=(0,0,1) )

while True:                 
    rate(50)
    cube.rotate( angle=0.005, axis=(0,1,0) )
Task: Draw a rotating cube




Go: package main

import (
	"image"
	"image/color"
	"image/gif"
	"log"
	"math"
	"os"
)

const (
	width, height = 640, 640
	offset        = height / 2
	fileName      = "rotatingCube.gif"
)

var nodes = [][]float64{{-100, -100, -100}, {-100, -100, 100}, {-100, 100, -100}, {-100, 100, 100},
	{100, -100, -100}, {100, -100, 100}, {100, 100, -100}, {100, 100, 100}}
var edges = [][]int{{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},
	{6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}}

func main() {
	var images []*image.Paletted
	fgCol := color.RGBA{0xff, 0x00, 0xff, 0xff}
	var palette = []color.Color{color.RGBA{0x00, 0x00, 0x00, 0xff}, fgCol}
	var delays []int

	imgFile, err := os.Create(fileName)
	if err != nil {
		log.Fatal(err)
	}
	defer imgFile.Close()

	rotateCube(math.Pi/4, math.Atan(math.Sqrt(2)))
	var frame float64
	for frame = 0; frame < 360; frame++ {
		img := image.NewPaletted(image.Rect(0, 0, width, height), palette)
		images = append(images, img)
		delays = append(delays, 5)
		for _, edge := range edges {
			xy1 := nodes[edge[0]]
			xy2 := nodes[edge[1]]
			drawLine(int(xy1[0])+offset, int(xy1[1])+offset, int(xy2[0])+offset, int(xy2[1])+offset, img, fgCol)
		}
		rotateCube(math.Pi/180, 0)
	}
	if err := gif.EncodeAll(imgFile, &gif.GIF{Image: images, Delay: delays}); err != nil {
		imgFile.Close()
		log.Fatal(err)
	}

}

func rotateCube(angleX, angleY float64) {
	sinX := math.Sin(angleX)
	cosX := math.Cos(angleX)
	sinY := math.Sin(angleY)
	cosY := math.Cos(angleY)
	for _, node := range nodes {
		x := node[0]
		y := node[1]
		z := node[2]
		node[0] = x*cosX - z*sinX
		node[2] = z*cosX + x*sinX
		z = node[2]
		node[1] = y*cosY - z*sinY
		node[2] = z*cosY + y*sinY
	}
}

func drawLine(x0, y0, x1, y1 int, img *image.Paletted, col color.RGBA) {
	dx := abs(x1 - x0)
	dy := abs(y1 - y0)
	var sx, sy int = -1, -1
	if x0 < x1 {
		sx = 1
	}
	if y0 < y1 {
		sy = 1
	}
	err := dx - dy
	for {
		img.Set(x0, y0, col)
		if x0 == x1 && y0 == y1 {
			break
		}
		e2 := 2 * err
		if e2 > -dy {
			err -= dy
			x0 += sx
		}
		if e2 < dx {
			err += dx
			y0 += sy
		}
	}
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
Task: Terminal control_Coloured text



C#: static void Main(string[] args)
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.BackgroundColor = ConsoleColor.Yellow;
    Console.WriteLine("Red on Yellow");
    Console.ForegroundColor = ConsoleColor.White;
    Console.BackgroundColor = ConsoleColor.Black;
    Console.WriteLine("White on black");
    Console.ResetColor();
    Console.WriteLine("Back to normal");
    Console.ReadKey();
}









Ada: with Ada.Text_Io;

with Ansi;

procedure Coloured  is
   use Ada.Text_Io;
   subtype Ansi_Colors is Ansi.Colors
     range Ansi.Black .. Ansi.Colors'Last;  
begin
   for Fg_Color in Ansi_Colors loop
      Put ("Rosetta ");
      Put (Ansi.Foreground (Fg_Color));
      for Bg_Color in Ansi_Colors loop
         Put (Ansi.Background (Bg_Color));
         Put ("Code");
      end loop;
      Put (Ansi.Reset);
      New_Line;
   end loop;
end Coloured;
Task: Terminal control_Coloured text

C: #include <stdio.h>

void table(const char *title, const char *mode)
{
	int f, b;
	printf("\n\033[1m%s\033[m\n bg\t fg\n", title);
	for (b = 40; b <= 107; b++) {
		if (b == 48) b = 100;
		printf("%3d\t\033[%s%dm", b, mode, b);
		for (f = 30; f <= 97; f++) {
			if (f == 38) f = 90;
			printf("\033[%dm%3d ", f, f);
		}
		puts("\033[m");
	}
}

int main(void)
{
	int fg, bg, blink, inverse;

	table("normal ( ESC[22m or ESC[m )", "22;");
	table("bold ( ESC[1m )", "1;");
	table("faint ( ESC[2m ), not well supported", "2;");
	table("italic ( ESC[3m ), not well supported", "3;");
	table("underline ( ESC[4m ), support varies", "4;");
	table("blink ( ESC[5m )", "5;");
	table("inverted ( ESC[7m )", "7;");
	return 0;
}











Ada: with Ada.Text_Io;

with Ansi;

procedure Coloured  is
   use Ada.Text_Io;
   subtype Ansi_Colors is Ansi.Colors
     range Ansi.Black .. Ansi.Colors'Last;  
begin
   for Fg_Color in Ansi_Colors loop
      Put ("Rosetta ");
      Put (Ansi.Foreground (Fg_Color));
      for Bg_Color in Ansi_Colors loop
         Put (Ansi.Background (Bg_Color));
         Put ("Code");
      end loop;
      Put (Ansi.Reset);
      New_Line;
   end loop;
end Coloured;
Task: Terminal control_Coloured text




Go: package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    color(red)
    fmt.Println("Red")
    color(green)
    fmt.Println("Green")
    color(blue)
    fmt.Println("Blue")
}

const (
    blue  = "1"
    green = "2"
    red   = "4"
)

func color(c string) {
    cmd := exec.Command("tput", "setf", c)
    cmd.Stdout = os.Stdout
    cmd.Run()
}








Ada: with Ada.Text_Io;

with Ansi;

procedure Coloured  is
   use Ada.Text_Io;
   subtype Ansi_Colors is Ansi.Colors
     range Ansi.Black .. Ansi.Colors'Last;  
begin
   for Fg_Color in Ansi_Colors loop
      Put ("Rosetta ");
      Put (Ansi.Foreground (Fg_Color));
      for Bg_Color in Ansi_Colors loop
         Put (Ansi.Background (Bg_Color));
         Put ("Code");
      end loop;
      Put (Ansi.Reset);
      New_Line;
   end loop;
end Coloured;
Task: Terminal control_Coloured text







Python: from colorama import init, Fore, Back, Style
init(autoreset=True)

print Fore.RED + "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic"
print Back.BLUE + Fore.YELLOW + "What a cute console!"
print "This is an %simportant%s word" % (Style.BRIGHT, Style.NORMAL)
print Fore.YELLOW  + "Rosetta Code!"
print Fore.CYAN    + "Rosetta Code!"
print Fore.GREEN   + "Rosetta Code!"
print Fore.MAGENTA + "Rosetta Code!"
print Back.YELLOW + Fore.BLUE + Style.BRIGHT + " " * 40 + " == Good Bye!"





Ada: with Ada.Text_Io;

with Ansi;

procedure Coloured  is
   use Ada.Text_Io;
   subtype Ansi_Colors is Ansi.Colors
     range Ansi.Black .. Ansi.Colors'Last;  
begin
   for Fg_Color in Ansi_Colors loop
      Put ("Rosetta ");
      Put (Ansi.Foreground (Fg_Color));
      for Bg_Color in Ansi_Colors loop
         Put (Ansi.Background (Bg_Color));
         Put ("Code");
      end loop;
      Put (Ansi.Reset);
      New_Line;
   end loop;
end Coloured;
Task: Terminal control_Coloured text

C: #include <stdio.h>

void table(const char *title, const char *mode)
{
	int f, b;
	printf("\n\033[1m%s\033[m\n bg\t fg\n", title);
	for (b = 40; b <= 107; b++) {
		if (b == 48) b = 100;
		printf("%3d\t\033[%s%dm", b, mode, b);
		for (f = 30; f <= 97; f++) {
			if (f == 38) f = 90;
			printf("\033[%dm%3d ", f, f);
		}
		puts("\033[m");
	}
}

int main(void)
{
	int fg, bg, blink, inverse;

	table("normal ( ESC[22m or ESC[m )", "22;");
	table("bold ( ESC[1m )", "1;");
	table("faint ( ESC[2m ), not well supported", "2;");
	table("italic ( ESC[3m ), not well supported", "3;");
	table("underline ( ESC[4m ), support varies", "4;");
	table("blink ( ESC[5m )", "5;");
	table("inverted ( ESC[7m )", "7;");
	return 0;
}
Task: Terminal control_Coloured text



C#: static void Main(string[] args)
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.BackgroundColor = ConsoleColor.Yellow;
    Console.WriteLine("Red on Yellow");
    Console.ForegroundColor = ConsoleColor.White;
    Console.BackgroundColor = ConsoleColor.Black;
    Console.WriteLine("White on black");
    Console.ResetColor();
    Console.WriteLine("Back to normal");
    Console.ReadKey();
}
Task: Terminal control_Coloured text







Python: from colorama import init, Fore, Back, Style
init(autoreset=True)

print Fore.RED + "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic"
print Back.BLUE + Fore.YELLOW + "What a cute console!"
print "This is an %simportant%s word" % (Style.BRIGHT, Style.NORMAL)
print Fore.YELLOW  + "Rosetta Code!"
print Fore.CYAN    + "Rosetta Code!"
print Fore.GREEN   + "Rosetta Code!"
print Fore.MAGENTA + "Rosetta Code!"
print Back.YELLOW + Fore.BLUE + Style.BRIGHT + " " * 40 + " == Good Bye!"
Task: Terminal control_Coloured text




Go: package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    color(red)
    fmt.Println("Red")
    color(green)
    fmt.Println("Green")
    color(blue)
    fmt.Println("Blue")
}

const (
    blue  = "1"
    green = "2"
    red   = "4"
)

func color(c string) {
    cmd := exec.Command("tput", "setf", c)
    cmd.Stdout = os.Stdout
    cmd.Run()
}
Task: Terminal control_Coloured text



C#: static void Main(string[] args)
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.BackgroundColor = ConsoleColor.Yellow;
    Console.WriteLine("Red on Yellow");
    Console.ForegroundColor = ConsoleColor.White;
    Console.BackgroundColor = ConsoleColor.Black;
    Console.WriteLine("White on black");
    Console.ResetColor();
    Console.WriteLine("Back to normal");
    Console.ReadKey();
}








Fortran: 

program coloured_terminal_text
  use, intrinsic :: iso_fortran_env, only: ERROR_UNIT
  implicit none

  
  character(*), parameter :: esc = achar(27) 
  character(*), parameter :: reset = esc // '[0m' 
  
  character(*), parameter :: red     = esc // '[31m'
  character(*), parameter :: green   = esc // '[32m'
  character(*), parameter :: yellow  = esc // '[33m'
  character(*), parameter :: blue    = esc // '[34m'
  character(*), parameter :: magenta = esc // '[35m'
  character(*), parameter :: cyan    = esc // '[36m'
  character(*), parameter :: grey    = esc // '[90m' 
  
  character(*), parameter :: background_green = esc // '[42m'
  
  character(*), parameter :: bold = esc // '[1m'
  character(*), parameter :: bold_blink = esc // '[1;5m'

  
  write(ERROR_UNIT, '(a)') bold // 'Coloured words:' // reset
  write(ERROR_UNIT, '(4x, a)')       & 
      red     // 'Red'     // reset, &
      green   // 'Green'   // reset, &
      yellow  // 'Yellow'  // reset, &
      blue    // 'Blue'    // reset, &
      magenta // 'Magenta' // reset, &
      cyan    // 'Cyan'    // reset, &
      grey    // 'Grey'    // reset
  write(ERROR_UNIT, '(a)') bold_blink // 'THE END ;-)' // reset

  write(ERROR_UNIT, '(a)') background_green // 'Bonus Round' // reset
end program coloured_terminal_text
Task: Terminal control_Coloured text

C: #include <stdio.h>

void table(const char *title, const char *mode)
{
	int f, b;
	printf("\n\033[1m%s\033[m\n bg\t fg\n", title);
	for (b = 40; b <= 107; b++) {
		if (b == 48) b = 100;
		printf("%3d\t\033[%s%dm", b, mode, b);
		for (f = 30; f <= 97; f++) {
			if (f == 38) f = 90;
			printf("\033[%dm%3d ", f, f);
		}
		puts("\033[m");
	}
}

int main(void)
{
	int fg, bg, blink, inverse;

	table("normal ( ESC[22m or ESC[m )", "22;");
	table("bold ( ESC[1m )", "1;");
	table("faint ( ESC[2m ), not well supported", "2;");
	table("italic ( ESC[3m ), not well supported", "3;");
	table("underline ( ESC[4m ), support varies", "4;");
	table("blink ( ESC[5m )", "5;");
	table("inverted ( ESC[7m )", "7;");
	return 0;
}










Fortran: 

program coloured_terminal_text
  use, intrinsic :: iso_fortran_env, only: ERROR_UNIT
  implicit none

  
  character(*), parameter :: esc = achar(27) 
  character(*), parameter :: reset = esc // '[0m' 
  
  character(*), parameter :: red     = esc // '[31m'
  character(*), parameter :: green   = esc // '[32m'
  character(*), parameter :: yellow  = esc // '[33m'
  character(*), parameter :: blue    = esc // '[34m'
  character(*), parameter :: magenta = esc // '[35m'
  character(*), parameter :: cyan    = esc // '[36m'
  character(*), parameter :: grey    = esc // '[90m' 
  
  character(*), parameter :: background_green = esc // '[42m'
  
  character(*), parameter :: bold = esc // '[1m'
  character(*), parameter :: bold_blink = esc // '[1;5m'

  
  write(ERROR_UNIT, '(a)') bold // 'Coloured words:' // reset
  write(ERROR_UNIT, '(4x, a)')       & 
      red     // 'Red'     // reset, &
      green   // 'Green'   // reset, &
      yellow  // 'Yellow'  // reset, &
      blue    // 'Blue'    // reset, &
      magenta // 'Magenta' // reset, &
      cyan    // 'Cyan'    // reset, &
      grey    // 'Grey'    // reset
  write(ERROR_UNIT, '(a)') bold_blink // 'THE END ;-)' // reset

  write(ERROR_UNIT, '(a)') background_green // 'Bonus Round' // reset
end program coloured_terminal_text
Task: Terminal control_Coloured text







Python: from colorama import init, Fore, Back, Style
init(autoreset=True)

print Fore.RED + "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic"
print Back.BLUE + Fore.YELLOW + "What a cute console!"
print "This is an %simportant%s word" % (Style.BRIGHT, Style.NORMAL)
print Fore.YELLOW  + "Rosetta Code!"
print Fore.CYAN    + "Rosetta Code!"
print Fore.GREEN   + "Rosetta Code!"
print Fore.MAGENTA + "Rosetta Code!"
print Back.YELLOW + Fore.BLUE + Style.BRIGHT + " " * 40 + " == Good Bye!"




Fortran: 

program coloured_terminal_text
  use, intrinsic :: iso_fortran_env, only: ERROR_UNIT
  implicit none

  
  character(*), parameter :: esc = achar(27) 
  character(*), parameter :: reset = esc // '[0m' 
  
  character(*), parameter :: red     = esc // '[31m'
  character(*), parameter :: green   = esc // '[32m'
  character(*), parameter :: yellow  = esc // '[33m'
  character(*), parameter :: blue    = esc // '[34m'
  character(*), parameter :: magenta = esc // '[35m'
  character(*), parameter :: cyan    = esc // '[36m'
  character(*), parameter :: grey    = esc // '[90m' 
  
  character(*), parameter :: background_green = esc // '[42m'
  
  character(*), parameter :: bold = esc // '[1m'
  character(*), parameter :: bold_blink = esc // '[1;5m'

  
  write(ERROR_UNIT, '(a)') bold // 'Coloured words:' // reset
  write(ERROR_UNIT, '(4x, a)')       & 
      red     // 'Red'     // reset, &
      green   // 'Green'   // reset, &
      yellow  // 'Yellow'  // reset, &
      blue    // 'Blue'    // reset, &
      magenta // 'Magenta' // reset, &
      cyan    // 'Cyan'    // reset, &
      grey    // 'Grey'    // reset
  write(ERROR_UNIT, '(a)') bold_blink // 'THE END ;-)' // reset

  write(ERROR_UNIT, '(a)') background_green // 'Bonus Round' // reset
end program coloured_terminal_text
Task: Loops_Foreach



C#: string[] things = {"Apple", "Banana", "Coconut"};

foreach (string thing in things)
{
    Console.WriteLine(thing);
}









Ada: with Ada.Integer_Text_IO;
use  Ada.Integer_Text_IO;

procedure For_Each is

   A : array (1..5) of Integer := (-1, 0, 1, 2, 3);

begin

   for Num in A'Range loop
      Put( A (Num) );
   end loop;

end For_Each;
Task: Loops_Foreach

C: #include <stdio.h>
...

const char *list[] = {"Red","Green","Blue","Black","White"};
#define LIST_SIZE (sizeof(list)/sizeof(list[0]))

int ix;
for(ix=0; ix<LIST_SIZE; ix++) {
   printf("%s\n", list[ix]);
}











Ada: with Ada.Integer_Text_IO;
use  Ada.Integer_Text_IO;

procedure For_Each is

   A : array (1..5) of Integer := (-1, 0, 1, 2, 3);

begin

   for Num in A'Range loop
      Put( A (Num) );
   end loop;

end For_Each;
Task: Loops_Foreach


C++: for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
  std::cout << *i << "\n";
}










Ada: with Ada.Integer_Text_IO;
use  Ada.Integer_Text_IO;

procedure For_Each is

   A : array (1..5) of Integer := (-1, 0, 1, 2, 3);

begin

   for Num in A'Range loop
      Put( A (Num) );
   end loop;

end For_Each;
Task: Loops_Foreach




Go: func printAll(values []int) {
   for i, x := range values {
      fmt.Printf("Item %d = %d\n", i, x)
   }
}








Ada: with Ada.Integer_Text_IO;
use  Ada.Integer_Text_IO;

procedure For_Each is

   A : array (1..5) of Integer := (-1, 0, 1, 2, 3);

begin

   for Num in A'Range loop
      Put( A (Num) );
   end loop;

end For_Each;
Task: Loops_Foreach





Java: module LoopForEach
    {
    @Inject Console console;
    void run()
        {
        val vals = [10, 20, 30, 40];
        console.print("Array of values:");
        Loop: for (val val : vals)
            {
            console.print($"  value #{Loop.count + 1}: {val}");
            }

        Map<String, Int> pairs = ["x"=42, "y"=69];
        console.print("\nKeys and values:");
        for ((String key, Int val) : pairs)
            {
            console.print($"  {key}={val}");
            }
        console.print("\nJust the keys:");
        Loop: for (String key : pairs)
            {
            console.print($"  key #{Loop.count + 1}: {key}");
            }

        console.print("\nValues from a range:");
        for (Int n : 1..5)
            {
            console.print($"  {n}");
            }
        }
    }







Ada: with Ada.Integer_Text_IO;
use  Ada.Integer_Text_IO;

procedure For_Each is

   A : array (1..5) of Integer := (-1, 0, 1, 2, 3);

begin

   for Num in A'Range loop
      Put( A (Num) );
   end loop;

end For_Each;
Task: Loops_Foreach







Python: for i in collection:
   print i





Ada: with Ada.Integer_Text_IO;
use  Ada.Integer_Text_IO;

procedure For_Each is

   A : array (1..5) of Integer := (-1, 0, 1, 2, 3);

begin

   for Num in A'Range loop
      Put( A (Num) );
   end loop;

end For_Each;
Task: Loops_Foreach








VB: Public Sub LoopsForeach()
    Dim FruitArray() As Variant
    Dim Fruit As Variant
    FruitArray = [{"Apple","Banana","Strawberry"}]
    Dim FruitBasket As Collection
    Set FruitBasket = New Collection
    For Each Fruit In FruitArray
        FruitBasket.Add Fruit
    Next Fruit
    For Each Fruit In FruitBasket
        Debug.Print Fruit
    Next Fruit
End Sub




Ada: with Ada.Integer_Text_IO;
use  Ada.Integer_Text_IO;

procedure For_Each is

   A : array (1..5) of Integer := (-1, 0, 1, 2, 3);

begin

   for Num in A'Range loop
      Put( A (Num) );
   end loop;

end For_Each;
Task: Loops_Foreach

C: #include <stdio.h>
...

const char *list[] = {"Red","Green","Blue","Black","White"};
#define LIST_SIZE (sizeof(list)/sizeof(list[0]))

int ix;
for(ix=0; ix<LIST_SIZE; ix++) {
   printf("%s\n", list[ix]);
}
Task: Loops_Foreach



C#: string[] things = {"Apple", "Banana", "Coconut"};

foreach (string thing in things)
{
    Console.WriteLine(thing);
}
Task: Loops_Foreach


C++: for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
  std::cout << *i << "\n";
}
Task: Loops_Foreach





Java: module LoopForEach
    {
    @Inject Console console;
    void run()
        {
        val vals = [10, 20, 30, 40];
        console.print("Array of values:");
        Loop: for (val val : vals)
            {
            console.print($"  value #{Loop.count + 1}: {val}");
            }

        Map<String, Int> pairs = ["x"=42, "y"=69];
        console.print("\nKeys and values:");
        for ((String key, Int val) : pairs)
            {
            console.print($"  {key}={val}");
            }
        console.print("\nJust the keys:");
        Loop: for (String key : pairs)
            {
            console.print($"  key #{Loop.count + 1}: {key}");
            }

        console.print("\nValues from a range:");
        for (Int n : 1..5)
            {
            console.print($"  {n}");
            }
        }
    }
Task: Loops_Foreach







Python: for i in collection:
   print i
Task: Loops_Foreach








VB: Public Sub LoopsForeach()
    Dim FruitArray() As Variant
    Dim Fruit As Variant
    FruitArray = [{"Apple","Banana","Strawberry"}]
    Dim FruitBasket As Collection
    Set FruitBasket = New Collection
    For Each Fruit In FruitArray
        FruitBasket.Add Fruit
    Next Fruit
    For Each Fruit In FruitBasket
        Debug.Print Fruit
    Next Fruit
End Sub
Task: Loops_Foreach




Go: func printAll(values []int) {
   for i, x := range values {
      fmt.Printf("Item %d = %d\n", i, x)
   }
}
Task: Loops_Foreach



C#: string[] things = {"Apple", "Banana", "Coconut"};

foreach (string thing in things)
{
    Console.WriteLine(thing);
}








Fortran: program main

 implicit none

 integer :: i
 character(len=5),dimension(5),parameter :: colors = ['Red  ','Green','Blue ','Black','White']

 
 do i=1,size(colors)
   write(*,'(A)') colors(i) 
 end do

 
 write(*,'(A)') colors

end program main
Task: Loops_Foreach


C++: for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
  std::cout << *i << "\n";
}









Fortran: program main

 implicit none

 integer :: i
 character(len=5),dimension(5),parameter :: colors = ['Red  ','Green','Blue ','Black','White']

 
 do i=1,size(colors)
   write(*,'(A)') colors(i) 
 end do

 
 write(*,'(A)') colors

end program main
Task: Loops_Foreach

C: #include <stdio.h>
...

const char *list[] = {"Red","Green","Blue","Black","White"};
#define LIST_SIZE (sizeof(list)/sizeof(list[0]))

int ix;
for(ix=0; ix<LIST_SIZE; ix++) {
   printf("%s\n", list[ix]);
}










Fortran: program main

 implicit none

 integer :: i
 character(len=5),dimension(5),parameter :: colors = ['Red  ','Green','Blue ','Black','White']

 
 do i=1,size(colors)
   write(*,'(A)') colors(i) 
 end do

 
 write(*,'(A)') colors

end program main