최근 수정 시각 : 2024-03-29 05:48:23

프로그래밍 언어/예제

파일:상위 문서 아이콘.svg   상위 문서: 프로그래밍 언어
프로그래밍 언어 문법
{{{#!wiki style="margin: -16px -11px; word-break: keep-all" <colbgcolor=#0095c7><colcolor=#fff,#000> 언어 문법 C( 포인터) · C++( 자료형 · 특성 · 클래스 · 이름공간 · 상수 표현식) · C# · Java · Python · Kotlin · MATLAB · SQL · PHP · JavaScript
마크업 문법 HTML · CSS
개념과 용어 함수 · 인라인 함수 · 고차 함수 · 람다식 · 리터럴 · size_t · 상속 · 예외 · 조건문 · 참조에 의한 호출 · eval
기타 == · === · NaN · null · undefined · 모나드 · 배커스-나우르 표기법
프로그래밍 언어 예제 · 목록 · 분류 }}}

[ 목차 펼치기 · 접기 ]
1. 개요2. Hello, world!3. 구구단4. 삼각형 그리기5. 99병의 맥주6. 1부터 N까지 출력

1. 개요

* 수록 순서를 변경하지 마십시오.
* 문서는 예제의 종류를 대분류로 하여, 프로그래밍 언어를 알파벳, 가나다 순으로 정렬하여 주십시오.
* 예제의 종류는 Hello World, 구구단, 삼각형 그리기, 99병의 맥주, 1부터 N까지 출력 순서를 유지하여 주십시오.
* 난해한 언어의 예제는 프로그래밍 언어/예제/난해한 프로그래밍 언어 문서에 추가해 주십시오.
* 이해하기 쉽고 간단한 코드예제로 작성해 주십시오.
* 복잡한 연산이나 라이브러리를 사용하지 마십시오.
* 원라이너 등 코드의 가독성을 해칠 수 있는 예제를 수록하지 마십시오.
이 문서는 컴퓨터 프로그래밍 언어로 구현한 몇 가지 코드들의 예제이다. 전통있는 컴퓨터공학과 1학년 1학기 과제들이다.

2. Hello, world!

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

2.1. ABAP

#!syntax python
* 창 자체에 문자로 출력
write 'Hello, world!'.

* 상태표시줄에 띄우기
MESSAGE 'Hello, world!' TYPE 'S' DISPLAY LIKE 'W'.

2.2. ActionScript

2.2.1. 2.0

#!syntax java
trace("Hello, World!");

2.2.2. 3.0

#!syntax java
package {
    public class HelloWorld extends Sprite {

        public function HelloWorld():void {
            trace("Hello, World!");
        }
    }
}

2.3. Arduino

#!syntax cpp
void setup() {
    Serial.begin(9600);
    Serial.println("Hello, World!");
}

void loop() {

} 

2.4. AutoHotkey

#!syntax python
Msgbox, Hello world!

2.5. BASIC

#!syntax basic
10 PRINT "Hello, World!"
20 END
RUN

2.6. C

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

(K&R 기준)

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


(C99 기준)[1]
#!syntax cpp
#include <stdio.h>

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


(C11)[2]
#!syntax cpp
#include <stdio.h>

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


또는

#!syntax cpp
#include <stdio.h>

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

2.7. C++

C언어와 유사하지만 출력을 위해 C++의 스트림 객체를 사용한다.
#!syntax cpp
#include <iostream>

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


또는

#!syntax cpp
#include <iostream>

using namespace std;

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

2.8. C#

#!syntax csharp
using System;

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


C# 9.0부터 최상위 문을 지원하여 아래와 같이 해도 된다.
#!syntax csharp
using System;
Console.WriteLine("Hello, world!");

#!syntax csharp
System.Console.WriteLine("Hello, World!");


C# 10.0부터 implicit global using을 지원하여 아래와 같이 해도 된다.
#!syntax csharp
Console.WriteLine("Hello, world!");

2.9. Classic ASP

#!syntax python
<%
    Response.Write("Hello, world!")
%>

2.10. Clojure

#!syntax python
(println "Hello, world!")

2.11. COBOL

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

2.12. CUDA

#!syntax cpp
#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;
}



로우레벨 프로그래밍의 멋진(...)예시!
CUDA로 이런걸 왜 짜는거야
다만, 위 예제는 CUDA 라이브러리를 쓰기 위해서 억지로 꼬아놓은 코드다. 그냥 C의 Hello, world를 넣어도 상관 없다.

2.13. D

#!syntax java
import std.stdio;

void main()
{
    writeln("Hello, world!");
}

2.14. Dart

#!syntax java
void main() {
  print('Hello, World!');
}

2.15. Elm

#!syntax typescript
import Html exposing (Html, text)
import Browser 

type alias Model = 
  String

type Msg =
  None

update : Msg -> Model -> Model
update msg model = 
  case msg of
    None -> model

view : Model -> Html msg
view model =
  text model

main : Program () Model Msg
main =
  Browser.sandbox
    { init = "Hello world!"
    , update = update
    , view = view
    }
Elm 언어는 하스켈스러운 문법을 지녔지만 자바스크립트(?) 를 결과물로 내놓는 함수형 언어이다. 위 코드는 단순히 웹브라우저에 "Hello, world!"를 출력할 뿐이지만, 웹페이지의 초기값("Hello, world!")이 입력된(init) Model을 Msg(여기서는 None 하나밖에 없긴 하지만)에 따라 업데이트(update)하고 이를 화면에 실시간으로 출력(view)하는 Model, Update, View 패턴에 따라 작성되었다. 사실 다음과 같이 작성해도 조건은 충족하나, Elm이 어떤 언어인지 잘 알 수 없는 예시다.

