프로그래밍 언어/코드 예제


이 페이지는 컴퓨터 프로그래밍 언어로 구현한 몇 가지 코드들의 예제이다.

전통있는 전산학과 1학년 1학기 과제들이다.

  • 새로운 언어의 예제 코드를 추가할 때, 가급적 알파벳, 가나다 순서를 유지해 주십시오. 당연히 이렇게 작성되어 있어야만 보다 편리하게 찾아볼 수 있습니다.
  • 기본적인 언어 예제를 표방하니만큼, 원라이너 등 코드의 가독성을 해칠 수 있는 예제를 수록하지 마세요.
  • 문서의 의미없는 비대화를 막기 위해, 기존에 등록되어 있는 코드의 기능들(Hello World, 99병의 맥주, 구구단, 삼각형 그리기, 1부터 N까지 출력) 외의 목차를 수록하지 마세요.
  • 프로그래밍 언어의 난이도나 프로그래밍 실력을 자랑하기 위한 곳이 아닙니다. 추가적인 복잡한 연산이나 라이브러리를 포함하지 않는 간단한 예제를 작성해주세요.
  • 난해한 프로그래밍 언어의 예제들은 프로그래밍 언어/코드 예제/난해한 프로그래밍 언어 페이지에 등록해 주시기 바랍니다.

1 Hello, world!

언어를 배울때 주로 사용하는 가장 기본적인 출력 예제이다. 프로그래밍에 입문하는 사람이라면 누구나 한번쯤은 코딩해보는 코드. 유래는 항목을 참조하라.

1.1 ABAP

<syntaxhighlight lang="python" line="1">
write 'Hello, world!'.
</syntaxhighlight>

1.2 ActionScript 3.0

package {
import flash.text.TextField;

public class HelloWorld extends Sprite {
public function HelloWorld():void {
var helloworldField:TextField = new TextField();
helloworldField.text = "Hello World!";
addChild(helloworldField);
}
}
}

1.3 Arduino

<syntaxhighlight lang="python" line="1">
void setup() {
Serial.begin(9600);Serial.println("Hello, World!");
}

void loop() {

}
</syntaxhighlight>

1.4 BASIC

<syntaxhighlight lang="python" line="1">
10 PRINT "Hello, World!"
20 END
</syntaxhighlight>

1.5 C

Hello, world!가 최초로 언급된 언어이다. The C Programming Language에 실려있는 매우 유서깊은 코드.

(K&R 기준)


main( ) {
puts("Hello, world!");
return 0;
}

(C99 기준)


#include 
int main(void) 
{
printf("Hello, World!\n");
return 0;
}

(C11)[1]


#include 
int main(int argc, const char * argv[]) 
{
printf("Hello, World!\n");
return 0;
}

또는


#include 
int main(void) 
{
puts("Hello, World!");
return 0;
}

1.6 C++

<syntaxhighlight lang="python" line="1">

  1. include <iostream>

int main()
{
std::cout << "Hello, World!" << std::endl;return 0;
}
</syntaxhighlight>

혹은


<syntaxhighlight lang="python" line="1">

  1. include <iostream>

using namespace std;

int main()
{
cout<<"Hello, World!" << endl;return 0;
}
</syntaxhighlight>

1.7 C\#

using System;
namespace foo
{
class foo
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
}
}
}

1.8 Clojure

<syntaxhighlight lang="python" line="1">
(println "Hello, world!")
</syntaxhighlight>

1.9 COBOL

 #!syntax python
*****************************
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
ENVIRONMENT DIVISION.
DATA DIVISION.
PROCEDURE DIVISION.
MAIN SECTION.
DISPLAY "Hello World!"
STOP RUN.
****************************

1.10 CUDA

<syntaxhighlight lang="python" line="1">

  1. include <stdio.h>

const int N = 16;
const int blocksize = 16;

global
void hello(char *a, int *b)
{
a[threadIdx.x] += b[threadIdx.x];
}

