아래의 소스 코드는 Groovy로도 실행되는 Java 용 소스파일 TestWhileLoop.java를 Groovy 용으로 Groovy 언어 답게 고친 것이다.

소스 파일명: testWhile.groovy

  1. /*
  2.  *  Filename: testWhile.groovy
  3.  *
  4.  *  Purpose:  Example using the while loop syntax
  5.  *                while ....
  6.  *
  7.  *  Execute: groovy testWhile.groovy -200 300
  8.  *
  9.  */
  10. // java.lang.Math 클래스를 명시적으로 import하는 구문이 없어도
  11. // Groovy는 이 클래스를 자동으로 import한다.
  12. // 사용법 표시
  13. def printUsage() {
  14.     println 'Using: groovy testWhile.groovy [integer1] [integer2]'
  15.     println 'This finds the greatest common divisor of the given two integers.'
  16. }
  17. if (args.length != 2) {
  18.     printUsage()
  19.     System.exit(1)
  20. }
  21. def val1 = args[0].toLong()
  22. def val2 = args[1].toLong()
  23. def a, b, q, r, gcd
  24. ////////////////////////////////////////////////
  25. // 명령행 인자의 두 스트링을 가져와서
  26. // 긴정수(long) 타입으로 변환하여
  27. // 변수 val1과 val2에 저장한다.
  28. a = val1.abs()
  29. b = val2.abs()
  30. // a는 |val1|, |val2| 중 큰 값
  31. if (a < b) {
  32.     a = val2.abs()
  33.     b = val1.abs()
  34. }
  35. if (b == 0L) {
  36.     println "GCD($val1, $val2) = $a"
  37.     System.exit(0)
  38. }
  39. ////////////////////////////////////////
  40. // Euclidean 알고리즘의 시작
  41. //
  42. // a를 b로 나누어 몫은 q에, 나머지는 r에 저장
  43. q = a / b
  44. r = a % b
  45. ////////////////////////////////////////
  46. // Euclidean 알고리즘의 반복 (나머지 r이 0이 될 때 까지)
  47. while (r != 0L) {
  48.     a = b
  49.     b = r
  50.     q = a / b
  51.     r = a % b
  52. }
  53. // 나머지가 0이면 그 때 나눈 수(제수) b가 최대공약수(GCD)이다.
  54. gcd = b
  55. // 최대공약수(GCD)를 출력한다.
  56. println "GCD($val1, $val2) = $gcd"


실행> groovy testWhile.groovy
Using: groovy testWhile.groovy [integer1] [integer2]
This finds the greatest common divisor of the given two integers.

실행> groovy testWhile.groovy -50, 200
GCD(-50, 200) = 50

실행> groovy testWhile.groovy 50, -30
GCD(50, -30) = 10

실행> groovy testWhile.groovy 0. 30
GCD(0, 30) = 30




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

소스 파일명: TestWhileLoop.java

  1. /*
  2.  *  Filename: TestWhileLoop.java
  3.  *
  4.  *  Purpose:  Example using the while loop syntax
  5.  *                while ....
  6.  *
  7.  *  Compile: javac -d . TestWhileLoop.java
  8.  *  Execute: java TestWhileLoop -200 300
  9.  *
  10.  */
  11. import java.lang.Math;
  12. public class TestWhileLoop {
  13.     // 사용법 표시
  14.     public static void printUsage() {
  15.          System.out.println("Using: java TestWhileLoop [integer1] [integer2]");
  16.          System.out.println("This finds the greatest common divisor of the given two integers.");
  17.     }
  18.     // Java 애플리케이션의 실행 시작 시점 main 메소드
  19.     // (C 언어의 main 함수에 해당)
  20.     public static void main(String[] args) {
  21.         if (args.length != 2) {
  22.             printUsage();
  23.             System.exit(1);
  24.         }
  25.         ////////////////////////////////////////////////
  26.         // 명령행 인자의 두 스트링을 가져와서
  27.         // 긴정수(long) 타입으로 변환하여
  28.         // 변수 val1과 val2에 저장한다.
  29.         long val1 = Long.parseLong(args[0]);
  30.         long val2 = Long.parseLong(args[1]);
  31.         long a, b, q, r, gcd;    // r은 나머지, q는 몫
  32.         // a는 |val1|, |val2| 중 큰 값
  33.         a = Math.abs(val1);
  34.         b = Math.abs(val2);
  35.         if (a < b) {
  36.             a = Math.abs(val2);
  37.             b = Math.abs(val1);
  38.         }
  39.         if (b == 0L) {
  40.             System.out.println("GCD(" + val1 + ", " + val2 + ") = " + a);
  41.             System.exit(0);
  42.         }
  43.         ////////////////////////////////////////
  44.         // Euclidean 알고리즘의 시작
  45.         //
  46.         // a를 b로 나누어 몫은 q에, 나머지는 r에 저장
  47.         q = a / b;
  48.         r = a % b;
  49.         ////////////////////////////////////////
  50.         // Euclidean 알고리즘의 반복 (나머지 r이 0이 될 때 까지)
  51.         while (r != 0L) {
  52.             a = b;
  53.             b = r;
  54.             q = a / b;
  55.             r = a % b;
  56.         }
  57.         // 나머지가 0이면 그 때 나눈 수(제수) b가 최대공약수(GCD)이다.
  58.         gcd = b;
  59.         // 최대공약수(GCD)를 출력한다.
  60.         System.out.println("GCD(" + val1 + ", " + val2 + ") = " + gcd);
  61.     }
  62. }