#!syntax typescript
import Html exposing (text)

main = text "Hello, world!"

2.16. emojicode

🏁 🍇
  😀 🔤Hello, World!🔤❗️
🍉

2.17. Erlang

#!syntax erlang
-module(hello).
-export([hello_world/0]).

hello_world() -> io:fwrite("hello, world\n").

2.18. Forth

." Hello, world!"

2.19. FORTRAN

#!syntax python
program
         Print *, "Hello, world!"
     End


또는

#!syntax python
PROGRAM MAIN
         WRITE(*,*) "Hello, world!"
END

2.20. GML

오브젝트 한개를 만들고, draw이벤트에 코드를 넣고, 룸을 만들어 안에 오브젝트를 배치하자.
#!syntax python
draw_text(x,y,"Hello, World!");


만약 젤 위에서 안나오고 이상한 곳에서 나온다면
#!syntax python
draw_text(0,0,"Hello World!");


메시지 창을 통해 출력
#!syntax python
show_message("Hello World!")

2.21. Go

#!syntax go
package main

import "fmt"

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

2.22. Haskell

#!syntax typescript
main :: IO ()
main = putStrLn "Hello, world!"

2.23. IDL

PRO main
    print, "Hello, world!" 
END

2.24. Idris2

#!syntax typescript
main : IO ()
main = putStrLn "Hello, world!"

2.25. Java

#!syntax java
public class NamuWiki {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}
[3]

2.26. JavaScript

웹 페이지로 출력
#!syntax javascript
document.write("Hello, world!");


브라우저 경고 창으로 출력
#!syntax javascript
alert("Hello, world!");


터미널이나 브라우저의 콘솔로 출력
#!syntax javascript
console.log("Hello, world!");


HTTP로 출력
#!syntax javascript
const http = require('http');
http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello, World!\n');
}).listen(8080, '127.0.0.1');

2.27. JSP

#!syntax python
<%
    out.println ("Hello, World!");
%>

2.28. Julia

#!syntax php
println("Hello, world!")

2.29. Kotlin

#!syntax kotlin
fun main() {
    println("Hello, world!")
}
[4]

2.30. LabVIEW

파일:external/habrastorage.org/7fed2cf9f0903de17482a35bcdf3494c.png
위쪽 창이 프로그램 코드, 아래쪽 창이 인터페이스.

러시아어는 무시하자

2.31. LISP

#!syntax python
(print "Hello, World!")

2.32. Lua

#!syntax lua
print("Hello, world!")

2.33. Objective-C

#!syntax objectivec
#import <Foundation/Foundation.h>

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

2.34. Pascal

#!syntax ruby
Program Hello;

begin
    writeln('Hello, world!')
end.

2.35. Perl

#!syntax perl
print "Hello, World!\n";


say를 사용하면 \\n을 넣어주지 않아도 된다.

#!syntax perl
say "Hello, World!";

2.36. PHP

#!syntax php
<?php
    echo ("Hello, World!");
?>


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

#!syntax php
<?="Hello, World!" ?>


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

2.37. Processing

#!syntax java
println("Hello, world!");


하지만 아래와 같이 쓰는 것이 프로세싱의 look&feel을 살리는 예제라고 한다. ( 위키피디아에서 전재)
#!syntax java
void setup() {
    PFont font = loadFont("myfont.vlw");
    textFont(font,20);
}
 
void draw() {
    text("Hello, world!", 30,50);
}


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

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

2.38. Prolog

#!syntax python
write("Hello, World!").


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

#!syntax python
?- write("Hello, world!").
Hello, World!
true.


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

2.39. Python

2.39.1. Python 2

#!syntax python
print "Hello, World!"

2.39.2. Python 3

#!syntax python
print("Hello, World!")


참고로, 파이썬에는 이와 관련된 이스터 에그가 존재한다.
#!syntax python
import __hello__ #Hello world!

다만 이는 콤마가 없고 w가 소문자이다.

2.40. Racket

#!syntax python
(print "Hello, World!")

2.41. Ren'Py

#!syntax ruby
"Hello, world!"


2.42. RGSS


#!syntax python
p "Hello, world!"

또는

#!syntax python
print "Hello, world!"

2.43. Ruby

#!syntax ruby
puts "Hello, world!"

2.44. Rust

#!syntax rust
fn main() {
    println!("Hello, world!");
}

2.45. Scala

#!syntax java
println("Hello, world!")

2.46. SQL

#!syntax sql
SELECT 'Hello, world!';

오라클 데이터베이스는 모든 쿼리에 FROM이 강제되므로, 아래처럼 입력해야 한다.
#!syntax sql
SELECT 'Hello, world!' FROM DUAL;

2.47. 스크래치

스프라이트를 하나 만들고 이렇게 해주자.
파일:스크래치2헬로우월드.png 파일:스크래치3헬로우월드!.png
스크래치 2.0 스크래치 3.0

스크래치 2.0과 3.0은 펜이나 연산 블럭의 추가/수정 등이 있지만, Hello, World!의 출력에선 그래픽 변경 외의 차이점은 없다.

2.48. 명령 프롬프트/ MS-DOS/ PowerShell

#!syntax python
echo hello world

2.49. Shell Script, sh