int main()
{
char a[N] = "Hello \0\0\0\0\0\0";
int b[N] = {15, 10, 6, 0, -11, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

char *ad;
int *bd;
const int csize = N*sizeof(char);
const int isize = N*sizeof(int);

printf("%s", a);

cudaMalloc( (void**)&ad, csize );
cudaMalloc( (void**)&bd, isize );
cudaMemcpy( ad, a, csize, cudaMemcpyHostToDevice );
cudaMemcpy( bd, b, isize, cudaMemcpyHostToDevice );

dim3 dimBlock( blocksize, 1 );
dim3 dimGrid( 1, 1 );
hello<<<dimGrid, dimBlock>>>(ad, bd);
cudaMemcpy( a, ad, csize, cudaMemcpyDeviceToHost );
cudaFree( ad );
cudaFree( bd );

printf("%s\n", a);
return EXIT_SUCCESS;
}
</syntaxhighlight>

CUDA로 이런걸 왜 짜는거야

1.11 D

import std.stdio;
void main()
{
writeln("Hello, world!");
}

1.12 Erlang

-module(hello).
-export([hello_world/0]).
hello_world() -> io:fwrite("hello, world\n").

1.13 FORTRAN

<syntaxhighlight lang="python" line="1">
program
Print *, "Hello, world!"End
</syntaxhighlight>

1.14 Go

package main
import "fmt"
func main() {
fmt.Printf("Hello, world!");
}

1.15 Haskell

main = putStrLn "Hello, world!"

1.16 IDL

PRO main
print, "Hello, world!" 
END

1.17 Java

<syntaxhighlight lang="python" line="1">
public class Foo {
public static void main(String[] args) {System.out.println("Hello, world!");
}
}
</syntaxhighlight>

1.18 JavaScript

웹 페이지로 출력

<syntaxhighlight lang="python" line="1">
document.write("Hello, world!");
</syntaxhighlight>

브라우저 경고 창으로 출력

<syntaxhighlight lang="python" line="1">
alert("Hello, world!");
</syntaxhighlight>

터미널이나 브라우저의 콘솔으로 출력

<syntaxhighlight lang="python" line="1">
console.log("Hello, world!");
</syntaxhighlight>

1.19 LabVIEW

7fed2cf9f0903de17482a35bcdf3494c.png
위쪽 창이 프로그램 코드, 아래쪽 창이 인터페이스.

러시아어는 무시하자

1.20 LISP

<syntaxhighlight lang="python" line="1">
(print "Hello, World!")
</syntaxhighlight>

1.21 Lua

<syntaxhighlight lang="python" line="1">
print("Hello, world!")
</syntaxhighlight>

1.22 Node.js

<syntaxhighlight lang="python" line="1">
console.log('Hello, world!');
</syntaxhighlight>

1.23 Objective-C

<syntaxhighlight lang="python" line="1">

  1. import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
@autoreleasepool {NSLog(@"Hello, World!");
}return 0;
}
</syntaxhighlight>

1.24 Pascal

<syntaxhighlight lang="python" line="1">
Program Hello;

begin
writeln('Hello, world!')
end.
</syntaxhighlight>

1.25 Perl

<syntaxhighlight lang="python" line="1">
print "Hello, World!\n";
</syntaxhighlight>

1.26 PHP

<syntaxhighlight lang="python" line="1">
<?php
echo ("Hello, World!");
?>
</syntaxhighlight>

echo를 print로 대체해도 같은 기능을 수행하고 괄호를 생략해도 된다.


<syntaxhighlight lang="python" line="1">
<?="Hello, World!" ?>
</syntaxhighlight>

이렇게 써도 결과는 동일하다.

1.27 Processing

<syntaxhighlight lang="python" line="1">
println("Hello, world!");
</syntaxhighlight>

하지만 아래와 같이 쓰는 것이 프로세싱의 look&feel을 살리는 예제라고 한다. (위키피디아에서 전재)

<syntaxhighlight lang="python" line="1">
void setup() {
PFont font = loadFont("myfont.vlw");textFont(font,20);
}

void draw() {
text("Hello, world!", 30,50);
}
</syntaxhighlight>

이 코드를 실행시키기 위해서는 프로세싱 IDE의 Create Font 기능을 이용하여 vlw 폰트를 미리 만들어두어야한다.

여담으로, 프로세싱은 어떤 교재를 봐도 Hello World 예제가 실려있는 경우가 드물다. 간단한 코드로 그림을 그리거나 하는 것이 가능한 언어다보니 ellipse나 rect 같은 함수로 간단한 그림부터 그려보는 것이 보통.

1.28 Prolog

<syntaxhighlight lang="python" line="1">
write("Hello, World!").
</syntaxhighlight>

다른 언어와는 좀 다르게 위의 코드는 프로그래머가 작성하는 소스 파일의 코드가 아니라 인터프리터에 입력(질의)하기 위한 코드이고 write역시 프롤로그에 이미 내장되어 있는 소스(서술식)이다. 결국 위의 코드 중 프로그래머가 직접 작성하는 소스코드는 없는 셈이고 실제로 아무 소스파일을 불러오지 않아도 실행할 수 있다. 인터프리터의 실행 화면에서는


<syntaxhighlight lang="python" line="1">
?- write("Hello, world!").
Hello, World!
true.
</syntaxhighlight>

와 같은 식으로 표현된다. 첫번째 행의 ?- 뒤의 부분이 인터프리터에 입력하는 부분이다.

1.29 Python

  • 3.x 버전 이전

<syntaxhighlight lang="python" line="1">
print "Hello, World!"
</syntaxhighlight>

  • 3.x 버전 이후

<syntaxhighlight lang="python" line="1">
print("Hello, World!")
</syntaxhighlight>

1.30 Swift

