[include(틀:상위 문서, top1=프로그래밍 언어)] [include(틀:프로그래밍 언어 문법)] 이 문서는 컴퓨터 [[프로그래밍 언어]]로 구현한 몇 가지 코드들의 예제이다. --전통있는 전산학과 1학년 1학기 과제들이다.-- * 새로운 언어의 예제 코드를 추가할 때, 가급적 알파벳, 가나다 순서를 유지해 주십시오. 당연히 이렇게 작성되어 있어야만 보다 편리하게 찾아볼 수 있습니다. * 기본적인 언어 예제를 표방하니만큼, 원라이너 등 코드의 가독성을 해칠 수 있는 예제를 수록하지 마세요. * 문서의 의미없는 비대화를 막기 위해, 기존에 등록되어 있는 코드의 기능들(Hello World, 99병의 맥주, 구구단, 삼각형 그리기, 1부터 N까지 출력) 외의 목차를 수록하지 마세요. * 프로그래밍 언어의 난이도나 프로그래밍 실력을 자랑하기 위한 곳이 아닙니다. 추가적인 복잡한 연산이나 라이브러리를 포함하지 않는 간단한 코드예제를 작성해주세요. * 난해한 언어의 예제는 [[프로그래밍 언어/코드 예제/난해한 프로그래밍 언어]] 문서에 추가해주세요. [목차] == [[Hello, world!]] == 언어를 배울 때 주로 사용하는 가장 기본적인 출력 예제이다. 프로그래밍에 입문하는 사람이라면 누구나 한 번쯤은 코딩해보는 코드. 유래는 [[Hello, world!|항목]]을 참조하라. === [[ABAP]] === {{{#!syntax python * 창 자체에 문자로 출력 write 'Hello, world!'. * 메세지상자 형태로 띄우기 MESSAGE 'Hello, world!' DISPLAY LIKE 'I'. }}} === [[액션스크립트|ActionScript]] === ==== 2.0 ==== {{{#!syntax java trace("Hello, World!");}}} ==== 3.0 ==== {{{#!syntax java package { public class HelloWorld extends Sprite { public function HelloWorld():void { trace("Hello, World!"); } } } }}} === [[Arduino]] === {{{#!syntax cpp void setup() { Serial.begin(9600); Serial.println("Hello, World!"); } void loop() { } }}} === [[오토핫키|AutoHotkey]] === {{{#!syntax python Msgbox, Hello world! }}} === [[BASIC]] === {{{#!syntax python 10 PRINT "Hello, World!" 20 END }}} === [[C(프로그래밍 언어)|C]] === '''[[Hello, world!]]가 최초로 언급된 언어다. The C Programming Language에 실려있는 매우 유서깊은 코드.''' (K&R 기준) {{{#!syntax cpp main( ) { puts("Hello, world!"); return 0; } }}} (C99 기준)[* ANSI C 문법에서 권장한 내용을 모두 포함하여 프로그래밍 할 때 이와 같음.] {{{#!syntax cpp #include <stdio.h> int main(void) { printf("Hello, World!\n"); return 0; } }}} (C11)[* 가장 최근 쓰이는 표준] {{{#!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; } }}} === [[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; } }}} === [[C\#]] === {{{#!syntax csharp using System; namespace Namuwiki { class Program { static void Main(string[] args) { Console.WriteLine("Hello, world!"); } } } }}} === [[ASP|Classic ASP]] === {{{#!syntax python <% Response.Write("Hello, world!") %> }}} === [[Clojure]] === {{{#!syntax python (println "Hello, world!") }}} === [[COBOL]] === {{{#!syntax python ***************************** IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. ENVIRONMENT DIVISION. DATA DIVISION. PROCEDURE DIVISION. MAIN SECTION. DISPLAY "Hello World!" STOP RUN. **************************** }}} === [[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를 넣어도 상관 없다. === [[D]] === {{{#!syntax java import std.stdio; void main() { writeln("Hello, world!"); } }}} === [[Dart(프로그래밍 언어)|Dart]] === {{{#!syntax java void main() { print('Hello, World!'); } }}} === [[Elm]] === {{{#!html <!-- HTML generated using hilite.me --><div style="background: #ffffff; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%"><span style="color: #0000aa">import</span> <span style="color: #00aaaa; text-decoration: underline">Html</span> exposing (<span style="color: #00aaaa">Html</span>, text) <span style="color: #0000aa">import</span> <span style="color: #00aaaa; text-decoration: underline">Browser</span> <span style="color: #0000aa">type</span> alias <span style="color: #00aaaa">Model</span> <span style="color: #0000aa">=</span> <span style="color: #00aaaa">String</span> <span style="color: #0000aa">type</span> <span style="color: #00aaaa">Msg</span> <span style="color: #0000aa">=</span> <span style="color: #00aaaa">None</span> <span style="color: #00aa00">update</span> <span style="color: #00aaaa">:</span> <span style="color: #00aaaa">Msg</span> <span style="color: #0000aa">-></span> <span style="color: #00aaaa">Model</span> <span style="color: #0000aa">-></span> <span style="color: #00aaaa">Model</span> <span style="color: #00aa00">update</span> msg model <span style="color: #0000aa">=</span> <span style="color: #0000aa">case</span> msg <span style="color: #0000aa">of</span> <span style="color: #00aaaa">None</span> <span style="color: #0000aa">-></span> model <span style="color: #00aa00">view</span> <span style="color: #00aaaa">:</span> <span style="color: #00aaaa">Model</span> <span style="color: #0000aa">-></span> <span style="color: #00aaaa">Html</span> msg <span style="color: #00aa00">view</span> model <span style="color: #0000aa">=</span> text model <span style="color: #00aa00">main</span> <span style="color: #00aaaa">:</span> <span style="color: #00aaaa">Program</span> <span style="color: #00aaaa">()</span> <span style="color: #00aaaa">Model</span> <span style="color: #00aaaa">Msg</span> <span style="color: #00aa00">main</span> <span style="color: #0000aa">=</span> <span style="color: #00aaaa">Browser</span>.sandbox { init <span style="color: #0000aa">=</span> <span style="color: #aa5500">"Hello world!"</span> , update <span style="color: #0000aa">=</span> update , view <span style="color: #0000aa">=</span> view } </pre></div> }}}Elm 언어는 하스켈스러운 문법을 지녔지만 자바스크립트(?) 를 결과물로 내놓는 함수형 언어이다. 위 코드는 단순히 웹브라우저에 "Hello, world!"를 출력할 뿐이지만, 웹페이지의 초기값("Hello, world!")이 입력된(init) Model을 Msg(여기서는 None 하나밖에 없긴 하지만)에 따라 업데이트(update)하고 이를 화면에 실시간으로 출력(view)하는 Model, Update, View 패턴에 따라 작성되었다. 사실 다음과 같이 작성해도 조건은 충족하나, Elm이 어떤 언어인지 잘 알 수 없는 예시다. {{{#!html <!-- HTML generated using hilite.me --><div style="background: #ffffff; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%"><span style="color: #0000aa">import</span> <span style="color: #00aaaa; text-decoration: underline">Html</span> exposing (text) <span style="color: #00aa00">main</span> <span style="color: #0000aa">=</span> text <span style="color: #aa5500">"Hello, world!"</span> </pre></div>}}} === [[emojicode]] === {{{ 🏁 🍇 😀 🔤Hello, World!🔤❗️ 🍉 }}} === [[Erlang]] === {{{#!html <!-- HTML generated using hilite.me --><div style="background: #ffffff; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%">-<span style="color: #880000; font-weight: bold">module</span>(hello). -<span style="color: #880000; font-weight: bold">export</span>([hello_world<span style="color: #333333">/</span><span style="color: #0000DD; font-weight: bold">0</span>]). <span style="color: #0066BB; font-weight: bold">hello_world</span>() <span style="color: #333333">-></span> <span style="color: #0e84b5; font-weight: bold">io</span>:<span style="color: #0066BB; font-weight: bold">fwrite</span>(<span style="background-color: #fff0f0">"hello, world</span><span style="color: #666666; font-weight: bold; background-color: #fff0f0">\n</span><span style="background-color: #fff0f0">"</span>). </pre></div> }}} === [[FORTRAN]] === {{{#!syntax python program Print *, "Hello, world!" End }}} 또는 {{{#!syntax python PROGRAM MAIN WRITE(*,*) "Hello, world!" END }}} === [[게임메이커#s-3.2|GML]] === 오브젝트 한개를 만들고, draw이벤트에 코드를 넣고, 룸을 만들어 안에 오브젝트를 배치하자. {{{#!syntax python draw_text(x,y,"Hello, World!"); }}} 만약 젤 위에서 안나오고 이상한 곳에서 나온다면 {{{#!syntax python draw_text(0,0,"Hello World!"); }}} 메시지 창을 통해 출력 {{{#!syntax python show_message("Hello World!") }}} === [[Go(프로그래밍 언어)|Go]] === {{{#!syntax go package main import "fmt" func main() { fmt.Printf("Hello, world!"); } }}} === [[Haskell]] === {{{#!syntax typescript main :: IO () main = putStrLn "Hello, world!" }}} === [[HQ9+]] === {{{ H }}} 이유는 해당 문서 참조. === [[IDL]] === {{{#!html <!-- HTML generated using hilite.me --><div style="background: #ffffff; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%"><span style="color: #0e84b5; font-weight: bold">PRO</span> <span style="color: #333333">main</span> <span style="color: #008800; font-weight: bold">print</span><span style="color: #333333">,</span> <span style="background-color: #fff0f0">"Hello, world!"</span> <span style="color: #0e84b5; font-weight: bold">END</span> </pre></div> }}} === [[Java]] === {{{#!syntax java package wiki.namu.test; public class NamuWiki { public static void main(String[] args) { System.out.println("Hello, world!"); } } }}} === [[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'); }}} === [[JSP]] === {{{#!syntax python <% out.println ("Hello, World!"); %> }}} === [[Julia]] === {{{#!syntax php println("Hello, world!") }}} === [[Kotlin]] === {{{#!html<pre><span style="font-weight:700;color:#69c;">fun</span> main(args: Array<String>) { println(<span style="color:#c08030;">"Hello, world!"</span>) }</pre>}}} === [[LabVIEW]] === [[파일:external/habrastorage.org/7fed2cf9f0903de17482a35bcdf3494c.png]] 위쪽 창이 프로그램 코드, 아래쪽 창이 인터페이스. ~~러시아어는 무시하자~~ === [[LISP]] === {{{#!syntax python (print "Hello, World!") }}} === [[Lua]] === {{{#!syntax python print("Hello, world!") }}} === [[Objective-C]] === {{{#!syntax objectivec #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { NSLog(@"Hello, World!"); } return 0; } }}} === [[파스칼(프로그래밍 언어)|Pascal]] === {{{#!syntax python Program Hello; begin writeln('Hello, world!') end. }}} === [[Perl]] === {{{#!syntax perl print "Hello, World!\n"; }}} say를 사용하면 \\n을 넣어주지 않아도 된다. {{{#!syntax perl say "Hello, World!"; }}} === [[PHP]] === {{{#!syntax php <?php echo ("Hello, World!"); ?> }}} echo를 print로 대체해도 같은 기능을 수행하고 괄호를 생략해도 된다. {{{#!syntax php <?="Hello, World!" ?> }}} 이렇게 써도 결과는 동일하다. === [[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 같은 함수로 간단한 그림부터 그려보는 것이 보통. === [[Prolog]] === {{{#!syntax python write("Hello, World!"). }}} 다른 언어와는 좀 다르게 위의 코드는 프로그래머가 작성하는 소스 파일의 코드가 아니라 인터프리터에 입력(질의)하기 위한 코드이고 write역시 프롤로그에 이미 내장되어 있는 소스(서술식)이다. 결국 위의 코드 중 프로그래머가 직접 작성하는 소스코드는 없는 셈이고 실제로 아무 소스파일을 불러오지 않아도 실행할 수 있다. 인터프리터의 실행 화면에서는 {{{#!syntax python ?- write("Hello, world!"). Hello, World! true. }}} 와 같은 식으로 표현된다. 첫번째 행의 ?- 뒤의 부분이 인터프리터에 입력하는 부분이다. === [[Python]] === ==== Python 2 ==== {{{#!syntax python print "Hello, World!" }}} ==== Python 3 ==== {{{#!syntax python print("Hello, World!") }}} === [[Racket]] === {{{#!syntax python (print "Hello, World!") }}} === RGSS === {{{#!syntax python p "Hello, world!" }}} 또는 {{{#!syntax python print "Hello, world!" }}} === [[Ruby]] === {{{#!syntax python puts "Hello, world!" }}} === [[Rust]] === {{{#!syntax python fn main() { println!("Hello, world!"); } }}} === [[Scala]] === {{{#!syntax java println("Hello, world!") }}} === [[스크래치(교육 플랫폼)|스크래치]] === 스프라이트를 하나 만들고 이렇게 해주자. || [[파일:스크래치2헬로우월드.png|align=center&width=200]] || [[파일:스크래치3헬로우월드!.png|align=center&width=200]] || || 스크래치 2.0 || 스크래치 3.0 || === [[명령 프롬프트]]/[[MS-DOS]]/[[배치 파일]] === {{{#!syntax python echo hello world }}} === [[Shell Script]], sh === 리눅스/유닉스 시스템에서 사용하는 명령프롬프트 실행파일 {{{#!syntax python #!/bin/bash echo "Hello World!" }}} === Small Basic === {{{#!syntax python TextWindow.WriteLine("Hello, world!") }}} === [[Swift(프로그래밍 언어)|Swift]] === ==== Swift 1.0 ==== {{{#!syntax python println("Hello, world!") }}} ==== Swift 2.0 이후 ==== {{{#!syntax python print("Hello, world!") }}} === [[TensorFlow]] === {{{#!syntax python import tensorflow as tf hello = tf.constant('Hello, world!') sess = tf.Session() print sess.run(hello) }}} [[텐서플로우]]는 [[기계학습]]을 위해 변수보다는 [[텐서]]를 다루는데 최적화되어 있는 오픈소스 라이브러리이다. 그렇기 때문에 변수가 아니라 텐서로 출력한다! === [[TypeScript]] === {{{#!syntax typescript console.log('Hello, world'); }}} === [[VBA]] 또는 [[Visual Basic]] 6 이하 === 단추를 추가하고, 이름을 CommandButton1로 해준다. 해당 단추를 누르면 메시지 상자가 나온다. {{{#!syntax python Private Sub CommandButton1_Click() MsgBox "Hello, World!" End Sub}}} === [[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}}} === [[어셈블리어]] === 어셈블리어는 운용되는 플랫폼과 어셈블러의 영향을 크게 받는다. 어차피 어셈블러에 표준 따위는 없기 때문에 모든 어셈블러나 시스템에 대한 코드를 추가하기는 어렵고, 아예 ISA가 다른 CPU들의 예제만 수록한다. ==== Intel 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 }}} ==== 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 }}} == [[구구단]] == === [[액션스크립트|ActionScript]] === FOR문을 활용한 예제 {{{#!syntax python for( var i = 1; i <= 9; i++ ) { trace( i + "단" ); for( var j = 1; j <= 9; j++ ) { trace( i + "x" + j + "=" + i*j ); } } }}} === [[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 }}} === [[BASIC]] === FOR / NEXT 문을 적절히 활용한 예제 중 하나다. {{{#!syntax python 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단까지 화면에 다 표시되도록 할 수 있다. === [[C(프로그래밍 언어)|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; } }}} === [[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; } }}} === [[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(quot;{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 => quot;{i} * {j} = {i * j}" ) ) .ToList( ).ForEach( s => Console.WriteLine( s ) ); } } } }}} === [[Clojure]] === {{{ (for [x (range 2 10) y (range 1 10)] (println x "x" y "=" (* x y))) }}} === [[D]] === {{{ import std.stdio; void main() { foreach(i ; 2..10) foreach(j ; 1..10) writeln(i, " x ", j, " = ", i * j); } }}} === [[Dart(프로그래밍 언어)|Dart]] === {{{#!syntax java void main() { for (int i = 2; i <= 9; i++) { for (int j = 1; j <= 9; j++) { print("$i * $j = ${i * j}"); } } } }}} === [[emojicode]] === {{{ 🏁🍇 🔂 i 🆕⏩⏩ 2 10❗️🍇 🔂 j 🆕⏩⏩ 1 10❗️🍇 😀🍪🔡 i 10❗🔤 * 🔤🔡 j 10❗🔤 = 🔤🔡 i✖️j 10❗🍪❗ 🍉 😀🔤 🔤❗ 🍉 🍉 }}} === [[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문의 카운터에 접근할 수 있게 언어 차원에서 제공하는 변수다. 모든 걸 [[스택(자료구조)|스택]]으로 다 해먹는 언어 특성상 변수 선언 따위는 존재하지 않는다. === [[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 }}} === [[Haskell]] === {{{#!syntax typescript stringify :: Int -> Int -> String stringify x y = show x ++ " * " ++ show y ++ " = " ++ show (x*y) main :: IO () main = mapM_ putStrLn $ stringify <gt; [2..9] <*> [1..9] }}} === [[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); } } } } }}} === [[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}`); }); }); }}} === [[Julia]] === {{{#!syntax php for i = 2 : 9, j = 1 : 9 println("$i * $j = $(i * j)") end }}} === [[Kotlin]] === {{{#!html <pre><span style="font-weight:700;color:#69c;">fun</span> main() { <span style="font-weight:700;color:#69c;">for</span> (i in <span style="color:#c08030;">2..9</span>) { <span style="font-weight:700;color:#69c;">for</span> (j in <span style="color:#c08030;">1..9</span>) { println(<span style="color:#c08030;">"$i * $j = ${i * j}"</span>) } } }</pre> }}} === [[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))))) }}} === [[Lua]] === {{{#!syntax python for i = 2, 9, 1 do for j = 1, 9, 1 do print(i .. " * " .. j .. " = " .. i * j) end print("") end }}} === [[Perl]] === {{{#!syntax perl foreach $i (2..9) { foreach $j (1..9) { print "$i * $j = " . $i * $j . "\n" } print "\n" } }}} === [[PHP]] === {{{#!syntax python <?php for ($i = 2; $i <= 9; $i++) for ($j = 1; $j <= 9; $j++) echo $i." * ".$j." = ".($i*$j)."<br />"; ?> }}} 아래와 같이 해도 결과는 같다. {{{#!syntax python <?php foreach(range(2,9) as $i){ foreach(range(1,9) as $j){ echo $i." * ".$j." = ".($i*$j)."<br />"; } } ?> }}} === [[Python]] === ==== [[Python]] 2 ==== {{{#!syntax python for i in range(2, 10): for j in range(1, 10): print i, "*", j, "=", i * j }}} ==== [[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)) }}} === [[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}"}} }}} === [[Rust]] === {{{#!syntax python fn main() { let mut i = 2; let mut j = 1; while true { 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 python fn main() { for i in (2..10) { for j in (1..10) { println!("{} * {} = {}", i, j, i * j); } println!(); } } }}} === [[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)) }}} === [[스크래치(교육 플랫폼)|스크래치]] === x, y 변수와 list 리스트를 만들고 이렇게 해 주자. [[파일:9by9.png]] === [[Swift]] === {{{#!syntax python for a in 2...9{ for b in 1..<10 { print("\(a) * \(b) = \(a*b)") } } }}} === [[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}}} == [[삼각형]] 그리기 == === [[BASIC]] === FOR / NEXT 문을 적절히 활용한 예제 중 하나이다. {{{#!syntax python 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 }}} === [[C언어|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; } }}} === [[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; } }}} === [[FORTH]] === {{{#!syntax python : STARS 0 DO 42 42 EMIT EMIT LOOP ; : NAMUSTARS 0 DO I 1 + STARS CR LOOP ; 20 NAMUSTARS }}} === [[FORTRAN]] 95 === {{{#!syntax python 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 }}} === [[Haskell]] === {{{#!syntax typescript main :: IO () main = mapM_ putStrLn $ map (\x -> replicate x '*') [1..20] }}} === [[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)); } } } }}} === [[JavaScript]] === {{{#!syntax python var star = ""; for(var a = 1; a < 20; a++) for(var b = 0; b < a * 2; b++) console.log(star += "*"); }}} 콘솔에 출력한다 {{{#!syntax python 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로 출력한다 === [[Julia]] === {{{#!syntax python for i in 1 : 19 println("*" ^ i) end }}} === [[Lua]] === {{{#!syntax python for i = 1, 20, 1 do for j = 1, i * 2, 1 do io.write("*") end io.write("\n") end }}} === [[Perl]] === {{{#!syntax perl foreach (1..20) { print '.' x $_ . "\n" } }}} Perl에서는 {{{x}}}가 문자열 반복 연산자, {{{.}}}이 문자열 연결 연산자임을 잘 보여주는 예시다. === [[PHP]] === {{{#!syntax python <? $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 = [];로 선언할 수도 있다. 물론 Imagick이나 GD 라이브러리를 이용하면 진짜 삼각형도 만들 수 있지만, 여기서는 생략한다. === [[Processing]] === {{{#!syntax python triangle(50, 10, 10, 90, 90, 90); }}} 다른 예제와는 달리 별표를 이용해 삼각형을 찍는 것이 아닌 창에 정상적인(?) 삼각형을 그리는 예제. 다른 언어의 예제처럼 콘솔에 삼각형 모양으로 별표를 찍는 예제를 원한다면 위의 Java 쪽 예제를 보자.[* Processing은 Java 기반이기 때문에 코드가 거의 완전히 호환된다.] === [[Python]] === {{{#!syntax python for i in range(1, 20): print("*" * i) }}} === [[Ruby]] === {{{#!syntax python (1..20).each{|i| puts '*' * (i*2)} }}} 위의 것의 좌우반전 {{{#!syntax python (1..20).each{|i| puts ' ' * (20 - i) + '*' * (i * 2 - 1) } }}} === [[Rust]] === {{{#!syntax python fn main() { for i in (1..20) { for j in (1..i) { print!("*"); } println!(); } } }}} === [[Scala]] === {{{#!syntax python val triangle= for (i <- 1 to 20) yield {"*"* i} println(triangle.mkString("\n")) }}} === [[스크래치(교육 플랫폼)|스크래치]] === [[파일:triangle3.png]] 스크래치에 내장된 펜 기능으로 정삼각형을 그린다. === [[Swift]] === {{{#!syntax python for a in 0...20 { for b in 0...a + 1 { print("*", terminator:""); } print(""); } }}} === [[어셈블리어]] === 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 }}} == [[99병의 맥주]] == Hello, world!와 더불어 가장 유명한 코드 예제. 제어문을 배울때 사용된다. === [[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 }}} === [[BASIC]] === {{{#!syntax python 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 }}} === [[C(프로그래밍 언어)|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; } }}} === [[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; } }}} === [[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; } } } } } }}} === [[Clojure]] === {{{#!syntax python (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.")))) }}} === [[Erlang]] === {{{#!syntax python -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). }}} === [[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 }}} === [[포트란|Fortran]] 90 === {{{#!syntax python 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 }}} === [[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 $ map message [99, 98..0] }}} === [[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."); } } } } }}} === [[Kotlin]] === {{{#!syntax python 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. """ 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" } } }}} 람다 식과 확장함수를 사용해 최대한 코틀린스럽게 작성한 코드이다. 더 줄일 수는 있지만 알아보기 좋게 이대로 둔다. === [[LabVIEW]] === [[http://www.99-bottles-of-beer.net/img/730-1.gif]] === [[Lua]] === {{{#!syntax python 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 }}} === [[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문으로 바꿀 수 있다. === [[PHP]] === {{{#!syntax python <? 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>"; } } ?> }}} === --[[HQ9+]]-- === {{{ 9 }}} 실제로 한 글자다. 이유는 해당 항목 참고. === [[Swift]] === {{{#!syntax python 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."); } } }}} === [[Rust]] === {{{#!syntax python fn main() { let mut i = 99; while true { if i == 1 { println!("{} bottles of beer on the wall, {} bottles of beer.\nTake one down and pass it around, no more bottles of beer on the wall.\n", i, i); } else { println!("{} bottles of beer on the wall, {} bottles of beer.\nTake one down and pass it around, {} bottles of beer on the wall.\n", i, i, i - 1); } if i == 1 { println!("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall."); break; } else { i = i - 1; } } } }}} === [[Scala]] === {{{#!syntax java 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) } } }}} === [[스크래치(교육 플랫폼)|스크래치]] === [[파일:99bottle.png|500px]] 스프라이트가 직접 99병의 맥주를 읽게 한다. 다 읽는 데 오래 걸리므로 근성을 가지자. == 1부터 N까지 출력 == 임의의 숫자 N을 입력받아 1 부터 N 까지의 모든 숫자를 출력한다. === [[BASIC]] === {{{#!syntax python 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 }}} === [[C(프로그래밍 언어)|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; } }}} === [[C++]] === {{{#!syntax cpp #include <iostream> using namespace std; int main() { int n; cin>>n; for(int i=1;i<=n;i++) cout<<i<<endl; return 0; } }}} === [[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); } } } } }}} === [[Clojure]] === {{{#!syntax python (defn read-int [] (Integer/parseInt (read-line))) (for [i (range 1 (inc (read-int)))] (println i)) }}} === [[D]] === {{{#!syntax python import std.stdio, std.conv, std.string; void main() { foreach(i; 0..readln.strip.to!int + 1) writeln(i); } }}} D는 [[https://en.wikipedia.org/wiki/Uniform_Function_Call_Syntax|UFCS]]라는 문법을 사용하여 함수간 연계 호출을 간결하게 한다. N을 입력받는 문장은 C스타일로 치면 다음과 같이 재해석할수 있다. {{{#!syntax python to ! int ( strip ( readln() ) ) }}} === [[Erlang]] === {{{#!syntax python -module(n_writer). -export([write/1]). write(N) -> lists:foreach(fun(T) -> io:format("~p~n", [T]) end, lists:seq(1, N)). }}} === [[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 }}} === [[Haskell]] === {{{#!syntax python import Data.List main :: IO () main = do a <- read <gt; getLine putStrLn $ intercalate " " $ show <gt; [1 .. a] }}} === [[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); } } } } }}} === [[JavaScript]] === {{{#!syntax python var n = parseInt(prompt("n을 입력해 주십시오."), 10); for (var i = 1; i <= n; i++) console.log(i); }}} === [[Kotlin]] === {{{#!html <!-- HTML generated using hilite.me --><div style="background: #ffffff; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%"><span style="color: #008800; font-weight: bold">fun</span> <span style="color: #0066BB; font-weight: bold">main</span>(args: Array<String>) { (<span style="color: #6600EE; font-weight: bold">1.</span>.readLine()!!.toInt()).forEach { println(it) } } </pre></div> }}} === [[Lua]] === {{{#!syntax python n = io.read() for i = 1, n do print(i) end }}} 한 줄 짜리 {{{#!syntax python for i = 1, io.read() do print(i) end }}} === [[LISP]] === Common Lisp으로 작성됨. {{{#!syntax python (let ( (n (parse-integer (read-line))) ) (loop for x from 1 to n do (print x))) }}} === [[Perl]] === {{{#!syntax python #!/usr/bin/env perl my $i = <STDIN>; chomp $i; print "$_\n" for 1 .. $i; }}} === [[Python]] === {{{#!syntax python for x in range(int(input("n을 입력해 주십시오: "))): print(x+1) }}} === [[PHP]] === {{{#!syntax python <? $n = 15; //임의의 값이 15라고 가정 for( $i = 1; $i <= $n; $i++){echo $i."<BR>";} ?> }}} 아래와 같이 해도 결과는 같다. {{{#!syntax python <? $n = 15; //임의의 값이 15라고 가정 echo implode("<br />",range(1,$n)); ?> }}} 변수를 굳이 받으려면 GET 방식[* (페이지 주소)?(변수1)=(값1)&(변수2)=(값2)...]을 사용해 볼 수 있다. 물론 GET이외에도 값을 받을 수 있는 방식은 많다. {{{#!syntax python <?=implode("<br />",range(1,abs($_GET['n']))); // ?n=(임의의 수) ?> }}} === [[Ruby]] === {{{#!syntax python # 방법 1 print (1..gets.to_i).to_a.join(' ') }}} {{{#!syntax python # 방법 2, Ruby Range 레퍼런스의 예제로 있는 방식이다. (1..gets.to_i).each{|i|print i,' '} }}} --루비가 훨씬 더 아름답고 간결하다!-- === [[Rust]] === {{{#!syntax python 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); } } }}} --간단한 방법을 찾아왔다-- === [[Scala]] === {{{#!syntax python val n = io.StdIn.readInt() println((1 to n).mkString(" ")) }}} === [[스크래치(교육 플랫폼)|스크래치]] === 변수 a와 리스트 list를 만들고 이렇게 해 주자. [[파일:1ton.png]] 그냥 리스트에만 출력시키려면 'a 을(를) 0.5 초동안 말하기'는 굳이 안 넣어도 된다. n이 100만 넘어도 50초니. === [[Swift]] === {{{#!syntax java //콘솔에서 입력을 받기위한 메소드이다. 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) } }}} [[분류:프로그래밍 예제]]