리눅스/유닉스 시스템에서 사용하는 명령프롬프트 실행파일
#!syntax python
#!/bin/bash

echo "Hello World!"

2.50. Small Basic

#!syntax python
TextWindow.WriteLine("Hello, world!")

2.51. Swift

2.51.1. Swift 1.0

#!syntax swift
println("Hello, world!")

2.51.2. Swift 2.0 이후

#!syntax swift
print("Hello, world!")

2.52. TensorFlow

#!syntax python
import tensorflow as tf

hello = tf.constant('Hello, world!')
sess = tf.Session()
print sess.run(hello)


텐서플로 기계학습을 위해 변수보다는 텐서를 다루는데 최적화되어 있는 오픈소스 라이브러리이다. 그렇기 때문에 변수가 아니라 텐서로 출력한다! 어쨌든 파이썬이다

2.53. TypeScript

#!syntax typescript
const hello = (name: string) => `Hello, ${name}`

console.log(hello('World')); // Hello, World

2.54. VBA 또는 Visual Basic 6 이하

단추를 추가하고, 이름을 CommandButton1로 해준다. 해당 단추를 누르면 메시지 상자가 나온다.

#!syntax python
Private Sub CommandButton1_Click()
     MsgBox "Hello, World!"
End Sub

2.55. Visual Basic .NET

#!syntax python
Public Class Form1
    Private Sub button1_click
        Msgbox("Hello, World!")
    End Sub
End Class

콘솔이라면 이렇게.
#!syntax python
Module Hello

    Sub Main()
        Console.Writeline("Hello, World!")
    End Sub

End module

2.56. 어셈블리어

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

2.56.1. Intel x86/AMD64(x64), Mac OS X, NASM

#!syntax python
        section .data
hello_world     db      "Hello, world!", 0x0a
 
        section .text
        global _start
 
_start:
        mov rax, 4
        mov rbx, 1
        mov rcx, hello_world
        mov rdx, 14
        syscall
        mov rax, 1
        mov rbx, 0
        syscall

2.56.2. PowerPC, Mac OS X, AS

#!syntax python
.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

3. 구구단

3.1. ActionScript

FOR문을 활용한 예제
#!syntax javascript
for( var i = 1; i <= 9; i++ )
{
    trace( i + "단" );
    
    for( var j = 1; j <= 9; j++ )
    {
        trace( i + "x" + j + "=" + i*j );
    }
}

3.2. APL

Dyalog APL을 기준으로 한다.
∘.{⍺'×'⍵'=',⍺×⍵}⍨⍳9
APL IDE에서 실행하면 깔끔한 9×9 형태의 표로 출력해 준다.

또한 아래는 n×n 크기의 곱셈표를 출력시키는 함수이다.
Multiple←∘.{⍺'×'⍵'=',⍺×⍵}⍨⍳
이후 Multiple n (n ∈ ℤ)로 함수를 호출할 수 있다.

3.3. AutoHotKey

#!syntax python
a := 0 
b := 1 
Loop, 9
{ 
    b++ 
    Loop, 9 
    { 
        a++ 
        c := a * b 
        d .= b " x " a " = " c "`n" 
    } 
    a := 0 
    Msgbox, % d 
    d := "" 
} 
Exitapp

3.4. Bash

#!syntax python
#!/bin/bash

for ((i=2; i<10; i++)); do
    for ((j=1; j<10; j++)); do
        echo "$i * $j = $((i*j))"
    done
    echo
done

3.5. BASIC

FOR / NEXT 문을 적절히 활용한 예제 중 하나다.
#!syntax basic
10 FOR I = 2 TO 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
  • 50번 줄에 INPUT 문을 삽입한 이유는 한 줄씩 띄기 때문에 화면에 다 표시하지 못하기 때문이다. 적절히 고쳐 주면 2단부터 9단까지 화면에 다 표시되도록 할 수 있다.

3.6. C

#!syntax cpp
#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;
}


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

#!syntax cpp
#include <stdio.h>

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

3.7. C++

#!syntax cpp
#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;
}

3.8. C#

#!syntax csharp
using System;

namespace Namuwiki
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 2; i <= 9; i++)
            {
                for (int j = 1; j <= 9; j++)
                {
                    Console.WriteLine($"{i} * {j} = {I * j}");
                }
            }
        }
    }
}

LINQ를 이용할 경우
#!syntax csharp
using System;
using System.Linq;

namespace Namuwiki {
    class Program {
        static void Main(string[] args) {
            Enumerable.Range( 2 , 9 )
                .SelectMany( i =>
                   Enumerable.Range( 1 , 9 )
                      .Select( j => $"{i} * {j} = {i * j}" ) )
                .ToList( ).ForEach( s =>
                   Console.WriteLine( s ) );
        }
    }
}

3.9. Clojure

#!syntax python
(for [x (range 2 10)
      y (range 1 10)]
     (println x "x" y "=" (* x y)))

3.10. D

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

3.11. Dart

#!syntax java
void main() {
  for (int i = 2; i <= 9; i++) {
    for (int j = 1; j <= 9; j++) {
      print("$i * $j = ${i * j}");
    }
  }
}

3.12. emojicode

🏁🍇
  🔂 i 🆕⏩⏩ 2 10❗️🍇
    🔂 j 🆕⏩⏩ 1 10❗️🍇
      😀🍪🔡 i 10❗🔤 * 🔤🔡 j 10❗🔤 = 🔤🔡 i✖️j 10❗🍪❗
    🍉
    😀🔤 🔤❗
  🍉
