프로그래밍 언어/예제
(♥ 0)
||
이 문서는 컴퓨터 프로그래밍 언어로 구현한 몇 가지 코드들의 예제이다.전통있는 컴퓨터공학과 1학년 1학기 과제들이다.
언어를 배울 때 주로 사용하는 가장 기본적인 출력 예제이다. 프로그래밍에 입문하는 사람이라면 누구나 한 번쯤은 코딩해보는 코드. 유래는 항목을 참조하라.
Hello, world!가 최초로 언급된 언어다. The C Programming Language에 실려있는 매우 유서깊은 코드.
(K&R 기준)
(C99 기준)[1]
(C11)[2]
또는
C언어와 유사하지만 출력을 위해 C++의 ostream 클래스의 cout 객체를 사용한다.
using namespace를 통한 std 공간 멤버에 접근
C++23 이후
C# 9.0부터 최상위 문을 지원하여 아래와 같이 해도 된다.
C# 10.0부터 implicit global using을 지원하여 아래와 같이 해도 된다.
로우 레벨 프로그래밍의 멋진(...)예시!
CUDA로 이런걸 왜 짜는거야
다만, 위 예제는 CUDA 라이브러리를 쓰기 위해서 억지로 꼬아놓은 코드다. 그냥 C의 Hello, world!를 넣어도 상관 없다.
또는
오브젝트 한개를 만들고, draw이벤트에 코드를 넣고, 룸을 만들어 안에 오브젝트를 배치하자.
만약 젤 위에서 안나오고 이상한 곳에서 나온다면
메시지 창을 통해 출력
웹 페이지로 출력
브라우저 경고 창으로 출력
터미널이나 브라우저의 콘솔로 출력
HTTP로 출력

위쪽 창이 프로그램 코드, 아래쪽 창이 인터페이스.
러시아어는 무시하자
say를 사용하면 \\n을 넣어주지 않아도 된다.
echo를 print로 대체해도 같은 기능을 수행하고 괄호를 생략해도 된다.
이렇게 써도 결과는 동일하다.
하지만 아래와 같이 쓰는 것이 프로세싱의 look&feel을 살리는 예제라고 한다. (위키피디아에서 전재)
이 코드를 실행시키기 위해서는 프로세싱 IDE의 Create Font 기능을 이용하여 vlw 폰트를 미리 만들어두어야한다.
여담으로, 프로세싱은 어떤 교재를 봐도 Hello World 예제가 실려있는 경우가 드물다. 간단한 코드로 그림을 그리거나 하는 것이 가능한 언어다보니 ellipse나 rect 같은 함수로 간단한 그림부터 그려보는 것이 보통.
다른 언어와는 좀 다르게 위의 코드는 프로그래머가 작성하는 소스 파일의 코드가 아니라 인터프리터에 입력(질의)하기 위한 코드이고 write역시 프롤로그에 이미 내장되어 있는 소스(서술식)이다. 결국 위의 코드 중 프로그래머가 직접 작성하는 소스코드는 없는 셈이고 실제로 아무 소스파일을 불러오지 않아도 실행할 수 있다. 인터프리터의 실행 화면에서는
와 같은 식으로 표현된다. 첫번째 행의 ?- 뒤의 부분이 인터프리터에 입력하는 부분이다.
참고로, 파이썬에는 이와 관련된 이스터 에그가 존재한다.
다만 이는 출력된 문장에 콤마가 없다.
또는
오라클 데이터베이스는 모든 쿼리에 FROM이 강제되므로, 아래처럼 입력해야 한다.
스프라이트를 하나 만들고 이렇게 해주자.
스크래치 2.0과 3.0은 펜이나 연산 블럭의 추가/수정 등이 있지만, Hello, world!의 출력에선 그래픽 변경 외의 차이점은 없다.
단, 파워쉘은 ','을 찍을시 분리되므로 바로 밑 문단의 리눅스/유닉스 계열 쉘들 처럼 " "로 감싸줘야 제대로 출력된다.
리눅스/유닉스 시스템에서 사용하는 명령프롬프트 실행파일
텐서플로는 기계학습을 위해 변수보다는 텐서를 다루는데 최적화되어 있는 오픈소스 라이브러리이다. 그렇기 때문에 변수가 아니라 텐서로 출력한다!어쨌든 파이썬이다
단추를 추가하고, 이름을 CommandButton1로 해준다. 해당 단추를 누르면 메시지 상자가 나온다.
콘솔이라면 이렇게.
시뮬레이션에서만 사용이 가능하다.
어셈블리어는 운용되는 플랫폼과 어셈블러의 영향을 크게 받는다. 어차피 어셈블러에 표준 따위는 없기 때문에 모든 어셈블러나 시스템에 대한 코드를 추가하기는 어렵고, 아예 ISA가 다른 CPU들의 예제만 수록한다.
FOR문을 활용한 예제
Dyalog APL을 기준으로 한다.
또한 아래는 n×n 크기의 곱셈표를 출력시키는 함수이다.
FOR / NEXT 문을 적절히 활용한 예제 중 하나다.
while을 사용할 경우 다음과 같다.
LINQ를 이용할 경우
첨언하자면, i 라는 변수는 do-loop문의 카운터에 접근할 수 있게 언어 차원에서 제공하는 변수다. 모든 걸 스택으로 다 해먹는 언어 특성상 변수 선언 따위는 존재하지 않는다.
표 형식으로 출력하려면:
이와 관련된 사건(?)으로 GuguClass가 있다.
또는
ECMAScript 2015
아래와 같이 해도 결과는 같다.
혹은, Python의 꽃이라 할 수 있는 list comprehension을 이용해 다음 예제도 가능하다.
아예 다음과 같이 써도 된다.
결과적으로,
또는
또는
x, y 변수와 list 리스트를 만들고 이렇게 해 주자.