<syntaxhighlight lang="python" line="1">
print("Hello, world!")
</syntaxhighlight>

1.31 TypeScript

<syntaxhighlight lang="python" line="1">
console.log('Hello, world');
</syntaxhighlight>

1.32 Racket

<syntaxhighlight lang="python" line="1">
(print "Hello, World!")
</syntaxhighlight>

1.33 Ruby

<syntaxhighlight lang="python" line="1">
puts "Hello, world!"
</syntaxhighlight>

1.34 Rust

<syntaxhighlight lang="python" line="1">
fn main() {
println!("Hello, world!");
}
</syntaxhighlight>

1.35 RGSS

<syntaxhighlight lang="python" line="1">
p "Hello, world!"
</syntaxhighlight>
또는


<syntaxhighlight lang="python" line="1">
print "Hello, world!"
</syntaxhighlight>

1.36 어셈블리어

어셈블리어는 운용되는 플랫폼과 어셈블러의 영향을 크게 받는다. 어차피 어셈블러에 표준 따위는 없기 때문에 모든 어셈블러나 시스템에 대한 코드를 추가하기는 어렵고, 아예 ISA가 다른 CPU들의 예제만 수록한다.

1.36.1 Intel x64, Mac OS X, NASM

<syntaxhighlight lang="python" line="1">
section .data
hello_world db "Hello, world!", 0x0a
section .textglobal _start

_start:
mov rax, 4mov rbx, 1mov rcx, hello_worldmov rdx, 14syscallmov rax, 1mov rbx, 0syscall
</syntaxhighlight>

1.36.2 PowerPC, Mac OS X, AS

.data
msg:
.string "Hello, world!\n"
len = . - msg

.text

.global _start
_start:

li      0,4
li      3,1
lis     4,msg@ha
addi    4,4,msg@l
li      5,len
sc

li      0,1
li      3,1
sc

1.37 Shell Script

<syntaxhighlight lang="python" line="1">

  1. !/bin/bash

echo "Hello World!"
</syntaxhighlight>

1.38 스크래치

스프라이트를 하나 만들고 이렇게 해주자
[[파일:/20150621_103/min08101_14348182358022owMo_PNG/%C1%A6%B8%F1_%BE%F8%C0%BD.png]]

1.39 VBA

<syntaxhighlight lang="python" line="1">
Private Sub CommandButton1_Click()
MsgBox "Hello, World!"
End Sub
</syntaxhighlight>

1.40 GML

오브젝트 한개를 만들고, draw이벤트에 코드를 넣고, 룸을 만들어 안에 오브젝트를 배치하자.

<syntaxhighlight lang="python" line="1">
draw_text(x,y,"Hello, World!");
</syntaxhighlight>

만약 젤 위에서 안나오고 이상한 곳에서 나온다면

<syntaxhighlight lang="python" line="1">
draw_text(0,0,"Hello World!");
</syntaxhighlight>

메세지 창을 통해 출력

<syntaxhighlight lang="python" line="1">
show_message("Hello World!")
</syntaxhighlight>

2 구구단

2.1 BASIC

FOR / NEXT 문을 적절히 활용한 예제 중 하나이다.

<syntaxhighlight lang="python" line="1">
10 FOR I = 2 T0 9
20 FOR J = 1 TO 9
30 PRINT I; "*"; J; "="; I * J
40 NEXT J
50 INPUT "Press Enter Key..."; A
60 NEXT I
</syntaxhighlight>

  • 50번 줄에 INPUT 문을 삽입한 이유는 한 줄씩 띄기 때문에 화면에 다 표시하지 못하기 때문이다. 적절히 고쳐 주면 2단부터 9단까지 화면에 다 표시되도록 할 수 있다.

2.2 C

<syntaxhighlight lang="python" line="1">

  1. include <stdio.h>

int main(void) {
int i, j;
for(i=2;i<=9;i++) {
for(j=1;j<=9;j++)
printf("%02d * %02d = %03d\n", i, j, i*j);
printf("\n");
}
return 0;
}
</syntaxhighlight>

while을 사용할 경우 다음과 같다.


<syntaxhighlight lang="python" line="1">

  1. include <stdio.h>

int main(void) {
int i, j;i=2;while(i<=9) {j=1;while(j<=9) {printf("%-2d * %-2d = %-3d\n", i, j, i*j);j++;
}i++;putchar('\n');
}return 0;
}
</syntaxhighlight>

2.3 C++

<syntaxhighlight lang="python" line="1">

  1. include <iostream>

int main() {
for(int i = 2; i <= 9; i++) {
for(int j = 1; j <= 9; j++) {
std::cout << i << " * " << j << " = " << i * j << std::endl;
}
std::cout << std::endl;
}

return 0;
}
</syntaxhighlight>

2.4 C\#

<syntaxhighlight lang="python" line="1">
using System;