🍉

3.13. FORTH

#!syntax python
: PRINTTABLE
9 
0 DO
    DUP .           ( 단 수 출력 )
    ." * "          ( '*' 출력 )
    I 1 + .         ( i + 1 출력 )
    ." = "          ( '=' 출력 )
    DUP I 1 + * .   ( n * (i + 1) 출력)
    CR
LOOP ;

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

9 PRINTFOR


첨언하자면, i 라는 변수는 do-loop문의 카운터에 접근할 수 있게 언어 차원에서 제공하는 변수다. 모든 걸 스택으로 다 해먹는 언어 특성상 변수 선언 따위는 존재하지 않는다.

3.14. FORTRAN 77

#!syntax python
      PROGRAM NINE
           IMPLICIT NONE
           INTEGER I
           INTEGER J
           INTEGER GG(8,8)

           DO 10 I=2,9
           DO 20 J=2,9
           GG(I-1,J-1)=I*J
 20        CONTINUE
 10        CONTINUE
           DO 30 I=1,8
           PRINT 300, (GG(I,J), J=1,8)
 30        CONTINUE
 300       FORMAT (8(I4))
      END PROGRAM NINE

3.15. Go

#!syntax typescript
package main

import "fmt"

func main() {
    for i := 2; i < 10; i++ {
        for j := 1; j < 10; j++ {
            fmt.Printf("%d * %d = %d\n", i, j, i*j)
        }
    }
}

3.16. Haskell

#!syntax typescript
import Control.Applicative

stringify :: Int -> Int -> String
stringify x y = show x ++ " * " ++ show y ++ " = " ++ show (x*y)

main :: IO ()
main = mapM_ putStrLn $ liftA2 stringify [2..9] [1..9]

3.17. Idris2

#!syntax typescript
Interpolation Int where interpolate = show

times : Int -> Int -> String
times x y = "\{x} * \{y} = \{x * y}"

main : IO ()
main = traverse_ putStrLn [times x y | x <- [2..9], y <- [1..9]]


표 형식으로 출력하려면:
#!syntax typescript
import Data.String

Interpolation Int where interpolate = show

pad2 : (Show a) => a -> String
pad2 x = padLeft 2 ' ' (show x)

times : Int -> Int -> String
times x y = "\{x} * \{y} = \{pad2 (x * y)}"

timesRow : Int -> String
timesRow y = joinBy " | " [times x y | x <- [2..9]]

main : IO ()
main = traverse_ putStrLn [timesRow y | y <- [1..9]]

3.18. Java

#!syntax java
package wiki.namu.test;

public class Foo {
    public static void main(String[] args) {
        for (int a = 2; a <= 9; a ++) {
            for (int b = 1; b <= 9; b++) {
                System.out.println(a + " * " + b + " = " + a * b);
            }
        }
    }
}


이와 관련된 사건(?)으로 GuguClass가 있다.

3.19. JavaScript

#!syntax javascript
for(var i = 2; i <= 9; i++) {
    for(var j = 1; j <= 9; j++) {
        console.log(i + " * " + j + " = " + i * j);
    }
}


또는

#!syntax javascript
[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));
   });
});


ECMAScript 2015