FOR / NEXT 문을 적절히 활용한 예제 중 하나이다.
콘솔에 출력한다
canvas로 출력한다
Perl에서는
위의 $a = array();는 생략해도 되며, PHP 5.4 이상인 경우 $a = [];로 선언할 수도 있다.
다른 예제와는 달리 별표를 이용해 삼각형을 찍는 것이 아닌 창에 정상적인(?) 삼각형을 그리는 예제.
다른 언어의 예제처럼 콘솔에 삼각형 모양으로 별표를 찍는 예제를 원한다면 위의 Java 쪽 예제를 보자.[5]
위의 것의 좌우반전

스크래치에 내장된 펜 기능으로 정삼각형을 그린다.
x86 Linux에 돌아가는 32-비트 버전. 어셈블러는 NASM, 문법은 Intel 스타일이다. 어셈블리어는 CPU와 운영체제 등에 따라 종류가 너무 많으므로 이거 하나만 게재한다.
Hello, world!와 더불어 가장 유명한 코드 예제. 제어문을 배울때 사용된다.
람다 식과 확장함수를 사용해 최대한 코틀린스럽게 작성한 코드이다. 더 줄일 수는 있지만 알아보기 좋게 이대로 둔다.

또는
여기서 사용된 함수 중 행 첫머리 여부에 따른 대소문자 지정 등으로 비교적 복잡한 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 문법을 사용한 버전.
500px
스프라이트가 직접 99병의 맥주를 읽게 한다. 다 읽는 데 오래 걸리므로 근성을 가지자.
임의의 숫자 N을 입력받아 1 부터 N 까지의 모든 숫자를 출력한다.
END까지가 프로그램 코드의 끝이고, 실행은 RUN을 입력한다.
D는 UFCS라는 문법을 사용하여 함수간 연계 호출을 간결하게 한다.
N을 입력받는 문장은 C스타일로 치면 다음과 같이 재해석할수 있다.
한 줄 짜리
Common Lisp으로 작성됨.
한 줄로 쓰게 되면
아래와 같이 해도 결과는 같다.
변수를 굳이 받으려면 GET 방식[6] 을 사용해 볼 수 있다. 물론 GET이외에도 값을 받을 수 있는 방식은 많다.
루비가 훨씬 더 아름답고 간결하다!
간단한 방법을 찾아왔다
변수 a와 리스트 list를 만들고 이렇게 해 주자.