컴파일> javac -d . TestWhileLoop.java

실행> java TestWhileLoop
Using: java TestWhileLoop [integer1] [integer2]
This finds the greatest common divisor of the given two integers.

실행> java TestWhileLoop 200 300
GCD(200, 300) = 100

실행> java TestWhileLoop 50, -20
GCD(50, -20) = 10

실행> java TestWhileLoop -30, 0
GCD(-30, 0) = 30



Groovy를 사용하면 위의 소스를 (컴파일 과정 없이) 그대로 실행시킬 수 있다. 그대신 파일 확장자명을 groovy로 하여 저장하여야 한다. 아래는 파일명을 TestWhileLoop.groovy로 저장하여 실행시칸 경우이다.


실행> groovy TestWhileLoop.groovy
Using: java TestWhileLoop [integer1] [integer2]
This finds the greatest common divisor of the given two integers.

실행> groovy TestWhileLoop.groovy -200 500
GCD(-200, 500) = 100

실행> groovy TestWhileLoop.groovy 108, 180
GCD(108, 180) = 36

실행> groovy TestArguments.groovy -30, 0
GCD(-30, 0) = 30




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

소스 파일명: testIf.lua

  1. --[[
  2.    Filename: testIf.lua
  3.    Purpose:  Example using the conditional control structure syntax
  4.                  if .... else ...
  5.    Execute: lua testIf.lua [number]
  6. --]]
  7. -- 사용법을 보여주는 함수
  8. function printUsing()
  9.    print("Using: ruby testIf.rb [number]")
  10.    print("This determines whether the number is positive or not.")
  11. end
  12. -- 명령행 인자의 개수가 1이 아니면 사용법을 보여준다.
  13. if #arg ~= 1 then
  14.     printUsing()
  15.     os.exit(1)
  16. end
  17. -- 명령행 인자의 스트링을 가져와서
  18. -- 배정밀도 부동소수점수로 변환하여
  19. -- 변수 val에 저장한다.
  20. val = tonumber(arg[1])
  21. -- 변수 val에 저장된 값이 양수인지 음수인지 0인지를
  22. -- 판단하는 if...else... 조건문
  23. if (val > 0.0) then
  24.     print(val .. " is a positive number.")
  25. elseif (val < 0.0) then
  26.     print(val .. " is a negative number.")
  27. else
  28.     print(val .. " is zero.")
  29. end


실행> lua testIf.lua
Using: lua testIf.lua [number]
This determines whether the number is positive or not.

실행> lua testIf.lua 1.21
1.21 is a positive number.

실행> lua testIf.lua -1.21
-1.21 is a negative number.

실행> lua testIf.lua 0
0 is zero.




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