#!syntax javascript
[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}`);
   });
});

3.20. Julia

#!syntax ruby
for i = 2 : 9, j = 1 : 9
    println("$i * $j = $(i * j)")
end

3.21. Kotlin

#!syntax kotlin
fun main() {
    for (i in 2..9) {
        for (j in 1..9) {
            println("$i * $j = ${i * j}")
        }
    }
}

3.22. LISP

#!syntax python
(loop for i from 2 to 9 do 
    (loop for j from 1 to 9 do 
        (princ (format nil "~D * ~D = ~D~%" i j (* i j)))))

3.23. Lua

#!syntax lua
for i = 2, 9, 1 do
   for j = 1, 9, 1 do
      print(i .. " * " .. j .. " = " .. i * j)
   end
   print("")
end

3.24. Perl

#!syntax perl
foreach $i (2..9) {
    foreach $j (1..9) {
        print "$i * $j = " . $i * $j . "\n"
    }
    print "\n"
}

3.25. PHP

#!syntax php
<?php
    for ($i = 2; $i <= 9; $i++)
        for ($j = 1; $j <= 9; $j++) 
            echo $i." * ".$j." = ".($i*$j)."<br />";
?>


아래와 같이 해도 결과는 같다.
#!syntax php
<?php
    foreach(range(2,9) as $i){
         foreach(range(1,9) as $j){
              echo $i." * ".$j." = ".($i*$j)."<br />";
         }
    }
?>

3.26. Python

3.26.1. Python 2

#!syntax python
for i in range(2, 10):
    for j in range(1, 10):
        print i, "*", j, "=", i * j

3.26.2. Python 3

#!syntax python
for i in range(2, 10):
    for j in range(1, 10):
        print(f"{i} * {j} = {i * j}")
    print()

혹은, Python의 꽃이라 할 수 있는 list comprehension을 이용해 다음 예제도 가능하다.
#!syntax python
gugu = [f"{x} * {y} = {x * y}" for x in range(2, 10) for y in range(1, 10)]
print("\n".join(gugu))


아예 다음과 같이 써도 된다.
#!syntax python
[print(x,"*",y,"=",x*y) for x in range(2, 10) for y in range(1, 10)]


결과적으로, #!syntax python [None] * 100이 생성되고, 생성되면서 #!syntax python print가 실행되어 구구단이 출력된다.

3.27. Ruby

#!syntax python
2.upto(9){|i| 1.upto(9){|j| puts "#{i}X#{j}=#{i*j} "}}


또는

#!syntax python
(2..9).each{|i| (1..9).each{|j| puts "#{i}X#{j}=#{i*j}"}}

3.28. Rust

#!syntax rust
fn main() {
    let mut i = 2;
    let mut j = 1;

    loop {
        println!("{} X {} = {}", i, j, i * j);

        if j == 9 {
            if i == 9 {
                break;
            }
            else {
                i = i + 1;
                j = 1;
                println!("")
            }
        }
        else {
            j = j + 1;
        }
    }
}

또는
#!syntax rust
fn main() {
    for i in (2..10) {
        for j in (1..10) {
        println!("{} * {} = {}", i, j, i * j);
        }
        println!();
    }
}

3.29. Scala

#!syntax python
val output = for (i <- 2 to 9) yield {
    val row = for (j <- 1 to 9) yield s"$i * $j = ${i * j}"
    row.mkString("\n")
}
println(output.mkString("\n"* 2))

3.30. 스크래치

x, y 변수와 list 리스트를 만들고 이렇게 해 주자.
파일:9by9.png

3.31. Swift

#!syntax swift
for a in 2...9 {
    for b in 1..<10 {
        print("\(a) * \(b) = \(a*b)")
    }
}

3.32. Visual Basic .NET

#!syntax python
Module NamuWiki

    Sub Main()
        For i = 2 To 9
            For j = 1 To 9
                Console.WriteLine(String.Format("{0} * {1} = {2}", i, j, i * j))
            Next
        Next
    End Sub

End Module

4. 삼각형 그리기

4.1. Bash

#!syntax python
#!/bin/bash

for ((i=1; i<=20; i++)); do
    for ((j=0; j<i; j++)); do
        echo -n "*"
    done
    echo
done

4.2. BASIC

FOR / NEXT 문을 적절히 활용한 예제 중 하나이다.
#!syntax basic
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

4.3. C

#!syntax cpp
#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;
}

4.4. C++

#!syntax cpp
#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i < 20; i++) {
        for (int j = 1; j <= i; j++) 
            cout << "*";
        cout << endl;
    }
    return 0;
}

4.5. FORTH

#!syntax python
: STARS 0 DO 42 42 EMIT EMIT LOOP ;
: NAMUSTARS 0 DO I 1 + STARS CR LOOP ;

20 NAMUSTARS

4.6. FORTRAN 95

#!syntax ruby
program triangle
  integer:: i
  integer:: j

  i = 1
  j = 1

  write(*,"(A)",advance="no") "*"
  do while(i<20)
    do while(j<=i-1)
      write(*,"(A)",advance="no") "*"
      j = j + 1
    end do

    print *    ! 개행하는 방법
    i = i + 1
    j = 0
  end do
end

4.7. Go

#!syntax typescript
package main

import "fmt"

func main() {
    for i := 1; i < 20; i++ {
        for j := 1; j < i+1; j++ {
            fmt.Print("*")
        }
        fmt.Println()
    }
}

4.8. Haskell

#!syntax typescript
main :: IO ()
main = mapM_ (putStrLn . flip replicate '*') [1..20]

4.9. Idris2

#!syntax typescript
import Data.String

main : IO ()
main = traverse_ (putStrLn . flip replicate '*') [1..20]

4.10. Java

#!syntax java
package wiki.namu.test;

public class Namu {
    public static void main(String[] args) {
        for (int i = 1; i <= 20; i++) {
            System.out.println("*".repeat(i));
        }
    }
}

4.11. JavaScript

#!syntax javascript
var star = "";
for(var a = 1; a < 20; a++)
    for(var b = 0; b < a * 2; b++)
        console.log(star += "*");

콘솔에 출력한다

#!syntax javascript
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
ctx.beginPath()
ctx.moveTo(10, 10)
ctx.lineTo(10, 100)
ctx.lineTo(100, 100)
ctx.closePath()
ctx.fillStyle = 'hotpink'
ctx.fill()
document.body.appendChild(canvas)

canvas로 출력한다

4.12. Julia

#!syntax ruby
for i in 1 : 19
    println("*" ^ i)
end

4.13. Lua

#!syntax lua
for i = 1, 20, 1 do
   for j = 1, i * 2, 1 do
      io.write("*")
   end
   io.write("\n")
end

4.14. Perl

#!syntax perl
foreach (1..20) {
    print '.' x $_ . "\n"
}

Perl에서는 x가 문자열 반복 연산자, .이 문자열 연결 연산자임을 잘 보여주는 예시다.

4.15. PHP

#!syntax php
<?
$a = array();
for ($i=0; $i< 20; $i++){
    $a[$i] = implode("",array_fill(0,($i+1),"*"));
}
?><?=implode("<br />",$a)?>

위의 $a = array();는 생략해도 되며, PHP 5.4 이상인 경우 $a = [];로 선언할 수도 있다.

4.16. Processing

#!syntax java
triangle(50, 10, 10, 90, 90, 90);

다른 예제와는 달리 별표를 이용해 삼각형을 찍는 것이 아닌 창에 정상적인(?) 삼각형을 그리는 예제.
다른 언어의 예제처럼 콘솔에 삼각형 모양으로 별표를 찍는 예제를 원한다면 위의 Java 쪽 예제를 보자.[5]

4.17. Python

#!syntax python
for i in range(1, 20):
    print("*" * i)

4.18. Ruby

#!syntax ruby
(1..20).each{|i| puts '*' * (i*2)}


위의 것의 좌우반전
#!syntax ruby
(1..20).each{|i|
  puts ' ' * (20 - i) + '*' * (i * 2 - 1)
}

4.19. Rust

#!syntax rust
fn main() {
    for i in (1..20) {
        for j in (1..i) {
            print!("*");
        }
        println!();
    }
}

4.20. Scala

#!syntax python
val triangle= for (i <- 1 to 20) yield {"*"* i}
println(triangle.mkString("\n"))

4.21. 스크래치

파일:triangle3.png
스크래치에 내장된 펜 기능으로 정삼각형을 그린다.

4.22. Swift

#!syntax swift
for a in 0...20 {
    for b in 0...a + 1 {
        print("*", terminator:"");
    }
    print("");
}

4.23. 어셈블리어

x86 Linux에 돌아가는 32-비트 버전. 어셈블러는 NASM, 문법은 Intel 스타일이다. 어셈블리어는 CPU와 운영체제 등에 따라 종류가 너무 많으므로 이거 하나만 게재한다.
#!syntax cpp
syscall_write equ 4
stdout equ 1

section .data
star db "*"
newl db 0x0A

segment .bss
line resb 1

section	.text
global _start
_start:
    mov byte [line], 1
print_line_loop:
    push dword [line]
    call _printLine
    add esp, 4
    inc byte [line]
    cmp byte [line], 20
    jle print_line_loop

    mov eax, 1
    mov ebx, 0
    int 0x80

_printLine:
    push ebp
    mov ebp, esp
    mov cx, [ebp+8]
print_star_loop:
    push cx
    mov eax, syscall_write
    mov ebx, stdout
    mov	ecx, star
    mov	edx, 1
    int	0x80
    pop cx
    dec cx
    cmp cx, 0
    jg print_star_loop
    
    mov eax, syscall_write
    mov ebx, stdout
    mov	ecx, newl
    mov	edx, 1
    int	0x80
    
    mov esp, ebp
    pop ebp
    ret

5. 99병의 맥주

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

5.1. AutoHotKey

#!syntax python
A=0
Loop,99
  B.=(F:=100-++A)(G:=" bottle")(Y:=F=1 ? "":"s")(X:=(Z:=" of beer ")"on the wall")",`n"F G Y Z
