분류
- 새로운 언어의 예제 코드를 추가할 때, 가급적 알파벳, 가나다 순서를 유지해 주십시오. 당연히 이렇게 작성되어 있어야만 보다 편리하게 찾아볼 수 있습니다.
- 기본적인 언어 예제를 표방하니만큼, 원라이너 등 코드의 가독성을 해칠 수 있는 예제를 수록하지 마세요.
- 문서의 의미없는 비대화를 막기 위해, 기존에 등록되어 있는 코드의 기능들(Hello World, 99병의 맥주, 구구단, 삼각형 그리기, 1부터 N까지 출력) 외의 목차를 수록하지 마세요.
- 프로그래밍 언어의 난이도나 프로그래밍 실력을 자랑하기 위한 곳이 아닙니다. 추가적인 복잡한 연산이나 라이브러리를 포함하지 않는 간단한 코드예제를 작성해주세요.
- 난해한 언어의 예제는 프로그래밍 언어/코드 예제/난해한 프로그래밍 언어 문서에 추가해주세요.
1. [[Hello, world!]]
1.1. [[ABAP]]1.2. [[액션스크립트|ActionScript]]1.3. [[Arduino]]1.4. [[오토핫키|AutoHotkey]]1.5. [[BASIC]]1.6. [[C(프로그래밍 언어)|C]]1.7. [[C++]]1.8. [[C\#]]1.9. [[ASP|Classic ASP]]1.10. [[Clojure]]1.11. [[COBOL]]1.12. [[CUDA]]1.13. [[D]]1.14. [[Dart(프로그래밍 언어)|Dart]]1.15. [[Elm]]1.16. [[emojicode]]1.17. [[Erlang]]1.18. [[FORTRAN]]1.19. [[게임메이커#s-3.2|GML]]1.20. [[Go(프로그래밍 언어)|Go]]1.21. [[Haskell]]1.22. [[HQ9+]]1.23. [[IDL]]1.24. [[Java]]1.25. [[JavaScript]]1.26. [[JSP]]1.27. [[Julia]]1.28. [[Kotlin]]1.29. [[LabVIEW]]1.30. [[LISP]]1.31. [[Lua]]1.32. [[Objective-C]]1.33. [[파스칼(프로그래밍 언어)|Pascal]]1.34. [[Perl]]1.35. [[PHP]]1.36. [[Processing]]1.37. [[Prolog]]1.38. [[Python]]1.39. [[Racket]]1.40. RGSS1.41. [[Ruby]]1.42. [[Rust]]1.43. [[Scala]]1.44. [[스크래치(교육 플랫폼)|스크래치]]1.45. [[명령 프롬프트]]/[[MS-DOS]]/[[배치 파일]]1.46. [[Shell Script]], sh1.47. Small Basic1.48. [[Swift(프로그래밍 언어)|Swift]]1.49. [[TensorFlow]]1.50. [[TypeScript]]1.51. [[VBA]] 또는 [[Visual Basic]] 6 이하1.52. [[Visual Basic .NET]]1.53. [[어셈블리어]]
2. [[구구단]]2.1. [[액션스크립트|ActionScript]]2.2. [[AutoHotKey]]2.3. [[BASIC]]2.4. [[C(프로그래밍 언어)|C]]2.5. [[C++]]2.6. [[C\#]]2.7. [[Clojure]]2.8. [[D]]2.9. [[Dart(프로그래밍 언어)|Dart]]2.10. [[emojicode]]2.11. [[FORTH]]2.12. [[FORTRAN]] 772.13. [[Haskell]]2.14. [[Java]]2.15. [[JavaScript]]2.16. [[Julia]]2.17. [[Kotlin]]2.18. [[LISP]]2.19. [[Lua]]2.20. [[Perl]]2.21. [[PHP]]2.22. [[Python]]2.23. [[Ruby]]2.24. [[Rust]]2.25. [[Scala]]2.26. [[스크래치(교육 플랫폼)|스크래치]]2.27. [[Swift]]2.28. [[Visual Basic .NET]]
3. [[삼각형]] 그리기3.1. [[BASIC]]3.2. [[C언어|C]]3.3. [[C++]]3.4. [[FORTH]]3.5. [[FORTRAN]] 953.6. [[Haskell]]3.7. [[Java]]3.8. [[JavaScript]]3.9. [[Julia]]3.10. [[Lua]]3.11. [[Perl]]3.12. [[PHP]]3.13. [[Processing]]3.14. [[Python]]3.15. [[Ruby]]3.16. [[Rust]]3.17. [[Scala]]3.18. [[스크래치(교육 플랫폼)|스크래치]]3.19. [[Swift]]3.20. [[어셈블리어]]
4. [[99병의 맥주]]4.1. [[AutoHotKey]]4.2. [[BASIC]]4.3. [[C(프로그래밍 언어)|C]]4.4. [[C++]]4.5. [[C\#]]4.6. [[Clojure]]4.7. [[Erlang]]4.8. [[FORTH]]4.9. [[포트란|Fortran]] 904.10. [[Haskell]]4.11. [[Java]]4.12. [[Kotlin]]4.13. [[LabVIEW]]4.14. [[Lua]]4.15. [[Python]]4.16. [[PHP]]4.17. --[[HQ9+]]--4.18. [[Swift]]4.19. [[Rust]]4.20. [[Scala]]4.21. [[스크래치(교육 플랫폼)|스크래치]]
5. 1부터 N까지 출력5.1. [[BASIC]]5.2. [[C(프로그래밍 언어)|C]]5.3. [[C++]]5.4. [[C\#]]5.5. [[Clojure]]5.6. [[D]]5.7. [[Erlang]]5.8. [[FORTRAN]] 955.9. [[Haskell]]5.10. [[Java]]5.11. [[JavaScript]]5.12. [[Kotlin]]5.13. [[Lua]]5.14. [[LISP]]5.15. [[Perl]]5.16. [[Python]]5.17. [[PHP]]5.18. [[Ruby]]5.19. [[Rust]]5.20. [[Scala]]5.21. [[스크래치(교육 플랫폼)|스크래치]]5.22. [[Swift]]
1. Hello, world!
1.1. ABAP
* 창 자체에 문자로 출력
write 'Hello, world!'.
* 메세지상자 형태로 띄우기
MESSAGE 'Hello, world!' DISPLAY LIKE 'I'.
1.2. ActionScript
1.2.1. 2.0
trace("Hello, World!");
1.2.2. 3.0
package {
public class HelloWorld extends Sprite {
public function HelloWorld():void {
trace("Hello, World!");
}
}
}
1.3. Arduino
void setup() {
Serial.begin(9600);
Serial.println("Hello, World!");
}
void loop() {
}
1.4. AutoHotkey
Msgbox, Hello world!
1.5. BASIC
10 PRINT "Hello, World!"
20 END
1.6. C
(K&R 기준)
main( )
{
puts("Hello, world!");
return 0;
}
(C99 기준)[2]
#include <stdio.h>
int main(void)
{
printf("Hello, World!\n");
return 0;
}
(C11)[4]
#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;
}
1.7. C++
C언어와 유사하지만 출력을 위해 C++의 스트림 객체를 사용한다.
또는
#include <iostream>
int main()
{
std::cout << "Hello, World!" << std::endl;
return 0;
}
또는
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
return 0;
}
1.8. C\#
using System;
namespace Namuwiki
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
}
}
}
1.9. Classic ASP
<%
Response.Write("Hello, world!")
%>
1.10. Clojure
(println "Hello, world!")
1.11. COBOL
*****************************
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
ENVIRONMENT DIVISION.
DATA DIVISION.
PROCEDURE DIVISION.
MAIN SECTION.
DISPLAY "Hello World!"
STOP RUN.
****************************
1.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를 넣어도 상관 없다.
1.13. D
import std.stdio;
void main()
{
writeln("Hello, world!");
}
1.14. Dart
void main() {
print('Hello, World!');
}
1.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 }
import Html exposing (text) main = text "Hello, world!"
1.16. emojicode
🏁 🍇
😀 🔤Hello, World!🔤❗️
🍉
1.17. Erlang
-module(hello). -export([hello_world/0]). hello_world() -> io:fwrite("hello, world\n").
1.18. FORTRAN
program
Print *, "Hello, world!"
End
또는
PROGRAM MAIN
WRITE(*,*) "Hello, world!"
END
1.19. GML
오브젝트 한개를 만들고, draw이벤트에 코드를 넣고, 룸을 만들어 안에 오브젝트를 배치하자.
만약 젤 위에서 안나오고 이상한 곳에서 나온다면
메시지 창을 통해 출력
draw_text(x,y,"Hello, World!");
만약 젤 위에서 안나오고 이상한 곳에서 나온다면
draw_text(0,0,"Hello World!");
메시지 창을 통해 출력
show_message("Hello World!")
1.20. Go
package main
import "fmt"
func main() {
fmt.Printf("Hello, world!");
}
1.21. Haskell
main :: IO ()
main = putStrLn "Hello, world!"
1.22. HQ9+
H
이유는 해당 문서 참조.
1.23. IDL
PRO main print, "Hello, world!" END
1.24. Java
package wiki.namu.test;
public class NamuWiki {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
1.25. JavaScript
웹 페이지로 출력
브라우저 경고 창으로 출력
터미널이나 브라우저의 콘솔로 출력
HTTP로 출력
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');
1.26. JSP
<%
out.println ("Hello, World!");
%>
1.27. Julia
println("Hello, world!")
1.28. Kotlin
fun main(args: Array<String>) { println("Hello, world!") }
1.29. LabVIEW
파일:external/habrastorage.org/7fed2cf9f0903de17482a35bcdf3494c.png
위쪽 창이 프로그램 코드, 아래쪽 창이 인터페이스.
러시아어는 무시하자
위쪽 창이 프로그램 코드, 아래쪽 창이 인터페이스.
1.30. LISP
(print "Hello, World!")
1.31. Lua
print("Hello, world!")
1.32. Objective-C
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"Hello, World!");
}
return 0;
}
1.33. Pascal
Program Hello;
begin
writeln('Hello, world!')
end.
1.34. Perl
print "Hello, World!\n";
say를 사용하면 \n을 넣어주지 않아도 된다.
say "Hello, World!";
1.35. PHP
<?php
echo ("Hello, World!");
?>
echo를 print로 대체해도 같은 기능을 수행하고 괄호를 생략해도 된다.
<?="Hello, World!" ?>
이렇게 써도 결과는 동일하다.
1.36. 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 같은 함수로 간단한 그림부터 그려보는 것이 보통.
1.37. Prolog
write("Hello, World!").
다른 언어와는 좀 다르게 위의 코드는 프로그래머가 작성하는 소스 파일의 코드가 아니라 인터프리터에 입력(질의)하기 위한 코드이고 write역시 프롤로그에 이미 내장되어 있는 소스(서술식)이다. 결국 위의 코드 중 프로그래머가 직접 작성하는 소스코드는 없는 셈이고 실제로 아무 소스파일을 불러오지 않아도 실행할 수 있다. 인터프리터의 실행 화면에서는
?- write("Hello, world!").
Hello, World!
true.
와 같은 식으로 표현된다. 첫번째 행의 ?- 뒤의 부분이 인터프리터에 입력하는 부분이다.
1.38. Python
1.38.1. Python 2
print "Hello, World!"
1.38.2. Python 3
print("Hello, World!")
1.39. Racket
(print "Hello, World!")
1.40. RGSS
p "Hello, world!"
또는
print "Hello, world!"
1.41. Ruby
puts "Hello, world!"
1.42. Rust
fn main() {
println!("Hello, world!");
}
1.43. Scala
println("Hello, world!")
1.44. 스크래치
1.45. 명령 프롬프트/MS-DOS/배치 파일
echo hello world
1.46. Shell Script, sh
리눅스/유닉스 시스템에서 사용하는 명령프롬프트 실행파일
#!/bin/bash
echo "Hello World!"
1.47. Small Basic
TextWindow.WriteLine("Hello, world!")
1.48. Swift
1.48.1. Swift 1.0
println("Hello, world!")
1.48.2. Swift 2.0 이후
print("Hello, world!")
1.49. TensorFlow
1.50. TypeScript
console.log('Hello, world');
1.51. VBA 또는 Visual Basic 6 이하
단추를 추가하고, 이름을 CommandButton1로 해준다. 해당 단추를 누르면 메시지 상자가 나온다.
Private Sub CommandButton1_Click()
MsgBox "Hello, World!"
End Sub
1.52. 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
1.53. 어셈블리어
어셈블리어는 운용되는 플랫폼과 어셈블러의 영향을 크게 받는다. 어차피 어셈블러에 표준 따위는 없기 때문에 모든 어셈블러나 시스템에 대한 코드를 추가하기는 어렵고, 아예 ISA가 다른 CPU들의 예제만 수록한다.
1.53.1. Intel 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
1.53.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
2. 구구단
2.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 );
}
}
2.2. 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
2.3. 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단까지 화면에 다 표시되도록 할 수 있다.
2.4. 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;
}
2.5. 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;
}
2.6. 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(quot;{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 => quot;{i} * {j} = {i * j}" ) )
.ToList( ).ForEach( s =>
Console.WriteLine( s ) );
}
}
}
2.7. Clojure
(for [x (range 2 10)
y (range 1 10)]
(println x "x" y "=" (* x y)))
2.8. D
import std.stdio;
void main()
{
foreach(i ; 2..10)
foreach(j ; 1..10)
writeln(i, " x ", j, " = ", i * j);
}
2.9. Dart
void main() {
for (int i = 2; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
print("$i * $j = ${i * j}");
}
}
}
2.10. emojicode
🏁🍇
🔂 i 🆕⏩⏩ 2 10❗️🍇
🔂 j 🆕⏩⏩ 1 10❗️🍇
😀🍪🔡 i 10❗🔤 * 🔤🔡 j 10❗🔤 = 🔤🔡 i✖️j 10❗🍪❗
🍉
😀🔤 🔤❗
🍉
🍉
2.11. 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문의 카운터에 접근할 수 있게 언어 차원에서 제공하는 변수다. 모든 걸 스택으로 다 해먹는 언어 특성상 변수 선언 따위는 존재하지 않는다.
2.12. 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
2.13. Haskell
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]
2.14. 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);
}
}
}
}
2.15. 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}`);
});
});
2.16. Julia
for i = 2 : 9, j = 1 : 9
println("$i * $j = $(i * j)")
end
2.17. Kotlin
fun main() { for (i in 2..9) { for (j in 1..9) { println("$i * $j = ${i * j}") } } }
2.18. 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)))))
2.19. Lua
for i = 2, 9, 1 do
for j = 1, 9, 1 do
print(i .. " * " .. j .. " = " .. i * j)
end
print("")
end
2.20. Perl
foreach $i (2..9) {
foreach $j (1..9) {
print "$i * $j = " . $i * $j . "\n"
}
print "\n"
}
2.21. 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 />";
}
}
?>
2.22. Python
2.22.1. Python 2
for i in range(2, 10):
for j in range(1, 10):
print i, "*", j, "=", i * j
2.22.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))
2.23. 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}"}}
2.24. Rust
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;
}
}
}
또는
fn main() {
for i in (2..10) {
for j in (1..10) {
println!("{} * {} = {}", i, j, i * j);
}
println!();
}
}
2.25. 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))
2.26. 스크래치
2.27. Swift
for a in 2...9{
for b in 1..<10 {
print("\(a) * \(b) = \(a*b)")
}
}
2.28. 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
3. 삼각형 그리기
3.1. 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
3.2. 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;
}
3.3. 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;
}
3.4. FORTH
: STARS 0 DO 42 42 EMIT EMIT LOOP ;
: NAMUSTARS 0 DO I 1 + STARS CR LOOP ;
20 NAMUSTARS
3.5. 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
3.6. Haskell
main :: IO ()
main = mapM_ putStrLn $ map (\x -> replicate x '*') [1..20]
3.7. 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));
}
}
}
3.8. 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로 출력한다
3.9. Julia
for i in 1 : 19
println("*" ^ i)
end
3.10. Lua
for i = 1, 20, 1 do
for j = 1, i * 2, 1 do
io.write("*")
end
io.write("\n")
end
3.11. Perl
foreach (1..20) {
print '.' x $_ . "\n"
}
Perl에서는
x가 문자열 반복 연산자, .이 문자열 연결 연산자임을 잘 보여주는 예시다.3.12. 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 = [];로 선언할 수도 있다.
물론 Imagick이나 GD 라이브러리를 이용하면 진짜 삼각형도 만들 수 있지만, 여기서는 생략한다.
3.13. Processing
triangle(50, 10, 10, 90, 90, 90);
다른 예제와는 달리 별표를 이용해 삼각형을 찍는 것이 아닌 창에 정상적인(?) 삼각형을 그리는 예제.
다른 언어의 예제처럼 콘솔에 삼각형 모양으로 별표를 찍는 예제를 원한다면 위의 Java 쪽 예제를 보자.[5]
3.14. Python
for i in range(1, 20):
print("*" * i)
3.15. Ruby
(1..20).each{|i| puts '*' * (i*2)}
위의 것의 좌우반전
(1..20).each{|i|
puts ' ' * (20 - i) + '*' * (i * 2 - 1)
}
3.16. Rust
fn main() {
for i in (1..20) {
for j in (1..i) {
print!("*");
}
println!();
}
}
3.17. Scala
val triangle= for (i <- 1 to 20) yield {"*"* i}
println(triangle.mkString("\n"))
3.18. 스크래치
3.19. Swift
for a in 0...20 {
for b in 0...a + 1 {
print("*", terminator:"");
}
print("");
}
3.20. 어셈블리어
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
4. 99병의 맥주
Hello, world!와 더불어 가장 유명한 코드 예제. 제어문을 배울때 사용된다.
4.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
4.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
4.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;
}
4.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;
}
4.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;
}
}
}
}
}
4.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."))))
4.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).
4.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
4.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
4.10. 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 $ map message [99, 98..0]
4.11. 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.");
}
}
}
}
4.12. 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.
"""
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"
}
}
람다 식과 확장함수를 사용해 최대한 코틀린스럽게 작성한 코드이다. 더 줄일 수는 있지만 알아보기 좋게 이대로 둔다.
4.13. LabVIEW
4.14. 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
4.15. 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문으로 바꿀 수 있다.
4.16. 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>";
}
}
?>
4.17. HQ9+
9
실제로 한 글자다. 이유는 해당 항목 참고.
4.18. 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.");
}
}
4.19. Rust
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;
}
}
}
4.20. 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) }
}
4.21. 스크래치
5. 1부터 N까지 출력
임의의 숫자 N을 입력받아 1 부터 N 까지의 모든 숫자를 출력한다.
5.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
5.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;
}
5.3. C++
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
for(int i=1;i<=n;i++)
cout<<i<<endl;
return 0;
}
5.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);
}
}
}
}
5.5. Clojure
(defn read-int []
(Integer/parseInt (read-line)))
(for [i (range 1 (inc (read-int)))]
(println i))
5.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() ) )
5.7. Erlang
-module(n_writer).
-export([write/1]).
write(N) ->
lists:foreach(fun(T) -> io:format("~p~n", [T]) end, lists:seq(1, N)).
5.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
5.9. Haskell
import Data.List
main :: IO ()
main = do
a <- read <gt; getLine
putStrLn $ intercalate " " $ show <gt; [1 .. a]
5.10. 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);
}
}
}
}
5.11. JavaScript
var n = parseInt(prompt("n을 입력해 주십시오."), 10);
for (var i = 1; i <= n; i++) console.log(i);
5.12. Kotlin
fun main(args: Array<String>) { (1..readLine()!!.toInt()).forEach { println(it) } }
5.13. Lua
n = io.read()
for i = 1, n do
print(i)
end
한 줄 짜리
for i = 1, io.read() do print(i) end
5.14. LISP
Common Lisp으로 작성됨.
(let ( (n (parse-integer (read-line))) )
(loop for x from 1 to n do
(print x)))
5.15. Perl
#!/usr/bin/env perl
my $i = <STDIN>;
chomp $i;
print "$_\n" for 1 .. $i;
5.16. Python
for x in range(int(input("n을 입력해 주십시오: "))):
print(x+1)
5.17. 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=(임의의 수) ?>
5.18. Ruby
# 방법 1
print (1..gets.to_i).to_a.join(' ')
# 방법 2, Ruby Range 레퍼런스의 예제로 있는 방식이다.
(1..gets.to_i).each{|i|print i,' '}
5.19. 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);
}
}
5.20. Scala
val n = io.StdIn.readInt()
println((1 to n).mkString(" "))
5.21. 스크래치
변수 a와 리스트 list를 만들고 이렇게 해 주자.
파일:1ton.png
그냥 리스트에만 출력시키려면 'a 을(를) 0.5 초동안 말하기'는 굳이 안 넣어도 된다. n이 100만 넘어도 50초니.
파일:1ton.png
그냥 리스트에만 출력시키려면 'a 을(를) 0.5 초동안 말하기'는 굳이 안 넣어도 된다. n이 100만 넘어도 50초니.
5.22. 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)
}