You are on page 1of 5

//Quianzon, Janelle V. //SEM2 /Wednesday 6:00 – 9:00 PM/4ITE //December 10, 2012 7.8 1.

Prepare and test a method entitled square that returns the square of its single parameter. def square(int sq) { sq * sq } n1 = 9 n2 = 5 println 'The square root of ' +n1+ ' is: ' +square(n1) println 'The square root of ' +n2+ ' is: ' +square(n2) RESULT:

3. Write and test a method to determine whether a given time of day is before another. Each time is represented by a triple of the form 11, 59, AM, or 1, 15, PM. def compareDate(h1,m1,d1,h2,m2,d2) { if (d1=="AM" && d2=="PM") return true else if(d1 == 'AM' && d2 == 'AM' || d1 == 'PM' && d2 == 'PM') { if(h1==h2) { if(m1<m2) return true else return false

h2.m2.d1.m1.d2)) println h1+ ':' +m1 + d1+ ' is before ' +h2+ ':' +m2 + d2 else println h1+ ':' +m1 + d1+ ' is not before ' +h2+ ':' + m2 + d2 RESULT: .} else if(h1<h2) return true else return false } else return false } def h1 = 10 def m1 = 23 def d1 = "AM" def h2 = 11 def m2 = 23 def d2 = "AM" if(compareDate(h1.

def isEven(num) { if (num%2==0) return true else return false } def isPowerOfTwo(num) { if (num == 0) return true else if (num==1 && isEven(num)) isPowerOfTwo(num/2) else return false } def num = 20 if (isEven(num)) println num+ " is even" else . develop a recursive method isPowerOfTwo that determines if its single parameter is a power of 2. . 2. using isEven. are powers of the value 2..def h1 = 10 def m1 = 23 def d1 = "PM" def h2 = 11 def m2 = 23 def d2 = "AM" 4. First. The values 1. Then. 8. develop a method isEven that determines whether its single integer parameter is an even value. 4.. 16.

... that is.. reads the same forward and backward: def isPalindrome(str) { . } Using these two methods.. which accepts a list of Strings and concatenates them into a single String: def implode(strList) { .println num+ " is not even" if (isPowerOfTwo(num)) println num+ " is a power of two" else println num+ " is not a power of two" RESULT: Def num = 8 13. Develop a method entitled explode that transforms a string into a List of Strings of size one. } Now.. The method signature is: def explode(str) { . develop the method reverseString for reversing the characters of a String parameter: def reverseString(str) { . develop the method isPalindrome to return the boolean true if the single String parameter is palindromic. develop the complementary method implode.. } . } Finally.

m) otherwise Implement a method to realize this and show that gcd(18. m) = gcd(n.n) else return gcd(m.m) { if (m<n && n%m==0) return m else if (n<m) return gcd(m.15.m) RESULT: . It is defined recursively as: gcd(n. m) = gcd(n – m. The greatest common divisor of two integers can be determined from Euclid’s algorithm. m – n) if n < m gcd(n. 27) is 9.n%m) } def n = 18 def m = 27 println 'GCD of ' +n+ ' and ' +m+ ' is ' +gcd(n. def gcd(n. m) = n if n == m gcd(n.