. ".`nTake one down and pass it around,`n"(H:=(Y ? F-1:"No more")(D:=G (F=2 ? "" :"s"))X)".`n`n"

B.=H ", no more"D Z ".`nGo to the store and buy some more, "A D X "."
Gui,Add,Edit,w600 h250,% B
Gui,Show
Return

GuiClose:
exitApp

5.2. BASIC

#!syntax basic
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

5.3. C

#!syntax cpp
#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 == 2 ? "bottle" : "bottles"));
            break;
        }
    }
    return 0;
}

5.4. C++

#!syntax cpp
#include <iostream>
using namespace std;

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

5.5. C#

#!syntax csharp
using System;

namespace Namuwiki{
    class Program
    {
        static void Main (string[] args)
        {
            for (int b = 99; b >= 0; b--)
            {
                switch (b)
                {
                    case 0:
                        Console.WriteLine("No more bottles of beer on the wall, no more bottles of beer.");
                        Console.WriteLine("Go to the store and buy some more, 99 bottles of beer on the wall.");
                        break;
                    case 1:
                        Console.WriteLine("1 bottle of beer on the wall, 1 bottle of beer.");
                        Console.WriteLine("Take one down and pass it around, no more bottles of beer on the wall\n");
                        break;
                    default:
                        Console.WriteLine("{0} bottles of beer on the wall, {0} bottles of beer.", b);
                        Console.WriteLine("Take one down and pass it around, {0} {1} of beer on the wall", b - 1, ((b - 1) != 1) ? "bottles" : "bottle");
                        break;
                }
            }            
        }
    }
}

5.6. Clojure

#!syntax cpp
(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."))))

5.7. Erlang

#!syntax erlang
-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).

5.8. FORTH

#!syntax python
: 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

5.9. Fortran 90

#!syntax javascript
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


5.10. Go

#!syntax typescript
package main

import "fmt"

func main() {
    for b := 99; b >= 0; b-- {
        switch b {
        case 0:
            fmt.Printf("No more bottles of beer on the wall, no more bottles of beer.\n")
            fmt.Printf("Go to the store and buy some more, 99 bottles of beer on the wall.\n")

        case 1:
            fmt.Printf("1 bottle of beer on the wall, 1 bottle of beer.\n")
            fmt.Printf("Take one down and pass it around, no more bottles of beer on the wall\n")

        default:
            fmt.Printf("%d bottles of beer on the wall, %d bottles of beer.\n", b, b)
            fmt.Printf("Take one down and pass it around, %d of beer on the wall.\n", b-1)
        }
    }
}

5.11. Haskell

#!syntax typescript
bottle :: Int -> String
bottle 0 = "no more bottles"
bottle 1 = "1 bottle"
bottle n = show n ++ " bottles"

message :: Int -> String
message 0 = "No more bottles of beer on the wall, no more bottles of beer\n" ++
            "Go to the store and buy some more, 99 bottles of beer on the wall\n"
message n = bottle n ++ " of beer on the wall, " ++ bottle n ++ " of beer\n" ++
            "Take one down and pass it around, " ++ bottle (n-1) ++ " of beer on the wall\n"