namespace foo
{
class foo{static void Main(string[] args){for (int i = 2; i<10; i++){for (int f = 1; f<10; f++){Console.WriteLine("{0} * {1} = {2}",i,f,i*f);
}
}
}
}
}
</syntaxhighlight>

2.5 Clojure

(for [x (range 2 10)]
(for [y (range 1 10)]
(println x " x " y " = " (* x y))))

2.6 D

import std.stdio;
void main()
{
foreach(i ; 2..10)
foreach(j ; 1..10)
writeln(i, " x ", j, " = ", i * j);
}

2.7 FORTH

<syntaxhighlight lang="python" line="1">
PRINTTABLE
9
0 DO
DUP . ( 단 수 출력 )." * " ( '*' 출력 )I 1 + . ( i + 1 출력 )." = " ( '=' 출력 )DUP I 1 + * . ( n * ++i 출력 )CR
LOOP ;

PRINTFOR ( n -- )
1 DO
I 1 + PRINTTABLE ( i + 1 -- )
DROP CR
LOOP ;

9 PRINTFOR
</syntaxhighlight>

2.8 FORTRAN 77

<syntaxhighlight lang="python" line="1">
PROGRAM NINEIMPLICIT NONEINTEGER IINTEGER JINTEGER GG(8,8)


DO 10 I=2,9DO 20 J=2,9GG(I-1,J-1)=I*J20 CONTINUE10 CONTINUEDO 30 I=1,8PRINT 300, (GG(I,J), J=1,8)30 CONTINUE300 FORMAT (8(I4))END PROGRAM NINE
</syntaxhighlight>

2.9 Java

<syntaxhighlight lang="python" line="1">
public class Foo {
public static void main(String[] args) {
for(int a = 2; a < 10; a ++) {
for (int b = 1; b < 10; b++) {
System.out.println(a +" * " + b + " = " + a*b);
}
}
}
}
</syntaxhighlight>

2.10 JavaScript

<syntaxhighlight lang="javascript" line="1">
for(var i = 2; i <= 9; i++)
for(var j = 1; j <= 9; j++)console.log(i + " * " + j + " = " + i * j);

</syntaxhighlight>

또는