소스 파일명: testIfCPP.cpp

  1. #include <iostream>
  2. #include <cmath>        // atof() 함수 사용을 위해
  3. using namespace std;    // cout 사용을 위해
  4. // 사용법 표시 함수
  5. void printUsing() {
  6.     cout << "Using: testIfCPP [number]\n";
  7.     cout << "This determines whether the number is positive or not.\n";
  8. }
  9. // main 함수
  10. int main(int argc, char *argv[]) {
  11.     float val;
  12.     if (argc != 2) {
  13.         printUsing();
  14.         exit(1);
  15.         return 1;
  16.     }
  17.     // 명령행 인자의 스트링을 가져와서
  18.     // 배정밀도 부동소수점수로 변환하여
  19.     // 변수 val에 저장한다.
  20.     val = atof(argv[1]);
  21.     // 변수 val에 저장된 값이 양수인지 음수인지 0인지를
  22.     // 판단하는 if...else... 조건문
  23.     if (val > 0.0)
  24.         cout << val << " is a positive number.\n";
  25.     else if (val < 0.0)
  26.         cout << val << " is a negative number.\n";
  27.     else
  28.         cout << val << " is zero.\n";
  29.     return 0;
  30. }

컴파일> cl /GX testIfCPP.cpp

실행> testIfCPP
Using: testIfCPP [number]
This determines whether the number is positive or not.

실행> testIfCPP 1.234
1.234 is a positive number.

실행> testIfCPP 1.234
-1.234 is a negative number.

실행> testIfCPP 0
0 is zero.



※ Ch 5.5를 사용하여 컴피일 과정 없이 소스를 실행시키려면 인클루드문

        #incldue <cmath>



        #incldue <math.h>

로 고치면 된다. 그대신 부동소수점수의 출력이 다소 다르다.



실행> ch testIfCPP.cpp
Using: testIfCPP [number]
This determines whether the number is positive or not.

실행> ch testCPP.cpp 2.7
2.7000 is a positive number.

실행> ch testCPP.cpp -2.7
-2.7000 is a negative number.

실행> ch testCPP.cpp 0
0 is zero.




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

소스 파일명: testIf.c

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. // 사용법 표시 함수
  4. void printUsing() {
  5.     printf("Using: testIf [number]\n");
  6.     printf("This determines whether the number is positive or not.\n");
  7. }
  8. // main 함수
  9. int main(int argc, char *argv[]) {
  10.     float val;
  11.     if (argc != 2) {
  12.         printUsing();
  13.         exit(1);
  14.         return 1;
  15.     }
  16.     // 명령행 인자의 스트링을 가져와서
  17.     // 배정밀도 부동소수점수로 변환하여
  18.     // 변수 val에 저장한다.
  19.     val = atof(argv[1]);
  20.     // 변수 val에 저장된 값이 양수인지 음수인지 0인지를
  21.     // 판단하는 if...else... 조건문
  22.     if (val > 0.0)
  23.         printf("%g is a positive number.\n", val);
  24.     else if (val < 0.0)
  25.         printf("%g is a negative number.\n", val);
  26.     else
  27.         printf("%g is zero.\n", val);
  28.     return 0;
  29. }

컴파일> cl testIf.c

실행> testIf
Using: testIf [number]
This determines whether the number is positive or not.

실행> testIf 1.234
1.234 is a positive number.

실행> testIf -1.234
-1.234 is a negative number.

실행> testIf 0
0 is zero.


※ Ch를 사용하면 위의 소스 코드를 (컴파일 과정 없이) 그대로 실행시킬 수 있다.

실행> ch testIf.c
Using: testIf [number]
This determines whether the number is positive or not.

실행> ch testIf.c 1.01
1.01 is a positive number.

실행> ch testIf.c -1.01
-1.01 is a negative number.

실행> ch testIf.c 0
0 is zero.



Posted by Scripter
,

소스 파일명: testIf.py

  1. # coding=euc-kr
  2. """
  3.    Filename: testIf.py
  4.    Purpose:  Example using the conditional control structure syntax
  5.                  if .... else ...
  6.    Execute: python testIf.py [number]
  7. """
  8. import sys    # sys.argv를 위한 수입(import) 구문
  9. # 사용법을 보여주는 함수
  10. def printUsing():
  11.    print("Using: python testIf.py [number]")
  12.    print("This determines whether the number is positive or not.")
  13. # 명령행 인자의 개수가 1이 아니면 사용법을 보여준다.
  14. if len(sys.argv) != 2:
  15.     printUsing()
  16.     sys.exit(1)
  17. # 명령행 인자의 스트링을 가져와서
  18. # 배정밀도 부동소수점수로 변환하여
  19. # 변수 val에 저장한다.
  20. val = float(sys.argv[1])
  21. # 변수 val에 저장된 값이 양수인지 음수인지 0인지를
  22. # 판단하는 if...else... 조건문
  23. if val > 0.0:
  24.     print("%g is a positive number." % val)
  25. elif val < 0.0:
  26.     print("%g is a negative number." % val)
  27. else:
  28.     print("%g is zero." % val)