main :: IO ()
main = mapM_ (putStr . message) [99, 98..0]

5.12. Idris2

#!syntax typescript
Interpolation Nat where interpolate = show

bottle : Nat -> String
bottle 0 = "no more bottles of beer"
bottle 1 = "1 bottle of beer"
bottle n = "\{n} bottles of beer"

action : Nat -> String
action 0 = "Go to the store and buy some more"
action _ = "Take one down and pass it around"

beers : (begin : Nat) -> List String
beers begin = map beer [begin..0] where
    next : Nat -> Nat
    next Z = begin
    next (S n) = n

    beer : Nat -> String
    beer n = """
        \{bottle n} on the wall, \{bottle n}.
        \{action n}, \{bottle (next n)} on the wall.
        """

main : IO ()
main = traverse_ putStrLn (beers 99)

5.13. Java

#!syntax java
package wiki.namu.test;

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.");
            }
        }
    }
}

5.14. Kotlin

#!syntax kotlin
fun main(args: Array<String>) {
    (99 downTo 0).forEach { printVerse(it) }
}

fun printVerse(n: Int) {
    println(
        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.
                |""".trimMargin()
            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.
                |""".trimMargin()
        }
    )
}

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

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

5.15. LabVIEW


5.16. Lua

#!syntax lua
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

5.17. Python

#!syntax python
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. ")
    else:
        print("{0} bottles of beer on the wall, {0} bottles of beer. ".format(i))
        print("Take one down and pass it around, ", (i - 1), "bottles of beer on the wall. ")

또는
#!syntax python
start = 99

def bottles(i, leading):
    if i < 0:
        i = start
    _n = "N" if leading else "n"
    _s = "s" if i != 1 else ""
    _i = str(i) if i != 0 else _n + "o more"
    return _i + " bottle" + _s

take_or_buy = lambda i: "Go to the store and buy some more" if i == 0 else "Take one down and pass it around"

for i in range(start, -1, -1):
    print(bottles(i, True) + " of beer on the wall, " + bottles(i, False) + " of beer.")
    print(take_or_buy(i) + ", " + bottles(i - 1, False) + " of beer on the wall.")
    print("")


여기서 사용된 함수 중 행 첫머리 여부에 따른 대소문자 지정 등으로 비교적 복잡한 bottles(i, leading)은 일반적인 함수선언인 def문으로, 그보다 간단한 take_or_buy(i)는 lambda문으로 쓰여 있다.
곳곳에 보이는 A if B else C 문은 삼항연산자로, B의 값에 따라 True이면 A, False이면 C가 된다. C 스타일로 쓰면 B?A:C에 해당한다.
13행에서 보다시피 range문은 argument를 세 개 먹는데, 이를 이용해 C 스타일 for문을 range문으로 바꿀 수 있다.

또는 파이썬 3.10의 match 문법을 사용한 버전.
#!syntax python
from textwrap import dedent


def to_bottles(n: int) -> str:
    match n:
        case 0:
            return "no more bottles"
        case 1:
            return "1 bottle"
        case _:
            return f"{n} bottles"


def get_verse(n: int) -> str:
    match n:
        case 0:
            return dedent(
                f"""\
                {to_bottles(n).capitalize()} of beer on the wall, {to_bottles(n)} of beer.
                Go to the store and buy some more, {to_bottles(99)} of beer on the wall.
                """
            )
        case _:
            return dedent(
                f"""\
                {to_bottles(n)} of beer on the wall, {to_bottles(n)} of beer.
                Take one down and pass it around, {to_bottles(n - 1)} of beer on the wall.
                """
            )


if __name__ == "__main__":
    for i in range(99, -1, -1):
        print(get_verse(i))

5.18. PHP

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


5.19. Swift

#!syntax swift
for i in (0...99).reversed() {
    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.");
    }
}

5.20. Rust

#!syntax rust
fn main() {
    for i in (0..100).rev(){
        match i{
            0 => {
                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.");
            },
            1 => {
                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 => {
                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.\n");
            },
            _ => {
                println!("{} bottles of beer on the wall, {} bottles of beer.", i, i);
                println!("Take one down and pass it around, {} bottles of beer on the wall.\n", i - 1);
            }
        }
    }
}

5.21. Scala

#!syntax php
object NinetyNineBottles extends App {

  object Verse {
    private[this] def s(implicit i: Int) = if (i > 1) "s" else ""
    def unapply(implicit i: Int): Option[String] = Option {
      i match {
        case n if n >= 1 =>
          s"""$n bottle$s of beer on the wall, $n bottle$s of beer.
             |Take one down and pass it around, ${n-1} bottle${s(n-1)} of beer on the wall.
             |""".stripMargin

        case 0 =>
          """No more bottles of beer on the wall, no more bottles of beer.
            |Go to the store and buy some more, 99 bottles of beer on the wall.
            |""".stripMargin
      }
    }
  }

  99.to(0, -1) foreach { case Verse(v) => println(v) }
}

5.22. 스크래치

파일:99bottle.png
스프라이트가 직접 99병의 맥주를 읽게 한다. 다 읽는 데 오래 걸리므로 근성을 가지자.

6. 1부터 N까지 출력

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

6.1. BASIC

#!syntax basic
10 CLS
20 DIM n AS INTEGER
30 INPUT "N: ", n
40 FOR i = 1 TO n
50     PRINT i
60 NEXT i
70 END


END까지가 프로그램 코드의 끝이고, 실행은 RUN을 입력한다.

6.2. C

#!syntax cpp
#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;
}