그냥 리스트에만 출력시키려면 'a 을(를) 0.5 초동안 말하기'는 굳이 안 넣어도 된다. n이 100만 넘어도 50초니.
이 문서의 내용 중 전체 또는 일부는 2024-09-20 10:28:28에 나무위키 프로그래밍 언어/예제 문서에서 가져왔습니다.
[ 목차 펼치기 · 접기 ]
1. 개요[편집]
이 문서는 컴퓨터 프로그래밍 언어로 구현한 몇 가지 코드들의 예제이다.
2. 편집 지침[편집]
- 수록 순서를 변경하지 마십시오.
- 문서는 예제의 종류를 대분류로 하여, 프로그래밍 언어를 알파벳, 가나다 순으로 정렬하여 주십시오.
- 예제의 종류는 Hello, world!, 구구단, 삼각형 그리기, 99병의 맥주, 1부터 N까지 출력 순서를 유지하여 주십시오.
- 난해한 언어의 예제는 프로그래밍 언어/예제/난해한 프로그래밍 언어 문서에 추가해 주십시오.
- 이해하기 쉽고 간단한 코드 예제로 작성해 주십시오.
- 복잡한 연산이나 라이브러리를 사용하지 마십시오.
- 원라이너 등 코드의 가독성을 해칠 수 있는 예제를 수록하지 마십시오.
3. Hello, world![편집]
언어를 배울 때 주로 사용하는 가장 기본적인 출력 예제이다. 프로그래밍에 입문하는 사람이라면 누구나 한 번쯤은 코딩해보는 코드. 유래는 항목을 참조하라.
3.1. ABAP[편집]
* 창 자체에 문자로 출력
write 'Hello, world!'.
* 상태표시줄에 띄우기
MESSAGE 'Hello, world!' TYPE 'S' DISPLAY LIKE 'W'.
3.2. ActionScript[편집]
3.2.1. 2.0[편집]
trace("Hello, world!");
3.2.2. 3.0[편집]
package {
public class HelloWorld extends Sprite {
public function HelloWorld():void {
trace("Hello, world!");
}
}
}
3.3. Arduino[편집]
void setup() {
Serial.begin(9600);
Serial.println("Hello, world!");
}
void loop() {
}
3.4. AutoHotkey[편집]
Msgbox, Hello, world!
3.5. BASIC[편집]
10 PRINT "Hello, world!"
20 END
RUN
3.6. C[편집]
Hello, world!가 최초로 언급된 언어다. The C Programming Language에 실려있는 매우 유서깊은 코드.
(K&R 기준)
main( )
{
puts("Hello, world!");
return 0;
}
(C99 기준)[1]
#include <stdio.h>
int main(void)
{
printf("Hello, world!\n");
return 0;
}
(C11)[2]
#include <stdio.h>
int main(int argc, const char * argv[])
{
printf("Hello, world!\n");
return 0;
}
또는
#include <stdio.h>
int main(void)
{
puts("Hello, world!");
return 0;
}
3.7. C++[편집]
C언어와 유사하지만 출력을 위해 C++의 ostream 클래스의 cout 객체를 사용한다.
#include <iostream>
int main()
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
using namespace를 통한 std 공간 멤버에 접근
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, world!" << endl;
return 0;
}
C++23 이후
import std; // 또는 import <print>;
int main() {
std::println("Hello, world!");
}
3.8. C\#[편집]
using System;
namespace Namuwiki
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
}
}
}
C# 9.0부터 최상위 문을 지원하여 아래와 같이 해도 된다.
using System;
Console.WriteLine("Hello, world!");
System.Console.WriteLine("Hello, world!");
C# 10.0부터 implicit global using을 지원하여 아래와 같이 해도 된다.
Console.WriteLine("Hello, world!");
3.9. Classic ASP[편집]
<%
Response.Write("Hello, world!")
%>
3.10. Clojure[편집]
(println "Hello, world!")
3.11. COBOL[편집]
*****************************
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
ENVIRONMENT DIVISION.
DATA DIVISION.
PROCEDURE DIVISION.
MAIN SECTION.
DISPLAY "Hello, world!"
STOP RUN.
****************************
3.12. CUDA[편집]
#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 라이브러리를 쓰기 위해서 억지로 꼬아놓은 코드다. 그냥 C의 Hello, world!를 넣어도 상관 없다.
3.13. D[편집]
import std.stdio;
void main()
{
writeln("Hello, world!");
}
3.14. Dart[편집]
void main() {
print('Hello, world!');
}
3.15. Elm[편집]
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이 어떤 언어인지 잘 알 수 없는 예시다.import Html exposing (text)
main = text "Hello, world!"
3.16. emojicode[편집]
🏁 🍇
😀 🔤Hello, world!🔤❗
🍉
3.17. Erlang[편집]
-module(hello).
-export([hello_world/0]).
hello_world() -> io:fwrite("hello, world\n").
3.18. Forth[편집]
." Hello, world!"
3.19. FORTRAN[편집]
program
Print *, "Hello, world!"
End
또는
PROGRAM MAIN
WRITE(*,*) "Hello, world!"
END
3.20. GML[편집]
오브젝트 한개를 만들고, draw이벤트에 코드를 넣고, 룸을 만들어 안에 오브젝트를 배치하자.
draw_text(x,y,"Hello, world!");
만약 젤 위에서 안나오고 이상한 곳에서 나온다면
draw_text(0,0,"Hello, world!");
메시지 창을 통해 출력
show_message("Hello, world!")
3.21. Go[편집]
package main
import "fmt"
func main() {
fmt.Printf("Hello, world!");
}
3.22. Haskell[편집]
main :: IO ()
main = putStrLn "Hello, world!"
3.23. IDL[편집]
PRO main print, "Hello, world!" END
3.24. Idris2[편집]
main : IO ()
main = putStrLn "Hello, world!"
3.25. Java[편집]
public class NamuWiki {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
[3]3.26. JavaScript[편집]
웹 페이지로 출력
document.write("Hello, world!");
브라우저 경고 창으로 출력
alert("Hello, world!");
터미널이나 브라우저의 콘솔로 출력
console.log("Hello, world!");
HTTP로 출력
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');
3.27. JSP[편집]
<%
out.println ("Hello, world!");
%>
3.28. Julia[편집]
println("Hello, world!")
3.29. Kotlin[편집]
fun main() {
println("Hello, world!")
}
[4]3.30. LabVIEW[편집]

위쪽 창이 프로그램 코드, 아래쪽 창이 인터페이스.
3.31. LISP[편집]
(print "Hello, world!")
3.32. Lua[편집]
print("Hello, world!")
3.33. Objective-C[편집]
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"Hello, world!");
}
return 0;
}
3.34. Pascal[편집]
Program Hello;
begin
writeln('Hello, world!')
end.
3.35. Perl[편집]
print "Hello, world!\n";
say를 사용하면 \\n을 넣어주지 않아도 된다.
say "Hello, world!";
3.36. PHP[편집]
<?php
echo ("Hello, world!");
?>
echo를 print로 대체해도 같은 기능을 수행하고 괄호를 생략해도 된다.
<?="Hello, world!" ?>
이렇게 써도 결과는 동일하다.
3.37. Processing[편집]
println("Hello, world!");
하지만 아래와 같이 쓰는 것이 프로세싱의 look&feel을 살리는 예제라고 한다. (위키피디아에서 전재)
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 같은 함수로 간단한 그림부터 그려보는 것이 보통.
3.38. Prolog[편집]
write("Hello, world!").
다른 언어와는 좀 다르게 위의 코드는 프로그래머가 작성하는 소스 파일의 코드가 아니라 인터프리터에 입력(질의)하기 위한 코드이고 write역시 프롤로그에 이미 내장되어 있는 소스(서술식)이다. 결국 위의 코드 중 프로그래머가 직접 작성하는 소스코드는 없는 셈이고 실제로 아무 소스파일을 불러오지 않아도 실행할 수 있다. 인터프리터의 실행 화면에서는
?- write("Hello, world!").
Hello, world!
true.
와 같은 식으로 표현된다. 첫번째 행의 ?- 뒤의 부분이 인터프리터에 입력하는 부분이다.
3.39. Python[편집]
3.39.1. Python 2[편집]
print "Hello, world!"
3.39.2. Python 3[편집]
print("Hello, world!")
참고로, 파이썬에는 이와 관련된 이스터 에그가 존재한다.
import __hello__ #Hello world!
다만 이는 출력된 문장에 콤마가 없다.
3.40. Racket[편집]
(print "Hello, world!")
3.41. Ren'Py[편집]
"Hello, world!"
3.42. RGSS[편집]
p "Hello, world!"
또는
print "Hello, world!"
3.43. Ruby[편집]
puts "Hello, world!"
3.44. Rust[편집]
fn main() {
println!("Hello, world!");
}
3.45. Scala[편집]
println("Hello, world!")
3.46. SQL[편집]
SELECT 'Hello, world!';
오라클 데이터베이스는 모든 쿼리에 FROM이 강제되므로, 아래처럼 입력해야 한다.
SELECT 'Hello, world!' FROM DUAL;
3.47. 스크래치[편집]
스프라이트를 하나 만들고 이렇게 해주자.
스크래치 2.0과 3.0은 펜이나 연산 블럭의 추가/수정 등이 있지만, Hello, world!의 출력에선 그래픽 변경 외의 차이점은 없다.
3.48. 명령 프롬프트/MS-DOS/PowerShell[편집]
echo Hello, world!
단, 파워쉘은 ','을 찍을시 분리되므로 바로 밑 문단의 리눅스/유닉스 계열 쉘들 처럼 " "로 감싸줘야 제대로 출력된다.
3.49. Shell Script, sh[편집]
리눅스/유닉스 시스템에서 사용하는 명령프롬프트 실행파일
#!/bin/bash
echo "Hello, world!"
3.50. Small Basic[편집]
TextWindow.WriteLine("Hello, world!")
3.51. Swift[편집]
3.51.1. Swift 1.0[편집]
println("Hello, world!")
3.51.2. Swift 2.0 이후[편집]
print("Hello, world!")
3.52. TensorFlow[편집]
import tensorflow as tf
hello = tf.constant('Hello, world!')
sess = tf.Session()
print sess.run(hello)
텐서플로는 기계학습을 위해 변수보다는 텐서를 다루는데 최적화되어 있는 오픈소스 라이브러리이다. 그렇기 때문에 변수가 아니라 텐서로 출력한다!
3.53. TypeScript[편집]
const hello = (name: string) => `Hello, ${name}`
console.log(hello('world!')); // Hello, world!
3.54. VBA 또는 Visual Basic 6 이하[편집]
단추를 추가하고, 이름을 CommandButton1로 해준다. 해당 단추를 누르면 메시지 상자가 나온다.
Private Sub CommandButton1_Click()
MsgBox "Hello, world!"
End Sub
3.55. Visual Basic .NET[편집]
Public Class Form1
Private Sub button1_click
Msgbox("Hello, world!")
End Sub
End Class
콘솔이라면 이렇게.
Module Hello
Sub Main()
Console.Writeline("Hello, world!")
End Sub
End module
3.56. Verilog[편집]
module HelloWorld;
initial begin
$display("Hello, world!");
end
endmodule
시뮬레이션에서만 사용이 가능하다.
3.57. 어셈블리어[편집]
어셈블리어는 운용되는 플랫폼과 어셈블러의 영향을 크게 받는다. 어차피 어셈블러에 표준 따위는 없기 때문에 모든 어셈블러나 시스템에 대한 코드를 추가하기는 어렵고, 아예 ISA가 다른 CPU들의 예제만 수록한다.
3.57.1. Intel x86/AMD64(x64), Mac OS X, NASM[편집]
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
3.57.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
4. 구구단[편집]
4.1. ActionScript[편집]
FOR문을 활용한 예제
for( var i = 1; i <= 9; i++ )
{
trace( i + "단" );
for( var j = 1; j <= 9; j++ )
{
trace( i + "x" + j + "=" + i*j );
}
}
4.2. APL[편집]
Dyalog APL을 기준으로 한다.
∘.{⍺'×'⍵'=',⍺×⍵}⍨⍳9
APL IDE에서 실행하면 깔끔한 9×9 형태의 표로 출력해 준다.또한 아래는 n×n 크기의 곱셈표를 출력시키는 함수이다.
Multiple←∘.{⍺'×'⍵'=',⍺×⍵}⍨⍳
이후 Multiple n
(n ∈ ℤ)로 함수를 호출할 수 있다.4.3. AutoHotKey[편집]
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
4.4. Bash[편집]
#!/bin/bash
for ((i=2; i<10; i++)); do
for ((j=1; j<10; j++)); do
echo "$i * $j = $((i*j))"
done
echo
done
4.5. BASIC[편집]
FOR / NEXT 문을 적절히 활용한 예제 중 하나다.
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단까지 화면에 다 표시되도록 할 수 있다.
4.6. C[편집]
#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을 사용할 경우 다음과 같다.
#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;
}
4.7. C++[편집]
#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;
}
4.8. C\#[편집]
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를 이용할 경우
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 ) );
}
}
}
4.9. Clojure[편집]
(for [x (range 2 10)
y (range 1 10)]
(println x "x" y "=" (* x y)))
4.10. D[편집]
import std.stdio;
void main()
{
foreach(i ; 2..10)
foreach(j ; 1..10)
writeln(i, " x ", j, " = ", i * j);
}
4.11. Dart[편집]
void main() {
for (int i = 2; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
print("$i * $j = ${i * j}");
}
}
}
4.12. emojicode[편집]
🏁🍇
🔂 i 🆕⏩⏩ 2 10❗🍇
🔂 j 🆕⏩⏩ 1 10❗🍇
😀🍪🔡 i 10❗🔤 * 🔤🔡 j 10❗🔤 = 🔤🔡 i✖j 10❗🍪❗
🍉
😀🔤 🔤❗
🍉
🍉
4.13. FORTH[편집]
: 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문의 카운터에 접근할 수 있게 언어 차원에서 제공하는 변수다. 모든 걸 스택으로 다 해먹는 언어 특성상 변수 선언 따위는 존재하지 않는다.
4.14. FORTRAN 77[편집]
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
4.15. Go[편집]
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)
}
}
}
4.16. Haskell[편집]
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]
4.17. Idris2[편집]
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]]
표 형식으로 출력하려면:
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]]
4.18. 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가 있다.
4.19. JavaScript[편집]
for(var i = 2; i <= 9; i++) {
for(var j = 1; j <= 9; j++) {
console.log(i + " * " + j + " = " + i * j);
}
}
또는
[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
[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}`);
});
});
4.20. Julia[편집]
for i = 2 : 9, j = 1 : 9
println("$i * $j = $(i * j)")
end
4.21. Kotlin[편집]
fun main() {
for (i in 2..9) {
for (j in 1..9) {
println("$i * $j = ${i * j}")
}
}
}
4.22. LISP[편집]
(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)))))
4.23. Lua[편집]
for i = 2, 9, 1 do
for j = 1, 9, 1 do
print(i .. " * " .. j .. " = " .. i * j)
end
print("")
end
4.24. Perl[편집]
foreach $i (2..9) {
foreach $j (1..9) {
print "$i * $j = " . $i * $j . "\n"
}
print "\n"
}
4.25. PHP[편집]
<?php
for ($i = 2; $i <= 9; $i++)
for ($j = 1; $j <= 9; $j++)
echo $i." * ".$j." = ".($i*$j)."<br />";
?>
아래와 같이 해도 결과는 같다.
<?php
foreach(range(2,9) as $i){
foreach(range(1,9) as $j){
echo $i." * ".$j." = ".($i*$j)."<br />";
}
}
?>
4.26. Python[편집]
4.26.1. Python 2[편집]
for i in range(2, 10):
for j in range(1, 10):
print i, "*", j, "=", i * j
4.26.2. Python 3[편집]
for i in range(2, 10):
for j in range(1, 10):
print(f"{i} * {j} = {i * j}")
print()
혹은, Python의 꽃이라 할 수 있는 list comprehension을 이용해 다음 예제도 가능하다.
gugu = [f"{x} * {y} = {x * y}" for x in range(2, 10) for y in range(1, 10)]
print("\n".join(gugu))
아예 다음과 같이 써도 된다.
[print(x,"*",y,"=",x*y) for x in range(2, 10) for y in range(1, 10)]
결과적으로,
이 생성되고, 생성되면서
가 실행되어 구구단이 출력된다.4.27. Ruby[편집]
2.upto(9){|i| 1.upto(9){|j| puts "#{i}X#{j}=#{i*j} "}}
또는
(2..9).each{|i| (1..9).each{|j| puts "#{i}X#{j}=#{i*j}"}}
4.28. 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;
}
}
}
또는
fn main() {
for i in (2..10) {
for j in (1..10) {
println!("{} * {} = {}", i, j, i * j);
}
println!();
}
}
4.29. Scala[편집]
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))
4.30. 스크래치[편집]
x, y 변수와 list 리스트를 만들고 이렇게 해 주자.

4.31. Swift[편집]
for a in 2...9 {
for b in 1..<10 {
print("\(a) * \(b) = \(a*b)")
}
}
4.32. Visual Basic .NET[편집]
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
5. 삼각형 그리기[편집]
5.1. Bash[편집]
#!/bin/bash
for ((i=1; i<=20; i++)); do
for ((j=0; j<i; j++)); do
echo -n "*"
done
echo
done
5.2. BASIC[편집]
FOR / NEXT 문을 적절히 활용한 예제 중 하나이다.
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
5.3. C[편집]
#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;
}
5.4. C++[편집]
#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;
}
5.5. FORTH[편집]
: STARS 0 DO 42 42 EMIT EMIT LOOP ;
: NAMUSTARS 0 DO I 1 + STARS CR LOOP ;
20 NAMUSTARS
5.6. FORTRAN 95[편집]
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
5.7. Go[편집]
package main
import "fmt"
func main() {
for i := 1; i < 20; i++ {
for j := 1; j < i+1; j++ {
fmt.Print("*")
}
fmt.Println()
}
}
5.8. Haskell[편집]
main :: IO ()
main = mapM_ (putStrLn . flip replicate '*') [1..20]
5.9. Idris2[편집]
import Data.String
main : IO ()
main = traverse_ (putStrLn . flip replicate '*') [1..20]
5.10. 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));
}
}
}
5.11. JavaScript[편집]
var star = "";
for(var a = 1; a < 20; a++)
for(var b = 0; b < a * 2; b++)
console.log(star += "*");
콘솔에 출력한다
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로 출력한다
5.12. Julia[편집]
for i in 1 : 19
println("*" ^ i)
end
5.13. Lua[편집]
for i = 1, 20, 1 do
for j = 1, i * 2, 1 do
io.write("*")
end
io.write("\n")
end
5.14. Perl[편집]
foreach (1..20) {
print '.' x $_ . "\n"
}
Perl에서는
x
가 문자열 반복 연산자, .
이 문자열 연결 연산자임을 잘 보여주는 예시다.5.15. 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 = [];로 선언할 수도 있다.
5.16. Processing[편집]
triangle(50, 10, 10, 90, 90, 90);
다른 예제와는 달리 별표를 이용해 삼각형을 찍는 것이 아닌 창에 정상적인(?) 삼각형을 그리는 예제.
다른 언어의 예제처럼 콘솔에 삼각형 모양으로 별표를 찍는 예제를 원한다면 위의 Java 쪽 예제를 보자.[5]
5.17. Python[편집]
for i in range(1, 20):
print("*" * i)
5.18. Ruby[편집]
(1..20).each{|i| puts '*' * (i*2)}
위의 것의 좌우반전
(1..20).each{|i|
puts ' ' * (20 - i) + '*' * (i * 2 - 1)
}
5.19. Rust[편집]
fn main() {
for i in (1..20) {
for j in (1..i) {
print!("*");
}
println!();
}
}
5.20. Scala[편집]
val triangle= for (i <- 1 to 20) yield {"*"* i}
println(triangle.mkString("\n"))
5.21. 스크래치[편집]

스크래치에 내장된 펜 기능으로 정삼각형을 그린다.
5.22. Swift[편집]
for a in 0...20 {
for b in 0...a + 1 {
print("*", terminator:"");
}
print("");
}
5.23. 어셈블리어[편집]
x86 Linux에 돌아가는 32-비트 버전. 어셈블러는 NASM, 문법은 Intel 스타일이다. 어셈블리어는 CPU와 운영체제 등에 따라 종류가 너무 많으므로 이거 하나만 게재한다.
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
6. 99병의 맥주[편집]
Hello, world!와 더불어 가장 유명한 코드 예제. 제어문을 배울때 사용된다.
6.1. AutoHotKey[편집]
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
6.2. 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
6.3. C[편집]
#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;
}
6.4. C++[편집]
#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;
}
6.5. C\#[편집]
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;
}
}
}
}
}
6.6. Clojure[편집]
(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."))))
6.7. 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).
6.8. FORTH[편집]
: 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
6.9. Fortran 90[편집]
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
6.10. Go[편집]
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)
}
}
}
6.11. Haskell[편집]
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]
6.12. Idris2[편집]
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)
6.13. 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.");
}
}
}
}
6.14. 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"
}
}
람다 식과 확장함수를 사용해 최대한 코틀린스럽게 작성한 코드이다. 더 줄일 수는 있지만 알아보기 좋게 이대로 둔다.
6.15. LabVIEW[편집]

6.16. 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
6.17. 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. ")
또는
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 문법을 사용한 버전.
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))
6.18. 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>";
}
}
?>
6.19. 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.");
}
}
6.20. 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);
}
}
}
}
6.21. Scala[편집]
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) }
}
6.22. 스크래치[편집]
500px
스프라이트가 직접 99병의 맥주를 읽게 한다. 다 읽는 데 오래 걸리므로 근성을 가지자.
7. 1부터 N까지 출력[편집]
임의의 숫자 N을 입력받아 1 부터 N 까지의 모든 숫자를 출력한다.
7.1. 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을 입력한다.
7.2. C[편집]
#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;
}
7.3. C++[편집]
#include <iostream>
int main() {
int n;
std::cin >> n;
for (int i = 1; i <= n; i++)
std::cout << i << std::endl;
return 0;
}
7.4. C\#[편집]
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);
}
}
}
}
7.5. Clojure[편집]
(defn read-int []
(Integer/parseInt (read-line)))
(for [i (range 1 (inc (read-int)))]
(println i))
7.6. D[편집]
import std.stdio, std.conv, std.string;
void main()
{
foreach(i; 0..readln.strip.to!int + 1)
writeln(i);
}
D는 UFCS라는 문법을 사용하여 함수간 연계 호출을 간결하게 한다.
N을 입력받는 문장은 C스타일로 치면 다음과 같이 재해석할수 있다.
to ! int ( strip ( readln() ) )
7.7. Erlang[편집]
-module(n_writer).
-export([write/1]).
write(N) ->
lists:foreach(fun(T) -> io:format("~p~n", [T]) end, lists:seq(1, N)).
7.8. FORTRAN 95[편집]
PROGRAM PRINT_N
INTEGER:: I
INTEGER:: N
READ(*,*) N
I = 1
DO WHILE(I<=N)
WRITE(*,'(I0)') I
I = I + 1
END DO
END
7.9. Go[편집]
package main
import "fmt"
func main() {
var n int
fmt.Scanln(&n)
for i := 1; i <= n; i++ {
fmt.Printf("%d \n", i)
}
}
7.10. Haskell[편집]
import Data.List
main :: IO ()
main = do
a <- read <$> getLine
putStrLn $ intercalate " " $ show <$> [1 .. a]
7.11. Idris2[편집]
import Data.String
main : IO ()
main = do
n <- cast <$> getLine
putStrLn . joinBy " " . map show $ [1..n]
7.12. 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);
}
}
}
}
7.13. JavaScript[편집]
var n = parseInt(prompt("n을 입력해 주십시오."), 10);
for (var i = 1; i <= n; i++) console.log(i);
7.14. Kotlin[편집]
fun main(args: Array<String>) {
(1..readLine()!!.toInt()).forEach { println(it) }
}
7.15. Lua[편집]
n = io.read()
for i = 1, n do
print(i)
end
한 줄 짜리
for i = 1, io.read() do print(i) end
7.16. LISP[편집]
Common Lisp으로 작성됨.
(let ( (n (parse-integer (read-line))) )
(loop for x from 1 to n do
(print x)))
7.17. Perl[편집]
#!/usr/bin/env perl
my $i = <STDIN>;
chomp $i;
print "$_\n" for 1 .. $i;
7.18. Python[편집]
for x in range(int(input("n을 입력해 주십시오: "))):
print(x+1)
한 줄로 쓰게 되면
for x in range(int(input("n을 입력해 주십시오: "))):print(x+1)
7.19. PHP[편집]
<?
$n = 15; //임의의 값이 15라고 가정
for( $i = 1; $i <= $n; $i++){echo $i."<BR>";}
?>
아래와 같이 해도 결과는 같다.
<?
$n = 15; //임의의 값이 15라고 가정
echo implode("<br />",range(1,$n));
?>
변수를 굳이 받으려면 GET 방식[6] 을 사용해 볼 수 있다. 물론 GET이외에도 값을 받을 수 있는 방식은 많다.
<?=implode("<br />",range(1,abs($_GET['n']))); // ?n=(임의의 수) ?>
7.20. Ruby[편집]
# 방법 1
print (1..gets.to_i).to_a.join(' ')
# 방법 2, Ruby Range 레퍼런스의 예제로 있는 방식이다.
(1..gets.to_i).each{|i|print i,' '}
7.21. 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);
}
}
7.22. Scala[편집]
val n = io.StdIn.readInt()
println((1 to n).mkString(" "))
7.23. 스크래치[편집]
변수 a와 리스트 list를 만들고 이렇게 해 주자.

그냥 리스트에만 출력시키려면 'a 을(를) 0.5 초동안 말하기'는 굳이 안 넣어도 된다. n이 100만 넘어도 50초니.
7.24. 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)
}