실행> python testIf.py
Using: python testIf.py [number]
This determines whether the number is positive or not.

실행> python testIf.py 6.25
6.25 is a positive number.

실행> python testIf.py -6.25
-6.25 is a negative number.

실행> python testIf.py 0
0 is zero.


※ 위의 소스 코드는 Jython으로도 수정 없이 그대로 실행된다.

실행> jython testIf.py
Using: python testIf.py [number]
This determines whether the number is positive or not.

실행> jython testIf.py 1.02
1.02 is a positive number.

실행> jython testIf.py -1.02
-1.02 is a negative number.

실행> jython testIf.py 0
0 is zero.


위의 소스 코드는 ipy 명령에 의하여 IronPython에서도 수정 없이 그대로 실행된다.




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

소스 파일명: testIf.rb

  1. =begin
  2.    Filename: testIf.rb
  3.    Purpose:  Example using the conditional control structure syntax
  4.                  if .... else ...
  5.    Execute: ruby testIf.rb [number]
  6. =end
  7. # 사용법을 보여주는 함수
  8. def printUsing()
  9.    print("Using: ruby testIf.rb [number]\n")
  10.    print("This determines whether the number is positive or not.\n")
  11. end
  12. # 명령행 인자의 개수가 1이 아니면 사용법을 보여준다.
  13. if (ARGV.length != 1)
  14.     printUsing()
  15.     exit(1)
  16. end
  17. # 명령행 인자의 스트링을 가져와서
  18. # 배정밀도 부동소수점수로 변환하여
  19. # 변수 val에 저장한다.
  20. val = ARGV[0].to_f
  21. # 변수 val에 저장된 값이 양수인지 음수인지 0인지를
  22. # 판단하는 if...else... 조건문
  23. if (val > 0.0)
  24.     print("#{val} is a positive number.\n")
  25. elsif (val < 0.0)
  26.     print("#{val} is a negative number.\n")
  27. else
  28.     print("#{val} is zero.\n")
  29. end


실행> ruby testIf.rb
Using: ruby testIf.rb [number]
This determines whether the number is positive or not.

실행> ruby testIf.rb 1.2
1.2 is a positive number.

실행> ruby testIf.rb -1.2
-1.2 is a negative number.

실행> ruby testIf.rb 0
0.0 is zero.



※ 위의 소스 코드는 JRuby로도 (수정 없이) 그대로 실행된다.

실행> jruby testIf.rb
Using: ruby testIf.rb [number]
This determines whether the number is positive or not.

실행> jruby testIf.rb 3.14
3.14 is a positive number.

실행> jruby testIf.rb -3.14
-3.14 is a negative number.

실행> jruby testIf.rb 0
0.0 is zero.




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

소스 파일명: testIf.groovy

  1. /*
  2.  *  Filename: testIf.groovy
  3.  *
  4.  *  Purpose:  Example using the conditional control structure syntax
  5.  *                if .... else ...
  6.  *
  7.  *  Execute: groovy testIf.groovy [number]
  8.  */
  9. def printUsing() {
  10.    println("Using: groovy testIf.groovy [number]")
  11.    println("This determines whether the number is positive or not.")
  12. }
  13. if (args.length != 1) {
  14.     printUsing()
  15.     System.exit(1)
  16. }
  17. ////////////////////////////////////////////////
  18. // 명령행 인자의 스트링을 가져와서
  19. // 배정밀도 부동소수점수로 변환하여
  20. // 변수 val에 저장한다.
  21. def val = args[0].toDouble()
  22. // 변수 val에 저장된 값이 양수인지 음수인지 0인지를
  23. // 판단하는 if...else... 조건문
  24. if (val > 0.0)
  25.     println("$val is a positive number.")
  26. else if (val < 0.0)
  27.     println("$val is a negative number.")
  28. else
  29.     println("$val is zero.")



실행> groovy testIf.groovy
Using: groovy testIf.groovy [number]
This determines whether the number is positive or not.

실행> groovy testIf.groovy 5
5 is a positive number.

실행> groovy testIf.groovy -5
-5 is a negative number.