6.3. C++

#!syntax cpp
#include <iostream>

int main() {
    int n;
    std::cin >> n;
    for (int i = 1; i <= n; i++)
        std::cout << i << std::endl;
    return 0;
}

6.4. C#

#!syntax csharp
using System;

namespace Namuwiki
{
    class Program
    {
        static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());
            for(int i = 1; i <= n; i++)
            {
                Console.WriteLine(i);
            }
        }
    }
}

6.5. Clojure

#!syntax python
(defn read-int []
  (Integer/parseInt (read-line)))

(for [i (range 1 (inc (read-int)))]
  (println i))

6.6. D

#!syntax cpp
import std.stdio, std.conv, std.string;
void main()
{
  foreach(i; 0..readln.strip.to!int + 1)
    writeln(i);
}

D는 UFCS라는 문법을 사용하여 함수간 연계 호출을 간결하게 한다.
N을 입력받는 문장은 C스타일로 치면 다음과 같이 재해석할수 있다.
#!syntax cpp
to ! int ( strip ( readln() ) )

6.7. Erlang

#!syntax erlang
-module(n_writer).
-export([write/1]).

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

6.8. FORTRAN 95

#!syntax python
PROGRAM PRINT_N
    INTEGER:: I
    INTEGER:: N
    READ(*,*) N
    
    I = 1
    DO WHILE(I<=N)
        WRITE(*,'(I0)') I
        I = I + 1
    END DO
END

6.9. Go

#!syntax typescript
package main

import "fmt"

func main() {
    var n int
    fmt.Scanln(&n)

    for i := 1; i <= n; i++ {
        fmt.Printf("%d \n", i)
    }
}

6.10. Haskell

#!syntax python
import Data.List

main :: IO ()
main = do
    a <- read <$> getLine
    putStrLn $ intercalate " " $ show <$> [1 .. a]

6.11. Idris2

#!syntax typescript
import Data.String

main : IO ()
main = do
    n <- cast <$> getLine
    putStrLn . joinBy " " . map show $ [1..n]

6.12. Java

#!syntax java
package wiki.namu.test;

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

6.13. JavaScript

#!syntax javascript
var n = parseInt(prompt("n을 입력해 주십시오."), 10);
for (var i = 1; i <= n; i++) console.log(i);

6.14. Kotlin

#!syntax kotlin
fun main(args: Array<String>) {
    (1..readLine()!!.toInt()).forEach { println(it) }
}

6.15. Lua

#!syntax lua
n = io.read()
for i = 1, n do
    print(i)
end

한 줄 짜리
#!syntax lua
for i = 1, io.read() do print(i) end

6.16. LISP

Common Lisp으로 작성됨.
#!syntax javascript
(let ( (n (parse-integer (read-line))) )
  (loop for x from 1 to n do
    (print x)))

6.17. Perl

#!syntax perl
#!/usr/bin/env perl
my $i = <STDIN>;
chomp $i;
print "$_\n" for 1 .. $i;

6.18. Python

#!syntax python
for x in range(int(input("n을 입력해 주십시오: "))):
    print(x+1)

6.19. PHP

#!syntax php
<?
$n = 15; //임의의 값이 15라고 가정
for( $i = 1; $i <= $n; $i++){echo $i."<BR>";}
?>

아래와 같이 해도 결과는 같다.
#!syntax php
<?
$n = 15; //임의의 값이 15라고 가정
echo implode("<br />",range(1,$n));
?>


변수를 굳이 받으려면 GET 방식[6]을 사용해 볼 수 있다. 물론 GET이외에도 값을 받을 수 있는 방식은 많다.
#!syntax php
<?=implode("<br />",range(1,abs($_GET['n']))); // ?n=(임의의 수) ?>

6.20. Ruby

#!syntax ruby
# 방법 1
print (1..gets.to_i).to_a.join(' ')

#!syntax ruby
# 방법 2, Ruby Range 레퍼런스의 예제로 있는 방식이다.
(1..gets.to_i).each{|i|print i,' '}

루비가 훨씬 더 아름답고 간결하다!

6.21. Rust

#!syntax rust
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);
    }
}

간단한 방법을 찾아왔다

6.22. Scala

#!syntax python
val n = io.StdIn.readInt()
println((1 to n).mkString(" "))

6.23. 스크래치

변수 a와 리스트 list를 만들고 이렇게 해 주자.
파일:1ton.png
그냥 리스트에만 출력시키려면 'a 을(를) 0.5 초동안 말하기'는 굳이 안 넣어도 된다. n이 100만 넘어도 50초니.

6.24. Swift

#!syntax swift
//콘솔에서 입력을 받기위한 메소드이다.
func input() -> String {
    let keyboard = NSFileHandle.fileHandleWithStandardInput()
    let inputData = keyboard.availableData
    let 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)
}



[1] ANSI C 문법에서 권장한 내용을 모두 포함하여 프로그래밍 할 때 이와 같음. [2] 가장 최근 쓰이는 표준 [3] package wiki.namu.test; 이런 식으로 처음에 패키지 선언 가능 [4] 본래 main의 매개변수인 args: Array<String> 는 최신버전에서는 생략해도 된다. [5] Processing은 Java 기반이기 때문에 코드가 거의 완전히 호환된다. [6] (페이지 주소)?(변수1)=(값1)&(변수2)=(값2)...