<syntaxhighlight lang="javascript" line="1">
[2, 3, 4, 5, 6, 7, 8, 9].forEach(function(i) {
[1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(function(j) {console.log(i + " * " + j + " = " + (i * j));
});
});
</syntaxhighlight>

ECMAScript 2015


<syntaxhighlight lang="python" line="1">
[2, 3, 4, 5, 6, 7, 8, 9].forEach((i) => {
[1, 2, 3, 4, 5, 6, 7, 8, 9].forEach((j) => {console.log(`${i} * ${j} = ${i * j}`);
});
});
</syntaxhighlight>

2.11 LISP

<syntaxhighlight lang="python" line="1">
(loop for i from 2 to 9 do
(loop for j from 2 to 9 do (princ (format nil "~D * ~D = ~D~%" i j (* i j)))))

</syntaxhighlight>

2.12 Lua

<syntaxhighlight lang="python" line="1">
for i = 2, 9, 1 do
for j = 1, 9, 1 doprint(i .. " * " .. j .. " = " .. i * j)
endprint("")
end
</syntaxhighlight>

2.13 PHP

<syntaxhighlight lang="python" line="1">
<?php
for ($i = 2; $i <= 9; $i++)for ($j = 1; $j <= 9; $j++) echo $i." * ".$j." = ".($i*$j)."
";


?>
</syntaxhighlight>

2.14 Python

2.14.1 Python 2.x

<syntaxhighlight lang="python" line="1">
for i in range(2, 10):
for j in range(1, 10):print i, "*", j, "=", i * j

</syntaxhighlight>

2.14.2 Python 3.x

<syntaxhighlight lang="python" line="1">
_ = list(eval(r"print(x*y, end = ('\n' if y == 9 else ' '))") for x in range(1,10) for y in range(1,10))
</syntaxhighlight>[2] 도 가능
또는

<syntaxhighlight lang="python" line="1">
_ = list(print(str(x),'*',str(y),'=',str(x*y)) for x in range(1,10) for y in range(1,10))
</syntaxhighlight>

2.15 Swift

<syntaxhighlight lang="python" line="1">
for a in 2...9{
for b in 1..<10 {print("\(a) * \(b) = \(a*b)")
}
}
</syntaxhighlight>

2.16 Ruby

<syntaxhighlight lang="python" line="1">
2.upto(9){|i| 1.upto(9){|j| puts "#{i}X#{j}=#{i*j} "}}
</syntaxhighlight>

또는


<syntaxhighlight lang="python" line="1">
(2..9).each{|i| (1..9).each{|j| puts "#{i}X#{j}=#{i*j}"}}
</syntaxhighlight>

3 삼각형 그리기

3.1 BASIC

FOR / NEXT 문을 적절히 활용한 예제 중 하나이다.

<syntaxhighlight lang="python" line="1">
10 FOR I = 1 TO 20
20 PRINT SPC(20-I);
30 FOR J = 1 TO I*2
40 PRINT "*";
50 NEXT J
60 PRINT
70 NEXT I
</syntaxhighlight>

3.2 C

<syntaxhighlight lang="python" line="1">

  1. include <stdio.h>

int main(int argc, const char * argv[]) {
int i,j;
for(i=1;i<20;i++){
for(j=1;j<i+1;j++)
printf("*");
puts("");
}
return 0;
}
</syntaxhighlight>

3.3 FORTH

<syntaxhighlight lang="python" line="1">
STARS 0 DO 42 42 EMIT EMIT LOOP ;NAMUSTARS 0 DO I 1 + STARS CR LOOP ;

20 NAMUSTARS
</syntaxhighlight>

3.4 Java

<syntaxhighlight lang="python" line="1">
public class namu {
public static void main(String[] args){
for(int a = 1; a < 20; a ++) {
for (int b = 0; b < a+1; b++) {
System.out.print("*");
}
System.out.println("");
}
}
}
</syntaxhighlight>

3.5 JavaScript

<syntaxhighlight lang="python" line="1">
var star = "";
for(var a = 1; a < 20; a++)
for(var b = 0; b < a * 2; b++)console.log(star += "*");

</syntaxhighlight>

3.6 Lua

<syntaxhighlight lang="python" line="1">
for i = 1, 20, 1 do
for j = 1, i * 2, 1 doio.write("*")
endio.write("\n")
end
</syntaxhighlight>

3.7 PHP

<syntaxhighlight lang="python" line="1">
<?
$a = array();
for ($i=0; $i< 20; $i++){
$a[$i] = implode("",array_fill(0,($i+1),"*"));
}
?><?=implode("
",$a)?>
</syntaxhighlight>
위의 $a = array();는 생략해도 된다.

3.8 Processing

<syntaxhighlight lang="python" line="1">
triangle(50, 10, 10, 90, 90, 90);
</syntaxhighlight>
다른 예제와는 달리 별표를 이용해 삼각형을 찍는 것이 아닌 창에 정상적인(?) 삼각형을 그리는 예제.
다른 언어의 예제처럼 콘솔에 삼각형 모양으로 별표를 찍는 예제를 원한다면 위의 Java 쪽 예제를 보자.[3]

3.9 Python

<syntaxhighlight lang="python" line="1">
star = ""
for a in range(1, 20):
for b in range(1, 2*a):star+= "*"print( star )

</syntaxhighlight>
또는

<syntaxhighlight lang="python" line="1">
print('\n'.join(('*'*(2*y-1) for y in range(1,20))))
</syntaxhighlight>

3.10 Swift

<syntaxhighlight lang="python" line="1">
for(var a = 1; a < 20; a++) {
for (var b = 0; b < a+1; b++) {print("*", terminator:"");
}print("");
}
</syntaxhighlight>

3.11 Ruby

<syntaxhighlight lang="python" line="1">
(1..20).each{|i| puts '*' * (i*2)}
</syntaxhighlight>

위의 것의 좌우반전

<syntaxhighlight lang="python" line="1">
(1..20).each{|i|
puts ' ' * (20 - i) + '*' * (i * 2 - 1)
}
</syntaxhighlight>

4 99병의 맥주

Hello, world!와 더불어 가장 유명한 코드 예제. 제어문을 배울때 사용된다.

4.1 BASIC

<syntaxhighlight lang="python" line="1">
10 CLS
20 FOR I = 99 TO 1 STEP -1
30 MODE = 1: GOSUB 110
40 PRINT I; "bottle" + BOTTLES$ + " of beer on the wall,"; i; "bottle" + BOTTLES$ + " of beer."
50 MODE = 2: GOSUB 110
60 PRINT " Take one down and pass it around,"; i-1; "bottle" + BOTTLES$ + " of beer on the wall."
70 NEXT
80 PRINT " No more bottles of beer on the wall, no more bottles of beer."
90 PRINT " Go to the store and buy some more. 99 bottles of beer."
100 END
110 IF I = MODE THEN BOTTLES$ = "" ELSE BOTTLES$ = "s"
120 RETURN
</syntaxhighlight>

4.2 C

<syntaxhighlight lang="python" line="1">

  1. include <stdio.h>

int main(void)
{
int b;
for (b = 99; b >= 0; b--)
{
switch (b)
{
case 0:
printf("No more bottles of beer on the wall, no more bottles of beer.\n");
printf("Go to the store and buy some more, 99 bottles of beer on the wall.\n");
break;
case 1:
printf("1 bottle of beer on the wall, 1 bottle of beer.\n");
printf("Take one down and pass it around, no more bottles of beer on the wall\n");
break;
default:
printf("%d bottles of beer on the wall, %d bottles of beer.\n", b, b);
printf("Take one down and pass it around, %d %s of beer on the wall.\n",b - 1,((b - 1) > 1)? "bottles" : "bottle");
break;
}
}
return 0;
}
</syntaxhighlight>

4.3 Clojure

<syntaxhighlight lang="python" line="1">
(defn rcount [n] (lazy-seq (cons n (rcount (dec n)))))

(for [n (take 100 (rcount 99))]
(cond(= n 0)(do(println "No more bottles of beer on the wall, no more bottles of beer.")(println "Go to the store and buy some more, 99 bottles of beer on the wall."))

(= n 1)(do(println "1 bottle of beer on the wall, 1 bottle of beer.")(println "Take one down and pass it around, no more bottles of beer on the wall."))

(= n 2)(do(println "2 bottles of beer on the wall, 2 bottles of beer.")(println "Take one down and pass it around, 1 bottle of beer on the wall."))
else(do(println n " bottles of beer on the wall, " n " bottles of beer.")(println "Take one down and pass it around, " (dec n) " bottles of beer on the wall."))))

</syntaxhighlight>

4.4 Erlang

<syntaxhighlight lang="python" line="1">
-module(bottles).
-export([nintynine_bottles/0]).

nintynine_bottles() ->
bottles(99).

bottles(0) ->
io:fwrite("No more bottles of beer on the wall, no more bottles of beer.~n"),io:fwrite("Go to the store and buy some more, 99 bottles of beer on the wall.~n");
bottles(1) ->
io:fwrite("1 bottle of beer on the wall, 1 bottle of beer.~n"),io:fwrite("Take one down and pass it around, no more bottles of beer on the wall.~n"),bottles(0);
bottles(2) ->
io:fwrite("2 bottles of beer on the wall, 2 bottles of beer.~n"),io:fwrite("Take one down and pass it around, 1 bottle of beer on the wall.~n"),bottles(1);
bottles(N) ->
io:fwrite("~b bottles of beer on the wall, ~b bottles of beer.~n", [N, N]),io:fwrite("Take one down and pass it around, ~b bottles of beer on the wall.~n", [N - 1]),bottles(N - 1).
</syntaxhighlight>

4.5 FORTH

<syntaxhighlight lang="python" line="1">
BEERCNT DUP 1 = IF DUP . ." BOTTLE OF BEER" ELSE ( 스택 꼭대기에 든 값이 1일때 )DUP 0 = IF ." NO MORE BOTTLES OF BEER" ELSE ( 스택 꼭대기에 든 값이 0일때 )DUP . ." BOTTLES OF BEER" ( 둘 다 아닐 때 )
THEN THEN ;
ONDAWALL ." ON THE WALL" ;PERIOD 46 EMIT ;OFBEER ." , " BEERCNT PERIOD ;VERSEONE BEERCNT ONDAWALL OFBEER CR ;

TAKEONE ." TAKE ONE DOWN AND PASS IT AROUND, " 1 - BEERCNT ONDAWALL PERIOD ;VERSETWO TAKEONE CR ;

VERSETWOZERO ." GO TO THE STORE AND BUY SOME MORE, " 99 BEERCNT ONDAWALL PERIOD CR ;

VERSES DUP 0 DO VERSEONE VERSETWO CR LOOP VERSEONE VERSETWOZERO ;

99 VERSES
</syntaxhighlight>

4.6 Fortran 90

<syntaxhighlight lang="python" line="1">
program namu99beers
implicit none

integer :: i

do i = 99, 0, -1
select case (i)
case (0)
write(*,*) 'No more bottles of beer on the wall, no more bottles of beer.'
write(*,*) 'Go to the store and buy some more, 99 bottles of beer on the wall.'
case (1)
write(*,*) '1 bottle of beer on the wall, 1 bottle of beer.'
write(*,*) 'Take one down and pass it around, no more bottles of beer on the wall.'
case (2)
write(*,*) i, 'bottles of beer on the wall, ', i, 'bottles of beer.'
write(*,*) 'Take one down and pass it around, 1 bottle of beer on the wall.'
case default
write(*,*) i, 'bottles of beer on the wall, ', i, 'bottles of beer.'
write(*,*) 'Take one down and pass it around, ', i - 1, 'bottles of beer on the wall.'
end select

write(*,*)
end do
end program

</syntaxhighlight>

4.7 Java

<syntaxhighlight lang="python" line="1">
class NinetyNineBottles{
public static void main(String[] args){
for(int i = 99; i >= 0; i--){
switch(i){
case 0:
System.out.println("'No more bottles of beer on the wall, no more bottles of beer." );
System.out.println("Go to the store and buy some more, 99 bottles of beer on the wall.");
break;
case 1:
System.out.println(i + "bottle of beer on the wall, " + i + "bottle of beer.");
System.out.println("Take one down and pass it around, no more bottles of beer on the wall.");
break;case 2:System.out.println(i + "bottles of beer on the wall, " + i + "bottles of beer.");
System.out.println("Take one down and pass it around, 1 bottle of beer on the wall.");
break;
default:
System.out.println(i + "bottles of beer on the wall, " + i + "bottles of beer.");
System.out.println("Take one down and pass it around, " + (i-1) + "bottles of beer on the wall.");
}
}
}
}
</syntaxhighlight>

4.8 Kotlin

<syntaxhighlight lang="python" line="1">
fun main(args: Array<String>) {
((99 downTo 0).map { verse(it) }).forEach { println(it) }
}

fun verse(n: Int): String {
return when (n) {0 -> """${n.bottles()} of beer on the wall, ${n.bottles()} of beer.

Go to the store and buy some more, ${99.bottles()} of beer on the wall.
"""
else -> """${n.bottles()} of beer on the wall, ${n.bottles()} of beer.
Take one down and pass it around, ${(n - 1).bottles()} of beer on the wall.
"""
}
}

fun Int.bottles(): String {
return when (this) {0 -> "No more bottles"1 -> "1 bottle"else -> "$this bottles"
}
}
</syntaxhighlight>

람다 식과 확장함수를 사용해 최대한 코틀린스럽게 작성한 코드이다. 더 줄일 수는 있지만 알아보기 좋게 이대로 둔다.

4.9 LabVIEW

[1]

4.10 Lua

<syntaxhighlight lang="python" line="1">
for i = 99, 0, -1 do
if i == 0 then
print("No more bottles of beer on the wall, no more bottles of beer.")
print("Go to the store and buy some more, 99 bottles of beer on the wall.")
elseif i == 1 then
print("1 bottle of beer on the wall, 1 bottle of beer.")
print("Take one down and pass it around, no more bottles of beer on the wall")
elseif i == 2 then
print(i .. " bottles of beer on the wall, " .. i .. " bottles of beer.")
print("Take one down and pass it around, 1 bottle of beer on the wall.")
else
print(i .. " bottles of beer on the wall, " .. i .. " bottles of beer.")
print("Take one down and pass it around, " .. i - 1 .. " bottles of beer on the wall.")
end
print("")
end
</syntaxhighlight>

4.11 Python

<syntaxhighlight lang="python" line="1">
for i in range(99, -1, -1):
if i == 0 :
print("No more bottles of beer on the wall, no more bottles of beer.")
print("Go to the store and buy some more, 99 bottles of beer on the wall.")
elif i == 1 :
print("1 bottle of beer on the wall, 1 bottle of beer.")
print("Take one down and pass it around, no more bottles of beer on the wall")
elif i == 2 :
print(str(i) + " bottles of beer on the wall, " + str(i) + " bottles of beer.")
print("Take one down and pass it around, 1 bottle of beer on the wall.")
else :
print(str(i) + " bottles of beer on the wall, " + str(i) + " bottles of beer.")
print("Take one down and pass it around, " + str(i - 1) + " bottles of beer on the wall.")

print("")
</syntaxhighlight>

보다시피 range문은 argument를 세 개 먹는데, 이를 이용해 C 스타일 for문을 range문으로 바꿀 수 있다.

4.12 PHP

<syntaxhighlight lang="python" line="1">
<?
for($i=99;$i>=0;$i--){
if($i==0){
echo "No more bottles of beer on the wall, no more bottles of beer.
";
echo "Go to the store and buy some more, 99 bottles of beer on the wall.
";
}else if($i==1){
echo "1 bottle of beer on the wall, 1 bottle of beer.
";
echo "Take one down and pass it around, no more bottles of beer on the wall.
";
}else{
echo $i." bottles of beer on the wall, ".$i." bottles of beer.
";
echo "Take one down and pass it around, ".($i-1)." bottles of beer on the wall.
";
}
}
?>
</syntaxhighlight>

4.13 HQ9+

9

실제로 한 글자다. 이유는 해당 항목 참고.

4.14 Swift

<syntaxhighlight lang="python" line="1">
for var i = 99; i >= 0; i-- {
switch(i) {case 0:print("'No more bottles of beer on the wall, no more bottles of beer." )print("Go to the store and buy some more, 99 bottles of beer on the wall.")
case 1:print("\(i)bottles of beer on the wall, \(i)bottles of beer on the wall")print("Take one down and pass it around, no more bottles of beer on the wall.")
case 2:print("\(i)bottles of beer on the wall, \(i)bottles of beer on the wall")print("Take one down and pass it around, 1 bottle of beer on the wall.")
default:print("\(i)bottles of beer on the wall, \(i)bottles of beer.")print("Take one down and pass it around, \(i-1) bottles of beer on the wall.");
}
}
</syntaxhighlight>

5 1부터 N까지 출력

임의의 숫자 N을 입력받아 1 부터 N 까지의 모든 숫자를 출력한다.

5.1 C

<syntaxhighlight lang="python" line="1">

  1. include <stdio.h>

int main(void) {
int n = 0, i = 0;
scanf("%d",&n);
for(i = 1; i <= n; i++)
printf("%d \n", i);
return 0;
}
</syntaxhighlight>

5.2 Clojure

<syntaxhighlight lang="python" line="1">
(defn read-int []
(Integer/parseInt (read-line)))

(for [i (range 1 (inc (read-int)))]
(println i))
</syntaxhighlight>

5.3 D

<syntaxhighlight lang="python" line="1">
import std.stdio, std.conv, std.string;
void main()
{
foreach(i; 0..readln.strip.to!int + 1)writeln(i);

}
</syntaxhighlight>
D는 UFCS라는 문법을 사용하여 함수간 연계 호출을 간결하게 한다.
N을 입력받는 문장은 C스타일로 치면 다음과 같이 재해석할수 있다.

<syntaxhighlight lang="python" line="1">
to ! int ( strip ( readln() ) )
</syntaxhighlight>

5.4 Erlang

<syntaxhighlight lang="python" line="1">
-module(n_writer).
-export([write/1]).

write(N) ->
lists:foreach(fun(T) -> io:format("~p~n", [T]) end, lists:seq(1, N)).
</syntaxhighlight>

5.5 Java

<syntaxhighlight lang="python" line="1">
import java.util.Scanner;

public class Printer {
public static void main(String[] args){try(Scanner scanner = new Scanner(System.in)){int n = scanner.nextInt();for(int i = 1; i <= n; i++){System.out.println(i);
}
}
}
}
</syntaxhighlight>

5.6 JavaScript

<syntaxhighlight lang="python" line="1">
var n = parseInt(prompt("n을 입력해 주십시오."), 10);
for (var i = 1; i <= n; i++) console.log(i);
</syntaxhighlight>

5.7 Lua

<syntaxhighlight lang="python" line="1">
n = io.read()
for i = 1, n do
print(i)
end
</syntaxhighlight>
한 줄 짜리

<syntaxhighlight lang="python" line="1">
for i = 1, io.read() do print(i) end
</syntaxhighlight>

5.8 LISP

Common Lisp으로 작성됨.

<syntaxhighlight lang="python" line="1">
(let ( (n (parse-integer (read-line))) )
(loop for x from 1 to n do(print x)))

</syntaxhighlight>

5.9 Perl

<syntaxhighlight lang="python" line="1">

  1. !/usr/bin/env perl

my $i = <STDIN>;
chomp $i;
print "$_\n" for 1 .. $i;
</syntaxhighlight>

5.10 Python

<syntaxhighlight lang="python" line="1">
for x in range(int(input("n을 입력해 주십시오: "))):
print(x+1)
</syntaxhighlight>
또는

<syntaxhighlight lang="python" line="1">
_ = list(print(x+1) for x in range(int(input("n을 입력해 주십시오: "))))
</syntaxhighlight>
파이썬은 이렇게 아름답습니다 여러분!!!

5.11 PHP

<syntaxhighlight lang="python" line="1">
<?
$n = 15; //임의의 값이 15라고 가정
for( $i = 1; $i <= $n; $i++){echo $i."
";}
?>
</syntaxhighlight>

5.12 Swift

<syntaxhighlight lang="python" line="1">
//콘솔에서 입력을 받기위한 메소드이다.
func input() -> String {
let keyboard = NSFileHandle.fileHandleWithStandardInput()let inputData = keyboard.availableDatalet rawString = NSString(data: inputData, encoding:NSUTF8StringEncoding)if let string = rawString {return string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
} else {return "Invalid input"
}
}

let n = Int(input())
for i in 1...n! {
print(i)
}

</syntaxhighlight>

5.13 Ruby

<syntaxhighlight lang="python" line="1">

  1. 방법 1

print (1..gets.to_i).to_a.join(' ')
</syntaxhighlight>

<syntaxhighlight lang="python" line="1">

  1. 방법 2, Ruby Range 레퍼런스의 예제로 있는 방식이다.

(1..gets.to_i).each{|i|print i,' '}
</syntaxhighlight>
루비가 훨씬 더 아름답고 간결하다!

5.14 Rust

<syntaxhighlight lang="python" line="1">
use std::io;

fn main() {
let mut input = String::new();

io::stdin().read_line(&mut input).ok().expect("fail to read");


let n: u32 = input.trim().parse().ok().expect("this is not a number");


for i in 1..n+1 {println!("{}", i);
}
}
</syntaxhighlight>

간단한 방법을 찾아왔다
  1. 가장 최근 쓰이는 표준
  2. [*(eval(r"print(x*y, end = ('\n' if y == 9 else ' '))") for x in range(1,10) for y in range(1,10))]
  3. Processing은 Java 기반이기 때문에 코드가 거의 완전히 호환된다.