실행> groovy testIf.groovy 0
0.0 is zero.




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

소스 파일명: TestIfThen.java

  1. public class TestIfThen {
  2.     public static void printUsing() {
  3.         System.out.println("Using: java TestIfThen [number]");
  4.         System.out.println("This determines whether the number is positive or not.");
  5.     }
  6.     // C 언어의 main 함수에 준하는 Java 언어의 main 메소드
  7.     public static void main(String[] args) {
  8.         if (args.length != 1) {
  9.             printUsing();
  10.             System.exit(1);
  11.         }
  12.         ////////////////////////////////////////////////
  13.         // 명령행 인자의 스트링을 가져와서
  14.         // 배정밀도 부동소수점수로 변환하여
  15.         // 변수 val에 저장한다.
  16.         double val = Double.parseDouble(args[0]);
  17.         // 변수 val에 저장된 값이 양수인지 음수인지 0인지를
  18.         // 판단하는 if...else... 조건문
  19.         if (val > 0.0)
  20.             System.out.println(val + " is a positive number.");
  21.         else if (val < 0.0)
  22.             System.out.println(val + " is a negative number.");
  23.         else
  24.             System.out.println(val + " is zero.");
  25.     }
  26. }

컴파일> javac -d . TestIfThen.java

실행> java TestIfThen
Using: java TestIfThen [number]
This determines whether the number is positive or not.

실행> java TestIfThen 2.1
2.1 is a positive number.

실행> java TestIfThen -2.1
-2.1 is a negative number.

실행> java TestIfThen 0
0.0 is zero.



Groovy를 사용하면 위의 소스를 (컴파일 과정 없이) 그대로 실행시킬 수 있다. 그대신 파일 확장자명을 groovy로 하여 저장하여야 한다. 아래는 파일명을 TestIfThen.groovy로 저장하여 실행시칸 경우이다.


실행> groovy TestIfThen.groovy
Using: java TestIfThen [number]
This determines whether the number is positive or not.

실행> groovy TestIfThen.groovy 2.1
2.1 is a positive number.

실행> groovy TestIfThen.groovy -2.1
-2.1 is a negative number.

실행> groovy TestIfThen.groovy 0
0.0 is zero.




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,
Lua 언어에서 명령행 인자는 변수 arg로 처리한다. 즉, arg는 Lua 언어에서 하나의 (명령행 인자 처리 변수) 예약어인 셈이다. 이 변수는 명령행 실행시 옵션으로 입력된 인자들을 스트링 값으로 모아둔 리스트 타입의 변수이다. 이 변수가 가리키는 리스트에 속한 아이템의 개수를 구하기 위해서는 전위 단항연산자 #을 선두에 붙이면 된다. 즉 #arg가 리스트에 속한 (아이템의 개수)-1이다. 그런데 Lua 언어에서는 Python 언어에서 처럼, 명령행 실행시 실행될 소스파일명의 인덱스 번호가 0번이므로, 아래의 소스 코드에서 우리가 처리할 명령행 인자들은 1번, 2번, 3번, .... 의 인텍스 번호를 갖는다.
(참고로, Lua 언어의 신택스는 테이블 타입의 자료 처리를 기반으로 하고 있으며, 리스트 타입이라고 하는 것도 실제로는 특수한 테이블 타입 중 하나인 셈이다.)

Lua 언어에서 줄 단위 주석문 기호는 --이다. 소스 코드의 어느 줄이든 -- 및 그 우측 부분은 모두 주석으로 처리된다. 이 기호는 Python/Ruby 언어의 줄 단위 주석문 기호 #에 해당하며, C/C++/Java/Groovy 언어의 줄 단위 주석문 기호 //에 해당한다.



소스 파일명: testArguments.lua
  1. -- 명령행 인자(command-line argument) 개수 출력
  2. print( "Count of arguments: " .. #arg )
  3. sum = 0.0
  4. for i = 1, #arg do
  5.     -- 스트링을 부동소수점수로 변환하여 누적
  6.     sum = sum + tonumber(arg[i])
  7. end
  8. -- 누적된 값을 출력
  9. print( "The sum of arguments is " .. sum)


실행> lua testArguments.lua 1 2 3 4
Count of arguments: 4
The sum of arguments is 10


실행> lua testArguments.lua 1 2 3 4.5
Count of arguments: 4
The sum of arguments is 10.5





Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,