TA5004 : COMPUTER PROGRAMMING - QUIZ 1

The option with boldface is the correct answer.

1. A set of rules used to instruct the program what operations to perform is called

a)pseudocode.

b)a walkthrough.

c)diagnostics.

d)a programming language.

 

2. A language that is an example of a scientifically oriented language is

a)FORTRAN.

b)BASIC

c)COBOL.

d)Pascal.

 

3. The highest level of programming language is

a)assembly.

b)COBOL.

c)natural.

d)machine.

 

4. The first step in the development of a program is

a)planning a solution.

b)defining the problem.

c)documenting the program.

d)testing the program.

 

5. The lowest level of programming language is

a)natural.

b)English.

c)assembly.

d)machine.

 

6. A programming language often used to teach programming to beginners is

a)machine language.

b)BASIC

c)assembly language.

d)Smalltalk.

 

7. A language that is more precise than English but less precise than a formal programming language is

a)Pascal.

b)translator.

c)pseudocode.

d)FORTRAN.

 

8. The rules of a programming language are called its

a)pseudocode.

b)coding.

c)compiling.

d)syntax.

 

9. Mistakes in a program that involve the improper use of the programming language are called

a)syntax errors.

b)diagnostics.

c)attributes.

d)logic errors.

 

10. A pictorial representation of an orderly, step-by-step solution to a programming problem is called a(n)

a)syntax.

b)ANSI symbol.

c)flowchart.

d)pseudocode.

 

11. Which is not output from the compiler?

a)load module

b)source program listing

c)object module

d)diagnostics

 

12. The process in which a group of peers review a program and offer suggestions to the programmer is known as

a)assembly.

b)a procedure.

c)documentation.

d)a walkthrough.

 

13. The set of instructions for the computer written by the programmer are called a(n)

a)program.

b)compiler.

c)flowchart.

d)attribute.

 

14. The original program is referred to as the

a)link module.

b)source module.

c)object module.

d)load module.

 

15. The module that is executed by the computer is the

a)link module.

b)source module.

c)object module.

d)load module.

 

16. A type of fourth-generation language used for retrieving data from databases is

a)FORTRAN.

b)C

c)query.

d)Pascal.

 

17. The language well-suited for business programming is

a)COBOL.

b)machine.

c)FORTRAN.

d)Pascal.

 

18. The programming language that can be used to produces code that approaches assembly language in efficiency while still offering high-level language features is

a)FORTRAN.

b)C

c)BASIC

d)Pascal.

 

19. A detailed written description of the program and the test results of the program is called

a)documentation.

b)pseudocode.

c)flowcharts.

d)diagnostics.

 

20. The level of language that is closest to spoken English is

a)natural.

b)machine.

c)FORTRAN.

d)very high level.

mzs:01-Jun-98 10:30 AM:kuiz_1

QUIZ 2 : Introduction To Java

1. The correct command to compile a Java program is

  1. javac myprog.java
  2. java myprog.java
  3. javac myprog
  4. java myprog

2. The correct command to run a Java program is

  1. javac myprog.java
  2. java myprog.java
  3. javac myprog
  4. java myprog

3. Which (complete) statement prints the text "Hello World!" on the screen?

  1. System.out.println(*Hello World!*)
  2. System.out.println("Hello World!");
  3. System.out.println('Hello World!');
  4. System.out.println("Hello World!")

4. Text in the /* */ will

  1. give command to preprocessor
  2. cause syntax error
  3. serve as documentation to human reader
  4. declare some memory location

5. Choose the valid Java identifiers:

i. R2D2

ii. $percap

iii. phone#

iv. iceCream

v. 99cents

  1. i, ii, iii, iv
  2. i, iv
  3. i, ii
  4. ii, iv, v

6. Which statement reads an integer into variable abc using the ccj package?

  1. Console.in.readInt(abc);
  2. abc = Console.in.readDouble();
  3. abc = Console.in.readInt();
  4. Console.in.readInt() = abc;

For questions 8 - 10, use the following initializations:

int i = 8, j = 5;

double x = 1.5, y = 0.5;

8. What is the value of this expression?

2*((i/8)+(4*(j-3))%(i+j-2))

  1. 9
  2. 18
  3. 7
  4. 11

9. What is the value of i after these statements were executed?

i += j;

i++;

  1. 9
  2. 14
  3. 13
  4. 6

10. What is the value of y after this statement?

y = x + y * (j + 1) / 2;

  1. 2.25
  2. 3.0
  3. 6.0
  4. 4.0

In question 11 to 13 you should determine the values of the following expressions. On each question, assume that:

 
double x = 2.0;
double y = -1.5;
int m = 18;
int n = 4;

 

11. x + n * y - (x + n) * y

  1. 6.25
  2. 5.0
  3. 20.0
  4. 47.0

12. m / n + m % n

  1. 6
  2. 0
  3. 2
  4. 3

13. 1 - (1 - (1 - (1 - n))))

  1. 3
  2. -3
  3. 4
  4. -4

14. Which Java expression is equal to the following arithmetic expression?

2+(ab+c)/3d

  1. 2 + a * b + c / 3 * d
  2. 2 + (a * b + c) / 3 * d
  3. 2 + (a * b + c) / (3 * d)
  4. 2 + (a * b + c) / 3 * d

15. Which Java statement defines a constant correctly?

  1. public static final BOTTLE_VOLUME = 2.0;
  2. public final double BOTTLE_VOLUME = 2.0;
  3. public static double BOTTLE_VOLUME = 2.0;
  4. public static final double BOTTLE_VOLUME = 2.0;

16. What is a magic number?

  1. Variables that were used to compute magical results.
  2. A number in a program appear without any explanation.
  3. Sequence of numbers that sums to a prime number.
  4. Sequence of numbers that sums to a negative number.

17. What is the main reason of using constants?

  1. Easy to read.
  2. Easy to change the value.
  3. Easier code maintenance.
  4. Programming style.

Since this quiz only contains 17 questions, you automatically got 3 free points.

Updated: 2:53 PM 21-Jun-98

If you want to verify some of the answer, you can try running this program: Quiz3.java

QUIZ 3 : Strings, Objects and Decisions

Strings

Questions 1 - 5 are based on the following definition:
String s = "University";

1.      What is the value of s.length() ?

    1. 10
    2. 9
    3. 11
    4. "y"

2.      What is the value of s.substring(0,1) ?

    1. 0
    2. "U"
    3. "n"
    4. 1

3.      What is the value of s.substring(0, s.length()) ?

    1. "niversity"
    2. "Universit"
    3. "y"
    4. "University"

4.      What is the value of s.substring(0,3) + s.substring(8,10) ?

    1. "University"
    2. "Universe"
    3. "Unity"
    4. "United"

5.      What is the value of s + s.toLowerCase() + "Malaysia" ?

    1. "UniversityuniversityMalaysia"
    2. "UniversityUNIVERSITYMalaysia"
    3. "UUM"
    4. "University university Malaysia"

Introduction to Objects

6.      How can we say that "a" is an object variable from class Time?

    1. a Time();
    2. Time(a);
    3. Time a;
    4. a Time;

7.      How can we create a new object from class Time?

    1. new Time();
    2. Time(new);
    3. Time() new;
    4. new (Time);

8.      How can we define and create a new object named "now" from class Time in one statement?

    1. now = new Time();
    2. Time now = new Time();
    3. now Time = new Time();
    4. Time now = Time(new);

9.      What is the correct way to add 100 seconds to the current value of "now"? (Remember, "now" is an object variable)

    1. addSeconds.now = 100;
    2. now = now + 100;
    3. now.addSeconds(100);
    4. addSeconds(100).now;

10.  getMonth is a method that returns the current month of an object from class Time. How do you print out the value of month in object "now"?

    1. System.out.println(now.getMonth());
    2. System.out.println(getMonth(now));
    3. System.out.println(getMonth());
    4. System.out.println(getMonth().now);
  1. Which statement makes a copy of existing object p and let q point to it?
    1. Point q = p.clone()(Point);
    2. Point p = (Point)q.clone();
    3. p = q;
    4. Point q = (Point)p.clone();

Decisions

  1. Which expression is true?
    1. (10 != 10)
    2. (5 <= 10)
    3. (5 > 10)
    4. (5 == 10)

Next 2 questions are based on the following definition:
String s1 = "abc", s2 = "ABC", s3 = "xyz";

  1. Which expression is false?
    1. s1.equals(s2)
    2. s1.toLowerCase().equals(s2)
    3. s1.equals(s2.toLowerCase())
    4. s1.equals(s3)
  2. Which expression evaluates to 0?
    1. s1.compareTo(s2)
    2. s2.compareTo(s1)
    3. s1.compareTo(s1)
    4. s1.compareTo(s3)
  3. Based on the following code, what letter will be printed if a is 50?
16.        
17.        if (a <= 200) 
18.             if (a < 100) 
19.                  if (a <= 0) 
20.                       System.out.println("A"); 
21.                  else 
22.                       System.out.println("B"); 
23.             else 
24.                  System.out.println("C"); 
25.        else 
26.             System.out.println("D"); 
    1. A
    2. B
    3. C
    4. D
  1. Based on the code for the above question, which range of variable "a" values will display the letter "C"?
    1. 0 < a < 100
    2. a <= 0
    3. 100 <= a <= 200
    4. 100 < a <= 200
  2. The following lines of code makes:
29.        
30.        if (a > b) z = a;
31.        if (a == b) z = 0;
32.        if (a < b) z = b;
    1. The smaller of a and b is stored in z.
    2. The larger of a and b is stored in z.
    3. The larger of a and b is stored in z unless a and b are equal, in which case z is assigned zero.
    4. The larger of a and b is stored in z unless a and b are not equal, in which case z is assigned zero.
  1. The if statement:
34.        
35.       if (20 > 25)
36.         System.out.println("impossible");
37.       else
  System.out.println("yes, right");
    1. Prints out "impossible".
    2. Prints out "yes, right".
    3. Will cause syntax error since 20 is not greater than 25.
    4. Will print nothing since 20 is not greater than 25.
  1. What is the value of i after the following statements?
39.        
40.         i = 3; j = 10;
41.         if ((3 * i) > j)
42.            i = i + 2;
43.            i = i + 3;
44.         i = i + 5;
    1. 11
    2. 6
    3. 8
    4. 14
  1. What is the value of j after the following statements?
46.        
47.         n = 3; j = 10;
48.         if (n == 5) j = 0;
49.         else if (n < 5) j = 1;
50.         else j = -1;
    1. 0
    2. 1
    3. -1
    4. 10

Updated: 7:55 PM 18-Jul-98

If you want to verify some of the answer, you can try running the program.

QUIZ 4 : Loops

1.      What are the output of the following code?

2.           import ccj.*;
3.            
4.           public class Myprog 
5.           {
6.              public static void main(String[] args)
7.              {
8.            
9.              int number = 1, sum = 0;
10.          while ( number < 11 )    
11.          {
12.              sum = sum + number;
13.              number = number + 2;
14.              System.out.println ("number=" + number + " sum=" + sum);
15.          }
16.        }
}

Answer:

number=3 sum=1
number=5 sum=4
number=7 sum=9
number=9 sum=16
number=11 sum=25

17.  Re-write the loop using a for loop.

Answer:

   for (int number = 1;  number < 11; number += 2 )    
   {
       sum = sum + number;
       System.out.println ("number=" + (number+2) + " sum=" + sum);
   }

Updated: 3:27 PM 15-Aug-98

QUIZ 5 : Loops, Functions and Classes

1.      Write a loop that will read integers and print out the total of all integers input. Use 9999 to stop the input. Do not include the 9999 in the total.
Answer:

2.            
3.            
4.            
5.            
6.            
7.            
8.            
9.            
10.        
11.        
12.        
13.        
14.        
15.        

16.  What is the difference between a function and a procedure?
Answer:

17.        
18.        
19.        
20.        
21.        
22.        
23.        
24.        

25.  Based on the following code, answer the questions below it.

26.       class Kereta
27.       {
28.               private int gear;
29.        
30.               Kereta () {gear = 0;} // constructor
31.        
32.               public void tukarGear(int arah)
33.               {
34.                      if (arah == 1)
35.                              gear++;
36.                      if (arah == -1)
37.                              gear--;
38.               }
39.        
40.               public void freeGear() { gear = 0; }
41.               public int infoGear() { return (gear); }
42.        
43.       } // tamat kelas       
44.        
45.       class GunaKereta
46.       {
47.         public static void main (String[] args)
48.         {
49.                      // statements here?
50.         }
}
    1. Create a new object from class kereta named Wira_saya.
    2. Create a new object from class kereta named Kancil_dia.
    3. Free the gear of Wira_saya, then change to gear 1.
    4. Free the gear of Kancil_dia, then change to gear -1 (reverse gear).
    5. Print out the current gear of both cars. (use System.out.println() )


Answer:

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Updated: 4:08 PM 22-Aug-98

QUIZ 6 : Arrays

[There are only 4 questions for this quiz. That is 0.5 mark for each question.]

Questions 1 - 3 are based on the following declaration:

 
int i, temp = 0;
int[] a = {3, 5, 7, 0, 2};

Choose the answer for questions 1 -3 from these alternatives:

  1. sorting the a elements.
  2. count for how many numbers in a that are greater than its first element.
  3. reversing the order of numbers in a.
  4. put the biggest value at the end of a.

1. What is the effect of this code segment?

for (i = 0; i < a.length/2; i++)
{
   temp = a[i];
   a[i] = a[a.length - i - 1];
   a[a.length - i - 1] = temp;
}

2. What is the effect of this code segment?

for (i = 0; i < a.length-1; i++)
{
if (a[i] > a[i + 1])
{
  temp = a[i];
  a[i] = a[i + 1];
  a[i + 1] = temp;
}
}

3. What is the effect of this code segment?

for (i = 0; i < a.length; i++)
{
  if (a[i] > a[0])
    temp++;
}

Questions 4 is based on this result function:

int result (int[] a)
{
int i, r;
r = 0;
for (i = 1; i < a.length; i++)
  if (a[i] > a[r])
    r = i;
return (r);
}

4. What is returned by the result function?

  1. index of the biggest value from array a.
  2. the biggest value from array a.
  3. index of the smallest value from array a.
  4. the smallest value from array a.

 

Quiz 1 : Introduction To Computing With Java

1.      Give the correct DOS command to compile a Java program named myprog

Answer: __________________________________

    1. javac myprog.java

2.      Give the correct DOS command to run a Java program named myprog

Answer: __________________________________

    1. java myprog
  1. Write a complete statement to print the text "I am here, now!" on the screen

Answer: ___________________________________________________

    1. System.out.println("I am here, now!");

4.      Text in the /* */ will

    1. give command to preprocessor
    2. cause syntax error
    3. serve as documentation to human reader
    4. declare some memory location

5.      Choose the valid Java identifiers:

6.                 i. WRONG_ANSWER

7.                 ii. phone#

8.                 iii. income@

9.                 iv. I_reallyLikeThisOne

v. 31October

    1. i, ii, iii, iv
    2. i, ii
    3. ii, iv, v
    4. i, iv

10.  Which statement reads an integer into variable abc using the ccj package?

    1. Console.in.readInt(abc);
    2. abc = Console.in.readInt();
    3. abc = Console.in.readDouble();
    4. Console.in.readInt() = abc;

11.  Which Java statement defines a constant correctly?

    1. public static final BOTTLE_VOLUME = 2.0;
    2. public final double BOTTLE_VOLUME = 2.0;
    3. public static double BOTTLE_VOLUME = 2.0;
    4. public static final double BOTTLE_VOLUME = 2.0;

12.  What is a magic number?

    1. Variables that were used to compute magical results.
    2. Sequence of numbers that sums to a prime number.
    3. A number in a program appear without any explanation.
    4. Sequence of numbers that sums to a negative number.

13.  What is the main reason of using constants?

    1. Easy to read.
    2. Easy to change the value.
    3. Easier code maintenance.
    4. Programming style.

For questions 10 - 11, use the following initializations:

int i = 8, j = 5;
double x = 1.5, y = 0.5;

14.  What is the value of this expression?

2*((i/8)+(4*(j-3))%(i+j-2))

Answer: __________________________________

    1. 18

15.  What is the value of i after these statements were executed?

i += j;
i++;

Answer: __________________________________

    1. 14

16.  What is the value of y after this statement?

y = x + y * (j + 1) / 2;

Answer: __________________________________

    1. 3.0

For questions 13 to 15, determine the values of the following expressions. On each question, assume that:

 
double x = 2.0;          double y = -1.5;
int m = 18;              int n = 4;

17.  x + n * y - (x + n) * y
Answer: _______

    1. 5.0

18.  m / n + m % n
Answer: _______

    1. 6

19.  1 - (1 - (1 - (1 - n))))
Answer: _______

    1. 4

20.  Write a Java expression that is equal to the following arithmetic expression

2+(ab+c)/3d

 

Answer: __________________________________

    1. 2 + (a * b + c) / (3 * d)

Updated: 28-Nov-98 16:00

QUIZ 2 : Strings, Objects and Decisions

Strings

Questions 1 - 4 are based on the following code segment:

      String s = "Universiti Utara Malaysia";
      String abc = s.substring(0,1) + s.substring(11,12) + s.substring(17,18);
      System.out.println(abc);  /* 1 */
 
      System.out.println(s.length());   /* 2 */
      String xyz = s.substring(s.length()-8, s.length());
      System.out.println(xyz);  /* 3 */
 
      String s1 = "aBc";
      System.out.println(s1.toLowerCase() + s1.toUpperCase()); /* 4 */

1.      What is printed by the line marked with /* 1 */? Answer: _______UUM__________

2.      What is printed by the line marked with /* 2 */? Answer: _______25__________

3.      What is printed by the line marked with /* 3 */? Answer: _________Malaysia__________

4.      What is printed by the line marked with /* 4 */? Answer: __________abcABC__________

Introduction to Objects

5.      How can we say that "a" is an object variable from class Time?

    1. a Time();
    2. Time(a);
    3. Time a;
    4. a Time;

6.      How can we create a new object from class Time?

    1. new Time();
    2. Time(new);
    3. Time() new;
    4. new (Time);

7.      How can we define and create a new object named "now" from class Time in one statement?

    1. now = new Time();
    2. Time now = new Time();
    3. now Time = new Time();
    4. Time now = Time(new);

Decisions

8.      If a is true, b is false and c is true, what is the value of the followings?

    1. (!a && b) || !c Answer:__________false
    2. !a || c) && !b Answer:__________true
    3. (!a != !c) Answer:__________false

9.      Study the following code. What will be the output if m is 17?

10.         if( m >= 17 )
11.           System.out.println ("Batman");
12.         else
13.           System.out.println ("Joker");
    System.out.println ("Robin");

Answer:

  Batman
  Robin
     -- because the third println is not part of else, it must be executed anyway.

14.  What is the output of the following code? Or we cannot tell due to lack of information?

15.         if( variable1 >= 85 || variable1 < 100 )
16.           System.out.println ("Yes");
17.         else
    System.out.println ("No");

Answer:

yes     -- because whatever is the value of variable,
     it must be either >= 85 or < 100 or both.
  1. This if statement:
19.       if (20 > 25)
20.         System.out.println("impossible");
21.       else
  System.out.println("yes, right");
    1. Prints out "impossible".
    2. Prints out "yes, right".
    3. Will cause syntax error since 20 is not greater than 25.
    4. Will print nothing since 20 is not greater than 25.

22.  A courier company, GoFast want to use a computer program to determine payable sum of their mileage claims. Their programmer ask for your help to draw the flowchart. The payable sum is calculated using this table.

23.       KM             Cents per KM
24.       First 500              50
25.       Next 200               40
Each extra km            30

Example:

    1. If the travel took 100 km, they should pay RM50.00.
    2. If the travel took 600 km, they should pay RM290.00 (that is 250 + 40).
    3. If the travel took 800 km, they should pay RM360.00 (that is 250 + 80 + 30).

Draw a flowchart to help your friend solve this problem. Do not combine conditons using && or ||.

Answer:

 

Updated: 08-Dec-98 12:33

If you want to verify the answer, you can try compile and run these source code: Quiz3a.java or Quiz3b.java.

QUIZ 3 : Functions and Loops

This is a lab-based quiz. You can:

  1. Use the PC in the lab (or anywhere else) to test your codes.
  2. Refer to notes or books.

Anyway, you must write down your answer on this sheet.

1.      Write a program that will:

    1. ask for integers until a negative number is typed-in.
    2. calculate the average of only even numbers typed (use a function to determine whether it is even).

The program should take appropriate action if the user has not key in any even number.

Sample interactions:

3.                 Number?5
4.                 Number?8
5.                 Number?6
6.                 Number?7
7.                 Number?10
8.                 Number?-1
9.                 Average of even numbers :8.0
10.             Number?9
11.             Number?7
12.             Number?15
13.             Number?-4
14.             No even number has been input
15.             Number?-2
16.             No even number has been input

You can also download the class file (save in javaccj directory) and then run it.

1.      Write a program that will:

a.                    ask for integers (X) until the user type in an integer between 1 and 12, inclusively.

b.                   print out the multiplication table of that integer (up to X times 10).

Sample interaction:

Number?13
Number?0
Number?-5
Number?7
7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70

You can also download the class file (save in javaccj directory) and then run it.


Updated: 03-Jan-99 10:49

Test 4

 

Diberi kelas ringkas kereta (Java) berikut, cuba tuliskan kenyataan di dalam kelas main dalam GunaKereta yang dapat menjalankan tugas diberikan:

 

class Kereta

{

   private     int gear;

 

   Kereta () {gear = 0;} // constructor

 

   public void tukarGear(int arah)

   {

         if (arah == 1)

               gear++;

         if (arah == -1)

               gear--;

   }

 

   public void freeGear() { gear = 0; }

   public int infoGear() { return (gear); }

 

} // tamat kelas    

 

class GunaKereta

{

public static void main (String[] args)

{

         // kenyatan-kenyataan di sini?

}

}

 

 

  1. Cipta suatu objek dari kelas kereta bernama wiraSaya.      

 

 

  1. Cipta suatu objek dari kelas kereta bernama kancilDia.    

 

 

  1. Bebaskan gear kereta wiraSaya, kemudian masuk gear 1.  

 

 

 

  1. Bebaskan gear kereta kancilDia, kemudian masuk gear undur (gear -1).   

 

 

 

  1. Cetak gear semasa kedua-dua kereta. (gunakan System.out.println() )

 

 

QUIZ 5 : Arrays and Algorithms, and Programming Languages

1.     Assume intArray is an array of 10 integers. Write a for loop that will reverse the order of numbers in intArray.

2.            
3.            
4.            
5.            
6.            
7.            
8.            
9.            
10.        
11.        
12.        
13.        

14. Choose the correct name for the following sorting method. Selection sort? Bubble sort? Mergesort? Quicksort?

15.               /* This code sort an array */
16.                  for (int i = 0; i < a.length - 1; i++)
17.                  {
18.                    for (int j = 0; j < a.length - 1 - i; j++)
19.                    {
20.                      if (a[j] > a[j+1])
21.                        swap(a, j, j+1);
22.                    }
           }

23. Discuss an example of a language construct where C is more expressive compared to Pascal.

24.        
25.        
26.        
27.        
28.        
29.        
30.        
31.        
32.        

Updated: 20-Feb-99 15:15

QUIZ 6 : Extra Quiz


1.        Write a function(method) that receives an integer array and an integer to find. Return the index/subscript where the item is found in the array. If the item is not found, return -1.

(10 points)

Answer:

 
 
 
 
 
 
 
 

2.        The following code edits a linked list consisting of three links.

3.                  
4.                         +--------+   +--------+   +--------+
5.                 head -->|  Ali   +-->|  Baba  +-->|  Minah +
6.                         +--------+   +--------+   +--------+

Draw a diagram to show how they are linked together after the code is executed.

EmployeeLink p1 = head.next;
EmployeeLink p2 = head;
while (p2.next != null)
  p2 = p2.next;
p2.next = head;
head = p1;

(7 points)

Answer:


7.        Draw a diagram to show how the following list looked after the operations are executed.

8.                  
9.                         +--------+   +--------+   +--------+
10.             top  -->|  Ali   +-->|  Baba  +-->|  Minah +
11.                     +--------+   +--------+   +--------+
12.             push("Chang");
13.             push("Samy");
14.             pop();

(7 points)

Answer:


15.     Draw a diagram to show how the following list looked after the operations are executed.

16.              
17.             tail                                          head
18.               |     +--------+   +--------+   +--------+     |
19.               +---->|  Ali   +-->|  Baba  +-->|  Minah +<----+
20.                     +--------+   +--------+   +--------+
21.             insert("Ricky");
delete();

(6 points)

Answer:

 

 

MOUSE CLICK

 

<H2>Modified version of Click.java program</H2>

 

<P>Please compare this program with the original one on page 112-113. (textbook)

 

<P>Use a style that <B>you</B> prefer.

 

<P>               -- mzs 12:48pm, 5 July 1998.

 

 

 

<HR>

 

 

 

<PRE>

 

/* Modified version of Click.java program

 

   to show the sequence of declaring and creating an object

 

   plus invoking a method.

 

*/

 

 

 

import ccj.*;

 

 

 

public class Click extends GraphicsApplet

 

{  public void run()

 

   {  String name;                                 /* declare first */

 

      name = readString("Please type your name:"); /* create an object */

 

 

 

      Circle c;                                    /* declare first */

 

      c = new Circle(new Point(0, 0), 1);          /* create an object */

 

      c.draw();                                    /* invoke a method */

 

 

 

      Point m;                                         /* declare first */

 

      m = readMouse("Please click inside the circle.");/* create an object */

 

      m.draw();                                        /* invoke a method */

 

 

 

      Message mymessage;                               /* declare first */

 

      mymessage = new Message(m, "You clicked here");  /* create an object */

 

      mymessage.draw();                                /* invoke a method */

 

   }

 

}

 

</PRE>

 


What you need for TA5004 course:

  1. Textbook: Ken Arnold, James Gosling, The Java Programming Language: 2nd Edition, Addison-Wesley 1998. ISBN: 0-201-31006-6.
  2. The EasyIn class. See the instructions on how to download and install it.
  3. The JDK from Sun site or if you are now in the UUM computer lab, you can download it faster from my page (UUM).

Pengenalan Polymorphism - Overloading

Kemahiran perlu diperolehi:

  1. Membuat kelas yang mempunyai ciri overloading
  2. Menjawab beberapa soalan asas berkaitan overloading

 
/* contoh aturcara yang menunjukkan bagaimana untuk overload the method.
   mzs -- 07-Dec-98 11:43
*/
class Kereta
{
        private int gear; // data atau member variables
 
        Kereta () {gear = 0;} // constructor
 
        public void tukarGear(int arah)       // method tukarGear pertama
        {
               if (arah == 1)
                       gear++;
               if (arah == -1)
                       gear--;
        }
 
        public void tukarGear(int gearAsal, int gearBaru) // kedua
        {
               if (gearBaru - gearAsal <= 4) // implementation checking
                       gear = gearBaru;
        }
 
        public void freeGear() { gear = 0; }
        public int infoGear() { return (gear); }
 
} // tamat kelas Kereta
 
 
class GunaKereta
{
  public static void main (String[] args)
  {
        Kereta wiraSaya = new Kereta();
        System.out.println("Gear wiraSaya sekarang = " + wiraSaya.infoGear());
 
        wiraSaya.tukarGear(1); // panggil method pertama
        wiraSaya.tukarGear(1);
        System.out.println("Gear wiraSaya sekarang = " + wiraSaya.infoGear());
 
        wiraSaya.tukarGear(2, 5); // panggil method kedua
        System.out.println("Gear wiraSaya sekarang = " + wiraSaya.infoGear());
  }
}

Output

Gear wiraSaya sekarang = 0
Gear wiraSaya sekarang = 2
Gear wiraSaya sekarang = 5

-- Tamat -- disediakan pada: 07-Dec-98 11:45

Pengenalan Polymorphism - Overloading(2)

Kemahiran perlu diperolehi:

  1. Membuat kelas yang mempunyai ciri overloading
  2. Menjawab beberapa soalan asas berkaitan overloading

2.Copy and paste fail berikut dan savekan sebagai "LawanTembak.java".

 
/* contoh aturcara yang menunjukkan bagaimana untuk overload the method.
   mzs -- 1:09 AM 16-Mar-98 :
   modified: 12:02 PM 21-Jul-98
*/
 
class Senjata {
 
  private int max_peluru;
  private int bakiPeluru;
  private String namaSenjata;
 
  // constructor : terima nama dan juga baki peluru
  Senjata (String nama, int bakiPeluruMula) {
    namaSenjata = nama;
    max_peluru = bakiPeluruMula;
    bakiPeluru = bakiPeluruMula;
  } // tamat constructor pertama
 
  // method Tembak #1: tembak sekali sahaja, manual
  void Tembak () {
    if ( bakiPeluru > 0) {
      System.out.println( namaSenjata + " tembak... PENG!");
      bakiPeluru--;
    }
    else
      System.out.println("Opps... peluru dah habis!");
  } // tamat method Tembak
  
  // method Tembak #2: tembak banyak kali (automatik?)
  void Tembak (int kali) {
    int i;
    System.out.print( namaSenjata + " tembak... ");
    for (i = 1; i <= kali; i++) {
      if ( bakiPeluru > 0) {
        System.out.print( "PENG! ");
        bakiPeluru--;
      }
      else {
        System.out.println("Opps... peluru dah habis!");
        break;
      }
    }
    System.out.println(); // hanya nak bawa kursor ke line berikut
 
  } // tamat method Tembak
 
  void cetakState () {
    System.out.println("----  Nama : " + namaSenjata
      + " --> Peluru ada lagi  : " + bakiPeluru );
  }
 
  void isiPeluru () {
     bakiPeluru = max_peluru;
     System.out.println(namaSenjata 
         + " telah diisi penuh. Peluru ada lagi  : " + bakiPeluru );
  }
 
} // tamat kelas Senjata
 
class LawanTembak {
  public static void main (String args[]) {
 
    Senjata pistol1 = new Senjata("Pistol Koboi", 6);
    Senjata mesingan1= new Senjata("Mesingan", 50);
 
    pistol1.cetakState();
    pistol1.Tembak();          // panggil method Tembak() pertama
    pistol1.cetakState();
 
    System.out.println(); // selang sebaris
    mesingan1.cetakState();
    mesingan1.Tembak(7);       // panggil method Tembak() kedua
    mesingan1.cetakState();
 
    System.out.println(); // selang sebaris
    mesingan1.isiPeluru();
 
  } // tamat main
 
} // tamat class LawanTembak

2.Kompil aturcara anda: Pada DOS prompt, taipkan

javac LawanTembak.java


Jika tiada ralat, tiada mesej diberikan.

4.Laksanakan aturcara anda: Taipkan pula

java LawanTembak

 

Anda mendapat output seperti:

----  Nama : Pistol Koboi --> Peluru ada lagi  : 6
Pistol Koboi tembak... PENG!
----  Nama : Pistol Koboi --> Peluru ada lagi  : 5
 
----  Nama : Mesingan --> Peluru ada lagi  : 50
Mesingan tembak... PENG! PENG! PENG! PENG! PENG! PENG! PENG!
----  Nama : Mesingan --> Peluru ada lagi  : 43
 
Mesingan telah diisi penuh. Peluru ada lagi  : 50

Jawab soalan-soalan berikut:

  1. Berikan kenyataan (setelah anda cuba di dalam fungsi main) yang dapat:
    1. Menembak mesingan1 sebanyak 20 kali?
    2. Mengisi peluru pistol1 hingga penuh kembali?
  2. Cuba tembak mesingan1 hingga habis peluru dan lihat apakah mesejnya.
  3. Apakah overloading?
  4. Cuba anda overload method isiPeluru() supaya method yang baru dapat menerima bilangan peluru yang hendak diisi, bukannya diisi hingga penuh. Panggilan terhadap method baru itu boleh berupa:
    mesingan1.isiPeluru(10);
    Contoh kenyataan:
5.            
6.               mesingan1.isiPeluru(); // isi hingga penuh
7.               mesingan1.Tembak(17); // tembak 17 kali
    mesingan1.isiPeluru(10); // isi balik 10 butir peluru


Maka outputnya:

Mesingan telah diisi penuh. Peluru ada lagi  : 50
Mesingan tembak... PENG! PENG! PENG! PENG! PENG! PENG! PENG! PENG! PENG! PENG! 
PENG! PENG! PENG! PENG! PENG! PENG! PENG!
Mesingan telah diisi. Peluru ada lagi  : 43

-- Tamat -- disediakan pada: 1:45 pm 21-Jul-98 -- ubahsuai terakhir: 02-Jan-99 12:18

Inheritance & Polymorphism - Overriding

Kemahiran perlu diperolehi:

  1. Membuat kelas baru dari kelas sedia ada
  2. Membuat method baru yang override method dalam superclass.
  3. Menjawab beberapa soalan asas berkaitan inheritance dan overriding

1.Copy and paste fail berikut dan savekan sebagai "CubaMeriam.java".

 
/* contoh aturcara yang menunjukkan bagaimana untuk override the method.
   mzs -- 1:55 PM 21-Jul-98
*/
 
class Senjata {
 
  protected int max_peluru; // protected supaya boleh dicapai oleh waris.
  protected int bakiPeluru;
  protected String namaSenjata;
 
  // Semua method dalam kelas Senjata tidak berubah -- sama seperti program terdahulu

 
  // Anda mesti sertakan semua method itu di sini.
  
} // tamat kelas
 
class Meriam extends Senjata {
 
  Meriam (String nama, int bakiPeluruMula) { // constructor
     super(nama, bakiPeluruMula); // panggil constructor superclass, i.e. Senjata
  }
 
  void isiPeluru () { // override the method isiPeluru() in class Senjata
     bakiPeluru = bakiPeluru + 1;
     System.out.println(namaSenjata 
         + " telah ditambah SATU peluru. Peluru ada lagi : " + bakiPeluru );
  }
} // tamat kelas Meriam
 
class CubaMeriam {
  public static void main (String args[]) {
 
    Meriam meriam1 = new Meriam("Meriam", 10);
 
    meriam1.cetakState();
    meriam1.Tembak();
    meriam1.Tembak();
    meriam1.Tembak();
    meriam1.Tembak();
    meriam1.cetakState();
 
    System.out.println(); // selang sebaris
    meriam1.isiPeluru();
 
  } // tamat main
} // tamat class

2.Kompil aturcara anda: Pada DOS prompt, taipkan

javac CubaMeriam.java


Jika tiada ralat, tiada mesej diberikan.

3.Laksanakan aturcara anda: Taipkan pula

java CubaMeriam

 

Anda mendapat output seperti:

----  Nama : Meriam --> Peluru ada lagi  : 10
Meriam tembak... PENG!
Meriam tembak... PENG!
Meriam tembak... PENG!
Meriam tembak... PENG!
----  Nama : Meriam --> Peluru ada lagi  : 6
 
Meriam telah ditambah SATU peluru. Peluru ada lagi : 7

Jawab soalan-soalan berikut:

  1. Apakah inheritance? Apakah kebaikannya?
  2. Apakah overriding?
  3. Apabila diberikan kenyataan meriam1.isiPeluru(); maka method isiPeluru() manakah yang sebenarnya dilaksanakan?
  4. Jika diberikan kenyataan meriam1.isiPeluru(3); maka method isiPeluru() manakah yang dilaksanakan?
  5. Meriam apabila ditembak tidak berbunyi "PENG!". Cuba anda override method Tembak() dengan satu method yang baru supaya dapat berbunyi "BOOM!" apabila ditembak. Contoh kenyataan:
    meriam1.Tembak();
    Maka outputnya:
    Meriam tembak... BOOM!

-- Tamat sesi makmal 4.-- disediakan pada: 2:45 pm 21-Jul-98 -- ubahsuai terakhir: 02-Jan-99 12:30

<H2>PANDUAN MENYUSUN ATUR ATURCARA DAN

 

PIAWAIAN ATURCARA Java DALAM KURSUS TA5004

 

</H2>

 

<P>

 

Kenapa susunatur aturcara yang tinggi readability itu penting?

 

<I>

 

Supaya aturcara senang di baca dan difahami oleh sesiapa sahaja, termasuk anda sendiri!

 

</I></P>

 

 

 

<HR>

 

<P><B>Lekukan</B></P>

 

<P>Mesti ada lekukan dalam setiap pernyataan yang terkandung dalam {}, () dan [], (iaitu lekukkan badannya) -- sekiranya pernyataan-pernyataan itu tidak muat pada satu baris.

 

Gunakan lekukan yang jaraknya lebih dari 1 aksara. Lekuk sebanyak 3 atau 4 aksara digalakkan.

 

</P>

 

<P>Contoh 1:</P>

 

 

 

<PRE>

 

public static void main(String[] args)

 

{

 

   int i; /* lekuk seperti baris ini */

 

   if (...)

 

   {

 

      ... /* lekuk seperti kandungan for ini */

 

      ...

 

   }

 

   ...

 

}

 

</PRE>

 

Contoh 2:

 

<PRE>

 

while (number < ARRAYSIZE &&

 

    data_pertama == data_kedua && /* lekuk spt. ini */

 

    data_pertama != data_ketiga

 

) {...}

 

</PRE>

 

 

 

<B>Perhatian:</B>

 

Sekiranya penutup-penutup kurungan }, ) dan ] tidak muat untuk berada sebaris dengan pembukanya, penutup kurungan itu mesti berada pada lajur yang sama dengan pembukanya. (lihat kedua-dua contoh di atas.)

 

 

 

Jangan takut untuk meletakkan banyak ruang kosong untuk menyusunatur aturcara anda, dengan tujuan memudahkan pembacaannya.

 

 

 

<HR>

 

<P><B>Komen</B></P>

 

Jangan terlalu kedekut komen! Ini akan menyusahkan anda sendiri. Letak komen pada:

 

<OL>

 

<LI>bahagian atas setiap aturcara (nama anda, tujuan aturcara, dsb.)</LI>

 

<LI>setiap bahagian utama aturcara (contoh: while/for untuk apa, mencetak hasil, dsb)</LI>

 

<LI>sebelum setiap definisi fungsi (contoh: tujuan fungsi, apa yang dipulangkan, dsb.)</LI>

 

<LI>selepas setiap } yang berada lebih dari 10 baris dari pembukanya (mesti !)</LI>

 

</OL>

 

 

 

<HR>

 

<B>Pengenal</B>

 

<OL>

 

<LI>Namakan dengan nama yang mudah difahami.</LI>

 

<LI>Pisahkan perkataan dengan underscore atau mulakan perkataan dengan

 

huruf besar.</LI>

 

<UL>

 

<LI>Untuk pemalar, gunakan hanya huruf besar.</LI>

 

</UL>

 

<LI>Semasa mengisytiharkan pembolehubah dan pemalar, lakukan satu sebaris.</LI>

 

</OL>

 

 

 

<HR>

 

<B>Lain-lain</B>

 

<OL>

 

<LI>Nilai khusus selain dari 0 dan 1 tidak sepatutnya ada dalam badan

 

aturcara. Jadikannya pemalar dengan menjadikannya <CODE>final</CODE>, supaya senang anda mengubah nilainya.</LI>

 

 

 

<LI>Selalu cetak semula input, supaya dapat diperiksa output yang betul telah dikeluarkan.

 

Contoh: (jika pengguna masukkan "kucing" kepada aturcara yang mengira panjang rentetan)

 

<PRE>

 

Rentetan: "kucing"

 

Panjangnya: 6</PRE>

 

</LI>

 

 

 

<LI>Global constants, OK tetapi Global variables kotor dan menyemakkan. Hanya dalam aturcara yang besar sahaja, di mana penggunaan global variables tidak dapat dielakkan, anda boleh menggunakannya.</LI>

 

 

 

<LI>Selalunya, fungsi-fungsi akan buat tugasnya sahaja (iaitu, untuk apa fungsi itu dicipta?), bukan lakukan kerja-kerja input/output, kecuali memang tujuannya untuk melakukan kerja-kerja input/output.</LI>

 

 

 

Sebagai panduan, selain output yang betul, program anda juga akan dinilai dari segi:

 

<OL type = a>

 

<LI>lekukan yang kemas dan konsisten</LI>

 

<LI>juga berkaitan penggunaan {}, () dan []</LI>

 

<LI>komen yang memadai</LI>

 

<LI>komen selepas setiap } yang berada lebih dari 10 baris dari { (pembukanya)</LI>

 

<LI>penggunaan pengenal yang bermakna</LI>

 

<LI>cukup ruang kosong antara bahagian-bahagian aturcara</LI>

 

</OL>

 

</OL>

 

 

 

<HR>

 

<P>

 

Semua panduan dan piawaian yang diberi ini tidak semestinya sama dengan apa yang akan anda temui semasa bekerja nanti. Bagaimana pun, selalunya setiap organisasi akan mempunyai piawaian aturcaranya sendiri yang harus diikuti oleh semua yang terlibat dalam pengaturcaraan. Oleh itu, berlatih mengikut piawaian begini adalah suatu amalan yang baik! Kalau tempat anda bekerja itu belum mempunyai piawaiannya sendiri, andalah yang cipta... .

 

</P>

 

 

 

mzs-prog_std-7/7/96.

 

TJ3044: Pembangunan Aplikasi Rangkaian: Projek

Satu projek dua orang pelajar sahaja. Seperti yang dinyatakan, setiap tajuk terdiri dari beberapa sub-projek. Setiap kumpulan akan buat sub yang berlainan, yang apabila digabungkan (diharapkan) membentuk satu aplikasi lengkap. Sila pilih dari senarai di bawah -- dan berikan nama serta nombor matrik ahli kumpulan.


Masih terbuka:

  1. Sistem Penjanaan Soalan Aturcara Java/C/C++

Untuk digunakan oleh para pelajar (dan pengajar) pengaturcaraan. Pengguna boleh lawat laman web, kemudian diberikan soalan untuk dijawab. Soalan itu dijanakan secara automatik oleh aturcara CGI -- berdasarkan beberapa kehendak pengguna asalnya. Kehendak pengguna itu boleh berupa konsep aturcara seperti struktur pemilihan (if, switch), struktur pengulangan (while, do, for), tatasusunan, dsb. Markah semasa sentiasa diberikan.
Ciri-ciri terlibat: pengaturcaraan melibatkan nombor rawak, pengetahuan asas tentang bahasa C, pangkalan data juga boleh dilibatkan (spt menyemak nama pengguna dan menentukan soalan yang diberikan tidak berulang dengan yang pernah diberi).
Bilangan kekosongan: 5 projek.

  1. Sistem Penjanaan Laman Web

Untuk digunakan oleh para pelajar kursus TJ3044 (kursus ini) dan lain-lain. Pengguna masukkan tajuk, heading, kandungan, dsb dan program CGI janakan laman webnya. Lebih kurang seperti WEB Wizard, tetapi berasaskan web.
Ciri-ciri terlibat: pengetahuan asas tentang HTML, pangkalan data juga boleh dilibatkan (spt memberikan imej yang boleh digunakan dalam laman web).
Bilangan kekosongan: 3 projek.

  1. Penukar Format Kod Sumber ke HTML

Pengguna masukkan kod aturcara, program CGI tukarkan ke bentuk HTML. Lebih kurang seperti Code to HTML Converter, tetapi lebih mudah, untuk satu bahasa sahaja (Java?).
Ciri-ciri terlibat: Pengaturcaraan melibatkan rentetan, pengetahuan asas bentuk kenyataan dalam C/C++/Java. pangkalan data mungkin tidak terlibat.
Bilangan kekosongan: 3 projek.

  1. Penukar Kod Sumber C ke C++

Pengguna masukkan kod aturcara C (yang mudah sahaja), program CGI tukarkan ke bentuk aturcara C++. Yang perlu ditukar hanya arahan scanf ke cin, printf ke cout, dan include. Siapa tahu program seperti ini yang dah ada di web, sila beritahu saya.
Ciri-ciri terlibat: Pengetahuan asas algoritma dan struktur data (untuk buat tindanan), pengetahuan asas berkenaan format arahan input/output dalam C dan C++. Pangkalan data mungkin tidak terlibat.
Bilangan kekosongan: 3 projek.

  1. -- akan ditambah lagi kemudian...

Sudah diambil:

  1.  
  2.  
  3.  

Kemas kini: 08-Nov-99 11:20


<< Balik ke laman kursus TJ3044.

Quiz 1 : Introduction To Computing With Java

1.      State a function of each of these computer components: (3 marks)

    1. Input devices : _______________________________________________________
    2. Output devices : ______________________________________________________
    3. RAM (main memory) : _________________________________________________

2.      Write a short paragraph describing phases went through in loading (from a hard-disk into the RAM) and executing a computer program. (4 marks)
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________

3.      List 3 conditions to make a valid Java indentifier. (3 marks)

    1. _______________________________________________________
    2. _______________________________________________________
    3. _______________________________________________________

4.      Study the Java program below and answer the following questions: (5 marks)

5.    public class Quiz0102 {
6.      public static void main(String[] args) {  
7.        int amount = 240;
8.        int a =  amount / 100;             
9.        int b = (amount % 100 ) / 10;  
10.    System.out.println(a + " and " + b);
11.  } /* end of main */
} /* end of class */

a.       What is the filename that we should give to the above program?
____________________________

b.      What command should we issue to compile the program?
____________________________

c.       What command should we issue to run the program?
____________________________

d.      What is the output of the above program?
____________________________

e.       If we change the line int amount = 240; into int amount = 130;, what will be the output?
____________________________


Name: __________________________________________ Metric#:_________________


<<Back.
Updated: 13-Jun-99 13:01

Quiz 2 : Decisions and Loops

Please try to run the answer. -- and have the output.
Direction:
You must tick 2 correct answers from 4 choices (a b c d). 3 points for each multiple-choice question.

  1. You get 3 points if you choose 2 and both are correct answers.
  2. You get 2 points if you choose 2 and only 1 is correct.
  3. You get 1 point if you choose only 1 and that is one of the correct answers.
  4. You get -1 point if you choose 2 and both are wrong answers.
  5. You get 0 point for any other combinations.

1.      Which expressions are true?

    1. ___ (9 < 10 && 10 <= 10)
    2. ___ (9 != 9 || 8 != 8)
    3. ___ (true != !false)
    4. ___ (8 * 8 >= 64 % 8)

2.      Which statements make variable a becomes 10?

    1. ___ if (8 % 2 == 0) a = 10;
    2. ___ if (10 % 5 == 0); a = 10;
    3. ___ if (8 % 10 == 0) a = 10;
    4. ___ if (5 * 2 != 10) a = 10;

3.      Which expressions ensure that integer variable x is within the range of 5 - 10, inclusively?

    1. ___ (x >= 5 && x <= 10)
    2. ___ (!(x < 5 && x > 10))
    3. ___ (x >= 5 || x <= 10)
    4. ___ (!(x < 5 || x > 10))

4.      Which loops make integer variable j becomes 25 when the loop ends?

    1. ___ i = 1; j = 0; while (i < 10) {j += i; i += 2;}
    2. ___ i = 0; j = 0; while (i <= 9) {i += 2; j += i;}
    3. ___ i = 0; j = 0; while (j < 25) {j += i; i += 2;}
    4. ___ j = 100; while (j != 25) {j /= 4;}

5.      Which loops correctly find the Least Common Multiply (LCM) of 6 and 10?

    1. ___ x = 2; do {x++;} while (x % 6 != 0 && x % 10 != 0);
    2. ___ x = 2; do {x++;} while (x % 6 == 0 || x % 10 == 0);
    3. ___ x = 2; do {x++;} while (x % 6 != 0 || x % 10 != 0);
    4. ___ x = 2; do {x++;} while (!(x % 6 == 0 && x % 10 == 0));

6.      Which loops print the sequence 1, 2, 3, 4, 5 ?

    1. ___ for (i = 1; i <= 5; i++) System.out.print(i + ", ");
    2. ___ for (i = 0; i <= 5; i++) System.out.print(i + ", ");
    3. ___ for (i = 0; i < 5; i++) System.out.print((i + 1) + ", ");
    4. ___ for (i = 2; i < 6; i++) System.out.print((i - 1) + ", ");

Name: __________________________________________ Metric#:_________________


<<Back.
Updated: 04-Jul-99 12:58

QUIZ 3 : OOP I and II


1.      Give the output of the following program:

2.    public class Quiz3 {
3.      public static void main(String[] args) {
4.     
5.         // Create object
6.         StringBuffer phrase = new StringBuffer("Programming is NOT fun");
7.     
8.         System.out.println("Before:" + phrase);
9.         for (int i = 0; i < phrase.length() - 1; i++) {
10.       if (phrase.charAt(i) == 'O' || phrase.charAt(i) == 'o') {
11.         phrase.setCharAt(i + 1, '#');
12.       }
13.     }
14.     System.out.println("After :" + phrase);
15. 
16.     // Create object
17.     StringBuffer phraseSB = new StringBuffer("Programming is fun");
18. 
19.     System.out.println("Phrase: " + phraseSB);
20. 
21.     // Check for occurence
22.     System.out.println("g is found at " + phraseSB.toString().indexOf('n'));
23. 
24.   } /* End of main */
25.} /* End of class */

The source: [Quiz3.java]
Answer:

Before:Programming is NOT fun
After :Pro#ramming is NO# fun
Phrase: Programming is fun
g is found at 9

26.  What is the maximum and minimum value will be printed by the following program?

27.public class Quiz3b {
28.  public static void main(String[] args) {
29. 
30.    System.out.println("\n\nAnother 100 random numbers");
31.    for (int i = 0; i < 100; i++) {
32.      System.out.print(3 + Math.round((Math.random()*10)) + ", ");
33.    }
34. 
35.   } /* End of main */
36.} /* End of class */

The source (differs a bit): [Quiz3b.java]
Answer:Min: 3 Max: 13

37.  State the relations of the following terms:

    1. Objects and classes: _________________________________________________________________________________ _________________________________________________________________________________
    2. Methods and data: _________________________________________________________________________________ _________________________________________________________________________________

Name: __________________________________________ Metric#:_________________


<<Back.
Updated: 01-Aug-99 15:37

QUIZ 4 : OOP3 and Arrays

1. What is the effect of this code segment?

for (i = 0; i < a.length-1; i++) {
if (a[i] > a[i + 1]) {
  temp = a[i];
  a[i] = a[i + 1];
  a[i + 1] = temp;
}
}

2. What is the effect of this code segment?

for (i = 0; i < a.length/2; i++) {
   temp = a[i];
   a[i] = a[a.length - i - 1];
   a[a.length - i - 1] = temp;
}

3. What is returned by the result function?

int result (int[] a) {
int i, r;
r = 0;
for (i = 1; i < a.length; i++)
  if (a[i] < a[r])
    r = i;
return (r);
}

4. What is the effect of this code segment?

int count = 0;
for (i = 0; i < a.length; i++) {
  if (a[i] < a[a.length-1])
    count++;
}

5. Define these terms:

 
1. Inheritance:
 
 
2. Method overriding:
 
 

Quiz 5 : Sorting & Programming Languages

  1. Sort these data using Selection sort. Show the data sequence after each pass.
               4  9  2  1  6  8
  1. Give an example for each of these:
    a) multiplicity of features in Java that give bad readability to the programs written in that language.
    b) a new data type in Java that increase the readability compared to C/C++.

3.      Explain this: why programs written in a compilation system run faster compared to programs written in an interpreted system?


<<Back.
Updated: 21-Sep-99 12:38

TA5004: Sample Exam Questions

Most of these questions have appeared on previous semester exams for TA1013 Pengaturcaraan Awalan course (for IT undergraduates). The original versions were in C/C++. Please let me know if you find any error. I don't have enough time to check all codes work in Java as they did in C/C++.

In exams, there are marks associated with each question so that you'll know how long the answer is expected to be or much time/effort you should spend on each question.


INTRODUCTION TO COMPUTING

1.      List the 6 steps needed to solve a problem using computer program.

2.      a) What is pseudocode? b) What is the advantage of using it?

3.      What are the use of the followings? a) editor b) compiler

4.      What is the different of logic error and syntax error?

5.      What is the different of compiled program and interpreted program?

6.      a) What is the different of high level and low level language? b) Give simple explanation of algorithm, pseudocode and flowchart.

7.      A computer program is normally completed after the programmer had done editing, compiling, and executing (running) the program. Explain those 3 steps you take to complete a Java program.


PROBLEM SOLVING

8.      "Calculate the pay for an employee given hours worked and pay rate per hour." Based on that problem, answer the following questions:
a. What is the suitable input to the problem?
b. What is the suitable output of the problem?
c. Write the pseudocode to solve the problem.

9.      Your friend have to write a program to calculate electricity bills. She asked for your help to draw the flowchart. The payable sum is calculated using this table.

10. 
11.Unit                     Cents per unit
12.First 100        20
13.Next 200         25
14.Each extra unit          28

Units used are based on metre reading. Example: if previous reading is 2300, current reading is 2800, the payable sum is RM126.00 . Draw a flowchart to help your friend solve this problem.


INTRODUCTION TO JAVA & FIRST PROGRAMS

15.  State 3 conditions to build an identifier in Java.

16.  Give the output of this code segment:

17. 
18.  int a, b;
19.  a = 2;
20.  a *= ( (3 + 5) / 2 ) - 9;
21.  System.out.println(a);
22. 
23.  a = 4;
24.  b = 20; b /= a; b--;
25.  System.out.println(b);
26. 
27.  a = 5; b = 3;
28.  a += b;
29.  System.out.println(a);

Strings and Objects

I don't have the chance to compose questions for this 2 topics, but you can still have a look at our Quiz 3 for some hints about the questions concerning Strings and Objects.


DECISIONS

30.  Give the output of this code segment if the input is:
i. 2, 3, 4.
ii. 15, 5, 3.

31. 
32.   int a = 10, b = 5, c = 6, d, e, f;
33.   System.out.print("Type in 3 integers: ");
34.   d = Console.in.readInt();
35.   e = Console.in.readInt();
36.   f = Console.in.readInt();
37. 
38.   if (d > a) 
39.  d = a + d;
40.   else
41.   {
42.  d = a;
43.  e = d + f;
44.   }
45. 
46.   System.out.println (a + " " + b);
47.   System.out.println (c + " " + d);
48.   System.out.println (e + " " + f);

49.  Give the output of this very bad-indented code segment if the input is:
i. 3, 5, 5
ii. 3, 3, 5
iii. 3, 5, 3

50. 
51.   int a, b, c;
52.   System.out.println ("Type in 3 integers: ");
53.   a = Console.in.readInt();
54.   b = Console.in.readInt();
55.   c = Console.in.readInt();
56. 
57.   if (a == b)
58.   if (b == c)
59.  System.out.println("XXX");
60.   else
61.  System.out.println("XXc");
62.   else if (b == c)
63.  System.out.println("aXX");
64.   else if (a == c)
65.  System.out.println("XbX");
66.   else
67.  System.out.println("abc");

68.  Below is a bad-indented code:

69. 
70.if (y == 8)
71.if (x == 5)
72.System.out.println("I");
73.else
74.System.out.println("want");
75.System.out.println("to");
76.System.out.println("believe");

a. Indent it properly so that it reflects its logic.
b. Draw a flowchart for that code.
c. Rewrite the code segment by adding "{" and "}" at appropriate places so that if x = 5 and y = 7, the output should be:

 
  want
  to
  believe

d. Rewrite the code segment by adding "{" and "}" at appropriate places so that if x = 5 and y = 8, the output should be:

 
  I
  believe 

77.  Study the following code. What will be the output if m is 65?

78. 
79.  if( m >= 65 )
80.    System.out.println ("Well...");
81.  else
82.    System.out.println ("Bad luck!");
83.    System.out.println ("You again?");
84. 

85.  Study the following code. What will be the output if A is 67 and B is 12?

86. 
87.   boolean yeah = ( A >= 50  &&  B <= 50 );
88.   if (yeah)
89.     System.out.println ("I'm released");
90.   else
91.     System.out.println ("Phew!");
92.   System.out.println("I'm lucky");

93.  Is the following expression true or false?

94. 
95.  ( 6 > 6 || 5 < 5 )

96.  What are the output of the following code? Or we can't tell?

97. 
98.  if( variable1 >= 65 || variable1 < 100 )
99.    System.out.println ("Iman Mutiara");
100.           else
101.             System.out.println ("Teman Sejati");
  1. Study this pseudocode:
103.           IF today is Friday
104.             IF it is raining
105.               read Java book 
106.             ELSE
107.               help spouse cooking
108.           ELSE
109.             IF it is not raining
110.               work outside
111.             ELSE
112.               play chess

a.       Draw a flowchart that reflects the same logic as the pseudocode.

b.      If today is Wednesday and it is raining, what is suggested by the following pseudocode?

c.       If today is Friday and it is not raining, what is suggested by the pseudocode?

113.                      Write a code segment using if-else, which prints a message, given a letter grade already read in, according to the following table:

114.    
115.       Letter grade      Message
116.            A            Excellent
117.            B            Good
118.            C            Average
119.            D            Bad
120.            F            Yuck!

You may assume the letter grade entered is upper case only.


FUNCTIONS

121.                      Write a function that accept 3 integers and return the biggest of them. Sample code that call the function is
System.out.println("The biggest value from 3, 7 and 2 is " + max(3, 7, 2));

122.                      Write a function that accept a character and print the character in uppercase. Use toUpperCase() in the function. It returns nothing.

123.                      Create a function named Modulus that accept 2 doubles, n1 and n2. It should calculate and return the remainder of the operation n1/n2. Sample code that call the function is
int mymodulus = Modulus(15, 4);


LOOPS

124.                      Based on the following code:
a. What are the output?
b. Re-write the loop using for loop.

125.    
126.   int number = 1, sum = 0;
127.   while ( number < 7 )   
128.   {
129.     sum = sum + number;
130.     number = number + 3;
131.     System.out.println ("number=" + number + " sum=" + sum);
132.   }

133.                      Write a while loop that accept input of integers and calculate the sum of the integers. The loop should stop when -1 is input.

134.                      What are the output of the following loop?

135.    
136.             int i = 5;
137.             while( i < 1 )
138.             {
139.               System.out.println (i);
140.               i++;
141.             }

142.                      What are the output of the following loop?

143.    
144.             int num = 2;
145.             while( num < 7 )
146.             {
147.               num++;
148.               System.out.println (num);
149.             }

150.                      What are the output of the following loop?

151.    
152.             int value = 12;
153.             while( value != 23 )
154.             {
155.               System.out.println (value);
156.               value = value + 2;
157.             }

158.                      What are the output of the following loop?

159.    
160.             int num = 2;
161.             while( num <= 20 )
162.             {
163.               if( num <= 10 )
164.                   num++;
165.               else
166.                   num = num * 2;
167.               System.out.println (num + " ");
168.             }

169.                      What are the output of the following loop?

170.    
171.             int i = 1;
172.             while( i < 5 )
173.             {
174.               if( i > 2 && i < 4 )
175.                   System.out.println (i + " ");
176.               else
177.                   System.out.println ((i * 3) + " ");
178.               i++;
179.             }

180.                      Study the following code:

181.    
182.             int num;
183.             Console.in.readInt(num);
184.             while( !(num == 7) )
185.             {
186.               System.out.println(num);
187.               Console.in.readInt(num); // **
188.             }

The above loop read numbers from the keyboard.
a. What number(s) should be type in to stop the loop?
b. What will most probably happen if the whole line marked with // ** is deleted?

189.                      What are the output of the following loop?

190.    
191.   for (j = 1; j <= 4; j++)
192.      System.out.println(" " + j++);

193.                      What are the output of the following loop?

194.    
195.   for (j = 1; j <= 4; j++)
196.      System.out.println(" " + --j);

197.                      What are the output of the following loop?

198.    
199.   int k = 0;
200.   int m = 0;
201.   for (p = 0; p < 21; p = p + k )
202.   {
203.         k = k + 1;
204.         m = m + p;
205.         System.out.println (p + " " + k + " " + m);
206.   }

207.                      How a while loop differs compared to a do...while loop?

208.                      Study the code segment below:

209.    
210.           int x;
211.           int bd = 0;
212.    
213.           System.out.println ("Enter an integer : ");
214.           Console.in.readInt(x);
215.           while (x > 0)
216.           {
217.                  System.out.println ("x = " + x);      /* print x */
218.                  bd++;
219.                  x = x / 10;
220.           }
221.           System.out.println ("Eventually, x = " + x );/* print x  */
222.           System.out.println ("Eventually, bd = " + bd); /* print bd */

a) What are the output if the input is 108?
b) In general, what is the purpose of that program?

223.                      What are the output of the following loop?

224.    
225.   int x = 0, a = 9, b = 11;
226.   while (x <  2)
227.   {
228.      if (a <  10)
229.         if ( b >  10)
230.            System.out.println("Hi Hi Hi");
231.         else
232.            System.out.println("Come here");
233.      System.out.println("Wait...");
234.      a = 11; b = 9; x++;
235.   }

236.                      Write a program that read in a sentence. Determine and print out the number of vowels (a, e, i, o, u) in that sentence. Sample output:

237.    
238.   Enter a sentence:
239.   saya suka belajar bahasa
240.    
241.   The number of 'a' in that sentence: 8
242.   The number of 'e' in that sentence: 1
243.   The number of 'i' in that sentence: 0
244.   The number of 'o' in that sentence: 0
245.   The number of 'u' in that sentence: 0

You may NOT assume the letters entered are lowercase only.


Updated: 3:35 pm Thursday 23-Jul-98

UNIVERSITI UTARA MALAYSIA
SEKOLAH TEKNOLOGI MAKLUMAT

COURSE CODE    :       TA5004
COURSE         :       COMPUTER PROGRAMMING
PRE-REQUISITES :       NONE

1.0 COURSE OBJECTIVES
At the end of this course, the students should be able to:

2.0 COURSE SYNOPSIS
The use of selections, loops, sub-programs, arrays and strings. Emphasizing on the problem solving method by applying object oriented programming (OOP). Using linear and linked lists. Analysis and comparisons of several searching and sorting methods. Languages history, paradigm and basic constructs in various programming languages.

3.0 COURSE OUTLINE

WEEK

TOPIC

HOURS

1

Introduction To Computing
Computer components and their relationships.
CPU, main memory and the fetch-execute cycle.
Steps in program development.
Compilation, interpretation, programming language, machine language and program execution.
Compiling and running a simple program.

4

2

Introduction To Programming
Identifier, variables, basic data types.
Arithmetic and compound assignment operators.
Built-in methods to manipulate strings.
Problem solving with basic arithmetic calculations.

4

3

Decisions
Conditions: relational, equality and logical operators.
Selection control structure.
Problem solving using simple and nested if, if/else and switch statements.
Boolean variables.

4

4

Iterations
Conditions in loops.
Counter controlled iterations : for
Sentinel controlled and conditional iterations: while and do...while.
Nested loops.

4

5

OOP: Objects (Using Classes)
Object, classes, encapsulation, inheritance and polymorphism: the theory.
Creating objects, calling methods: built-in classes.
Problem solving by object-oriented design: built-in classes.

4

6

OOP: User-defined Classes
Creating user-defined classes.
Creating user-defined methods: return values, parameters, variable scope.
Creating objects, calling methods: user-defined classes.

4

7

OOP : Inheritance and Polymorphism
Inheriting classes.
Access controls.
Overloading and overriding methods.
Problem solving by object-oriented design: user-defined classes.

4

8

Arrays
Motive of using arrays, declaring arrays.
Loops to traverse arrays.
Simple algorithms to manipulate arrays: searching, counting and element reversing.
Sending, receiving arrays to/from functions.
Creating and manipulating array of objects.

4

9

Data Structures: Lists
Array-based linked lists.
References.
Linked lists without arrays.

4

10

Data Structures: Stack and Queue
Stack:Contiguous and linked stack, sample use.
Queue:Contiguous and linked queue, sample use.

4

11

Algorithm Analysis: Sorting and Searching
Simple analysis method.
Sorting: a simple algorithm and an advanced algorithm.
Searching: a simple algorithm and an advanced algorithm.

12

Programming Languages I
Brief language history.
Language paradigms: imperative and declarative.
Language evaluation criteria: readability, writability, reliability.

4

13

Programming Languages II
Bindings, type checking and data types.
Names, variables, control structures of various languages.

4

14

Applets, HTML and other issues
Introduction to GUI programming.
Introduction to HTML.
Current issues in programming.

4

4.0 TEXTBOOK
Ken Arnold, James Gosling, The Java Programming Language: 2nd Edition,
Addison-Wesley 1998. ISBN: 0-201-31006-6

Other References

  1. Cay Horstmann, Computing Concepts with Java Essentials, John-Wiley, 1998.
  2. James Gosling, Henry McGilton, The Java Language Environment: A White Paper, Sun MicroSystems 1996.
  3. C. Thomas Wu, An Introduction To Object-Oriented Programming With Java, McGraw-Hill 1999.

5.0 METHOD OF INSTRUCTION
14 X 4 = 56 hours (lectures and lab sessions).

6.0 ASSESSMENTS
Assignments - 25%
Quiz - 15%
Mid-semester exam - 20%
Final Exam - 40%
TOTAL - 100%
21-Apr-99

Sub-Programs


1. This first program shows how to call a function. When we use/call a function, we rarely care about how it do its job.

 
/* function as black box  - 1:59 PM 01-Aug-98 */
 
class Func1
{
  public static void main (String args[])
  {
    double a = Math.sqrt(4);
    System.out.println(a);
  }
}

2. This 2nd program shows how to create our own functions. It also shows how we can call a function in 2 different ways. We can assign the value returned or we can use it in an expression.

 
/* writing functions - 2:06 PM 01-Aug-98 */
 
class Func2
{
  public static void main (String args[])
  {
    int a = bigger(3, 6); // call, assign,
    System.out.println(a); // then print.
 
    System.out.println( bigger(3, 6) ); // directly print
 
  } /* end of main */
 
  public static int bigger (int x, int y)
  {
    int big;
    if (x > y)
      big = x;
    else
      big = y;
 
    return (big);
  } /* end of bigger function */
 
} /* end of class */

2b. This one shows how we can condense our function. The previous one declare a variable "big" and assign it with the value that will be returned. This one returns the value straight away without using extra variable.

 
/* writing functions - 2:06 PM 01-Aug-98 */
 
class Func2b
{
  public static void main (String args[])
  {
    int a = bigger(3, 6);
    System.out.println(a);
 
    System.out.println( bigger(3, 6) );
 
  } /* end of main */
 
  public static int bigger (int x, int y)
  {
    if (x > y)
      return (x);
    else
      return (y);
  } /* end of bigger function */
 
}

3. This program shows how to create a predicate function, that is a function that return "true" or "false".

 
/* writing functions : predicate - 2:17 PM 01-Aug-98 */
 
class Func3
{
  public static void main (String args[])
  {
    int a = 3;
    System.out.println(a + " is odd? :" + isOdd(a));
 
    a = 6;
    System.out.println(a + " is odd? :" + isOdd(a));
  } /* end of main */
 
  public static boolean isOdd (int x)
  {
    if (x % 2 == 0)
      return (false);
    else
      return (true);
  } /* end of isOdd function */
 
} /* end of class */

3b. The following program is the simplified version of the above. The function contains just one statement that is the return statement. It also shows that a predicate function can be used in a condition.

 
/* writing functions : predicate - 2:17 PM 01-Aug-98 */
 
class Func3b
{
  public static void main (String args[])
  {
 
    int a = 3;
    if (isOdd(a))
      System.out.println(a + " is odd");
    else
      System.out.println(a + " is even");
 
  } /* end of main */
 
  public static boolean isOdd (int x)
  {
    return (x % 2 != 0);
  } /* end of isOdd function */
 
} /* end of class */

4. The following program demonstrates the variable scope. The variable in a function is not the same one as in other functions.

 
/* function : parameter  - 3:02 PM 01-Aug-98 */
 
class Func4
{
  public static void main (String args[])
  {
    int a = 10;
    System.out.println("Before calling function, a is " + a);
    int b = Times2(a);
    System.out.println("After calling function, a is " + a);
    System.out.println("After calling function, b is " + b);
  } /* --------------------- end of main ------ */
 
  public static int Times2 (int a)
  {
    a = 2 * a;
    System.out.println("       Inside function, a is " + a);
    return (a);
  } /* --------------------- end of Times2 ------ */
 
} /* end of class */

5. A procedure is a special kind of function: it does not return anything. We call a procedure to do something, not to do and give back the result to us like functions do.

 
/* writing procedures : 2:43 PM 01-Aug-98 */
 
class Proc1
{
  public static void main (String args[])
  {
 
    System.out.println("THIS IS MY INFO");
    printName("Mohamad Zamberi Saad");
    printAddres("School of IT, UUM Sintok.");
    printOfficeContact("04-700 3770", "04-700 5753");
 
  } /* end of main */
 
  public static void printName (String name)
  {
    System.out.println("Name : [" + name + "]");
  } /* end of printName procedure */
 
  public static void printAddres (String addres)
  {
    System.out.println(addres);
  } /* end of printAddres procedure */
 
  public static void printOfficeContact (String tel, String fax)
  {
    System.out.println("Tel : " + tel);
    System.out.println("Fax : " + fax);
  } /* end of printOfficeContact procedure */
 
} /* end of class */

 

 

Updated: 12-Dec-98 12:55

[* SEMESTER 1 - 1999/2000 *]

TA5004

Computer Programming (home)

 

Lectures

Assessments

Announcement

Misc.

Notes (together with Java source codes) used in lectures are available.

  • Your updated assignment questions.
  • Your current coursework marks.
  • Course Evaluation
  • Current Coursework Marks
  • Prepare for your quiz. Have a look at past quizzes. Get some help.
  • Assignments (with answers to past ones)

Check the latest info on this course!

You are required to check your electronic mail frequently for information about this course, as well as this home page.

  • What you need for this course.
  • Early hand-outs. (syllabus, schedule, etc)
  • Course Schedule and Outline.
  • Extra Exercises (without answers)
  • Frequently Ask Questions.


[About the course:]
This course is specially offered to the MSc(IT) students that have non-IT background. We use Java as the language. Currently, no IDE is available to us. We are still using JDK from Sun (command line compiler and interpreter).

I will update this site to reflect the syllabus for Semester 1, 1999/2000. Most of the contents will change. However, if you are interested, you can try the pages from previous semesters:


This semester, I also teach: TJ3044 - Pembangunan Aplikasi Rangkaian

·  <<Back to instructors' page (in Bahasa Melayu).

-- 18-May-99 16:39 --

[* SEMESTER 1 - 1999/2000 *]

TA5004

Lectures

 

Lectures

Assessments

Announcement

Misc.


This notes are from last semester. They will change. Don't print them until you have attend the specific lecture.

Jump to lecture number >>:
Basics: 1 | 2 | 3 | 4 | OOP: 5 | 6 | 7 | Data Str. and Algo. Analysis: 8 | 9 | 10 | 11 | Prog Lang: 12 | 13 | Misc.: 14

Lecture#

Topic

1

Introduction To Computing
The Software Preparation.
The Hello.java source code. Try it.
I've put a program template for you. You can use it each time you need to start typing a new program.

2

Introduction To Programming
Introduction To Programming

3

Decisions
Decisions

4

Iterations
Loops and Use of Loops. Also, please look at the sample test question on Loops. After you understand the early parts of the loop topic, you can proceed with the exercise on nested loops.

5

OOP I: Objects (Using Classes)
Sample programs:
  [OOP101.java] or [OOP102.java] or [OOP103.java] or [OOP104.java]

Documentations:

  1. For printing purposes, try the summary of String class documentation and StringBuffer class documentation (local copies -- all links are defunct).
  2. JDK1.1 API or direct to Package java.lang (JDK1.1)
  3. JDK1.2 API or direct to Package java.lang (JDK1.2)

6

OOP II: User-defined Classes
OOP II: User-defined Classes. Then, proceed to Test Score example. Also, please look at the sample test question on Class and Methods.

7

OOP III: Inheritance and Polymorphism
OOP and Classes. You can print them. Hand-outs will not be available in class.

  1. Pengenalan Kelas
  2. Pengenalan Polymorphism - Overloading
  3. Pengenalan Polymorphism - Overloading (2)
  4. Inheritance & Polymorphism - Overriding

8

Arrays
Arrays
Command Line Arguments

9

Data Structures: Lists

10

Data Structures: Stack and Queue
The Simple Array-based Stack source code.

11

Algorithm Analysis: Sorting and Searching
Sorting and Searching

12

Programming Languages I
Notes in RTF file (MSWord can open it) -- or for faster download, try the zipped file.

13

Programming Languages II
-- combined with previous lecture. --

14

Applets, HTML and other issues
Introduction to Applets


Back to course page.

-- 01-Sep-99 13:01 --

TA5004: Computer Programming - Test (25%)

Name:_______________________________
Metric number:___________

Directions:

  1. Answer all questions.
  2. Write clearly.
  3. Time: 100 minutes.
  4. Total marks: 100.

INTRODUCTION TO COMPUTING

1.      What is the difference of logic error and syntax error?
(3%)

Answer:

Logic error : when the program can run, but give incorrect result. 
Syntax error : the program cannot run at all because the 
programmer violate the grammar of the language.
Logic error : cannot be detected by the compiler.
Syntax error : can be detected by the compiler.

2.      What is the difference of compiled and interpreted program?
(3%)

Answer:

Compiled program is faster than interpreted one.
Compiled program code is 'safer' than interpreted one (because)
the programmer does not have to distribute his/her source code.

3.      A computer program is normally completed after the programmer had done editing, compiling, and executing (running) the program. Explain (in brief) how you take those 3 steps to complete a Java program.
(6%)

Answer:

Editing: we create/edit the source code using any text editor, 
     example: Notepad or DOS Editor.
Compiling: we use the JDK compiler: javac 
Executing: we use the JDK interpretr: java 

PROBLEM SOLVING

4.      "Given two dimensions of a rectangle, calculate and display its area."
Based on that problem, answer the following questions:
a. What is the suitable input to the problem?
b. What is the suitable output of the problem?
c. Write a pseudocode to solve the problem.
(5%)

Answer:

a. Input: rectangle length and width
b. Output: rectangle area
c. Read in the rectangle length and width.
   Calculate the rectangle area:
         area = width x length
   Print out the rectangle area

5.      A courier company, GoFast want to use a computer program to determine payable sum of their mileage claims. Their programmer ask for your help to draw the flowchart. The payable sum is calculated using this table.

6.    KM               Cents per KM
7.    First 500        50
8.    Next 200         40
9.    Each extra km            30

Example:

Draw a flowchart to help your friend solve this problem. Do not combine conditons using && or ||.
(12%)

Answer:

      |
      V
   ---------
 / read m  /
 ---------
      |
      |
      V
     / \
    /   \
   / m <=\  False
   \ 500?/-------------+
    \   /              |         
     \ /               V         
      |True           / \        
      |              /   \       
      V             / m <=\  False
  +--------+        \ 700?/--------------+
  | pay =  |         \   /               |
  | m x .5 |          \ /                |
  +--------+           |True             |
      |                |                 |
      |                V                 V
      |           +------------+    +------------+ 
      |           |pay =       |    |pay =       | 
      |           |(500 x .5)+ |    |(500 x .5)+ | 
      |           |(m-500 x .4)|    |(200 x .4)+ | 
      |           +------------+    |(m-700 x .3)|
      |                |            +------------+ 
      |                |                 |      
      |<-------------- V---------------- V
      V
   -----------
 / print pay /
 ------------
      |
      V

INTRODUCTION TO JAVA & FIRST PROGRAMS

10.  Write Java statements to accomplish these tasks:

a.       declare a variable x from type integer and store the value 10 in it.

b.      double the content of x.

c.       print out the value of x.

(9%)
Answer:

d.                 int x = 10;
 
e.                 x = x * 2; or x *= 2;
 
f.                 System.out.println(x);
 

11.  Give the output of this code segment:
(9%)

12.  int a, b;
13.  a = 2;
14.  a = a * (( (3 + 7) / 2 ) - 8);
15.  System.out.println(a);
16. 
17.  a = 3;
18.  b = 21; b /= a; b--;
19.  System.out.println(b);
20. 
21.  a = 6; b = 9;
22.  a += b;
23.  System.out.println(a);

Answer:

-6
6
15

STRINGS

24.  Give the output of this code segment:
(5%)

25.    String a = "Using";
26.    String b = "Java";
27.    String c = a.substring(1, 5).toUpperCase() 
28.               + a.substring(2, 5) + " " 
29.               + b.substring(0, 2) + "zz";
30.    System.out.println(c);

Answer:

SINGing Jazz

OBJECTS

31.  Why we should not use == to compare the equality of 2 objects content?
(5%)
Answer:

32.Because the name of objects are actually their references.
33.If we use == to compare 2 object names, that means we are comparing
34.whether they point to the same object, not whether both objects
35.are equal.

DECISIONS

36.  If a is true, b is false and c is true, what is the value of the followings?
(6%)

37.              
 .                 (!a && b) || !c
38.              
 .                 (a || c) && !b
39.              
 .                 (!a != !c)
40.              
41. 

Answer:

 .                 false
 
a.                 true
 
b.                 false
 

42.  Study the following code. What will be the output if m is 17?
(2%)

43. 
44.  if( m >= 17 )
45.    System.out.println ("Batman");
46.  else
47.    System.out.println ("Joker");
48.    System.out.println ("Robin");


Answer:

Batman
Robin
-- because the third println is not part of else, it must be executed anyway.

49.  What is the output of the following code? Or we cannot tell due to lack of information?
(2%)

50. 
51.  if( variable1 >= 85 || variable1 < 100 )
52.    System.out.println ("Yes");
53.  else
54.    System.out.println ("No");


Answer:

yes
-- because whatever is the value of variable,
it must be either >= 85 or < 100 or both.

FUNCTIONS (+ decisions)

55.  a) What are the output of the following program?
b) Generalize the purpose of the abc function. Suggest a better name to replace abc.
(7%)

56.class Myprog
57.{
58.  public static void main (String args[])
59.  {
60.    System.out.println(abc(5,3));
61.    System.out.println(abc(16,4));
62.  }  /* end of main ----------  */
63. 
64.  public static boolean abc (int x, int y)
65.  {
66.    return (x % y == 0);
67.  }  /* end of abc -----------  */
68.} /* end of class */

Answer:

a) false
   true
b) -- purpose of the function: determining whether its 1st argument
      is divisible by its 2nd argument or not.
   -- a better name: isDivisible 

69.  Write a function, min, that receives 3 integers and returns the smallest among them.
(9%)
Answer:

70.public static int min (int x, int y, int z)
71.  {
72.    int smallest = x;
73.    if (y < smallest)
74.      smallest = y;
75.    if (z < smallest)
76.      smallest = z;
77.    return (smallest);
  }

LOOPS

78.  a) What are the output of the following code segment?
b) Re-write the code using while loop.
(7%)

79.    int sum = 0;
80.    for (int i = 1; i <= 3; i++)
81.    {
82.      sum = sum + (i*i);
83.      System.out.println(sum);
84.    }
85.    System.out.println(sum);

Answer:

a)1
  5
  14
  14
 
b)  int sum = 0;
    int i = 1;
    while (i <= 3)
    {
      sum  = sum + (i*i);
      System.out.println(sum);
      i++;
    }
    System.out.println(sum);

86.  a) If the input are 2 and 3, what are the output of the following program?
b) Summarize the purpose of the program. Suggest a better name to replace xyz.
(10%)

87.  public static void main (String args[])
88.  {
89.    System.out.print("Enter 2 integers:");
90.    int a = Console.in.readInt();
91.    int b = Console.in.readInt();
92. 
93.    int xyz = 0;
94.    boolean c1 = false;
95.    boolean c2 = false;
96.    do
97.    {
98.      xyz++;
99.      c1 = (xyz % a == 0);
100.         c2 = (xyz % b == 0);
101.         if (c1)
102.           System.out.println(xyz);
103.         if (c2)
104.           System.out.println(xyz);
105.       } while (!(c1 && c2));
106.    
107.       System.out.println("The number is: " + xyz);
108.    
109.     }  /* end of main -----------------------------------  */

Answer:

a)       Enter 2 integers:2 3
  2
  3
  4
  6
  6
  The number is: 6
b) -- purpose of the program: finding the Least Common Multiply (LCM) 
      of its 2 input.
   -- a better name for variable: LCM or LeastCommonMultiply

-- END OF TEST --


Updated: Wednesday, August 12, 1998 - 5:23 PM. Made solely using only text editor.

TA5004: Computer Programming - Test (25%)

Name:_______________________________
Metric number:___________ Date of exam: Saturday 15th August 1998.

Directions:

  1. Answer all questions.
  2. Write clearly.
  3. Time: 100 minutes.
  4. Total marks: 100.
  5. Assume you can use the ccj package from the textbook.

INTRODUCTION TO COMPUTING

1.      What is the difference of logic error and syntax error?
(3%)

Answer:

 
 
 
 
 
 
 

2.      What is the difference of compiled and interpreted program?
(3%)

Answer:

 
 
 
 
 

3.      A computer program is normally completed after the programmer had done editing, compiling, and executing (running) the program. Explain (in brief) how you take those 3 steps to complete a Java program.
(6%)

Answer:

 
 
 
 
 
 
 
 
 
 
 

PROBLEM SOLVING

4.      A courier company, GoFast want to use a computer program to determine payable sum of their mileage claims. Their programmer ask for your help to draw the flowchart. The payable sum is calculated using this table.

5.    KM               Cents per KM
6.    First 500        50
7.    Next 200         40
8.    Each extra km            30

Example:

Draw a flowchart to help your friend solve this problem. Do not combine conditons using && or ||.
(12%)

Answer:

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

9.      "Given two dimensions of a rectangle, calculate and display its area."
Based on that problem, answer the following questions:
a. What is the suitable input to the problem?
b. What is the suitable output of the problem?
c. Write a pseudocode to solve the problem.
(5%)

Answer:

a.
 
b.
 
c.
 
 
 
 
 
 
 
 

INTRODUCTION TO JAVA & FIRST PROGRAMS

10.  Write Java statements to accomplish these tasks:

a.       declare a variable x from type integer and store the value 10 in it.

b.      double the content of x (make it 20).

c.       print out the value of x.

(9%)
Answer:

d.                  
e.                  
 
f.                  
g.                  
 
h.                  
 
 

11.  Give the output of this code segment:
(9%)

12.  int a, b;
13.  a = 2;
14.  a = a * (( (3 + 7) / 2 ) - 8);
15.  System.out.println(a);
16. 
17.  a = 3;
18.  b = 21; b /= a; b--;
19.  System.out.println(b);
20. 
21.  a = 6; b = 9;
22.  a += b;
23.  System.out.println(a);
24. 

Answer:

 
 
 
 
 

STRINGS

25.  Give the output of this code segment:
(5%)

26.    String a = "Using";
27.    String b = "Java";
28.    String c = a.substring(1, 5).toUpperCase() 
29.               + a.substring(2, 5) + " " 
30.               + b.substring(0, 2) + "zz";
31.    System.out.println(c);

Answer:

 
 
 

OBJECTS

32.  Why we should not use == to compare the equality of 2 objects content?
(5%)
Answer:

33. 
34. 
35. 
36. 
37. 
38. 
39. 
40. 

DECISIONS

41.  If a is true, b is false and c is true, what is the value of the followings?
(6%)

42.              
 .                 (!a && b) || !c
43.              
 .                 (a || c) && !b
44.              
 .                 (!a != !c)
45.              
46. 

Answer:

 .                  
a.                  
 
b.                  
c.                  
 
d.                  
e.                  
 

47.  Study the following code. What will be the output if m is 17?
(2%)

48. 
49.  if( m >= 17 )
50.    System.out.println ("Batman");
51.  else
52.    System.out.println ("Joker");
53.    System.out.println ("Robin");


Answer:

 
 
 
 

54.  What is the output of the following code? Or we cannot tell due to lack of information?
(2%)

55. 
56.  if( variable1 >= 85 || variable1 < 100 )
57.    System.out.println ("Yes");
58.  else
59.    System.out.println ("No");


Answer:

 
 

FUNCTIONS (+ decisions)

60.  a) What are the output of the following program?
b) Generalize the purpose of the abc function. Suggest a better name to replace abc.
(7%)

61.class Myprog
62.{
63.  public static void main (String args[])
64.  {
65.    System.out.println(abc(5,3));
66.    System.out.println(abc(16,4));
67.  }  /* end of main ----------  */
68. 
69.  public static boolean abc (int x, int y)
70.  {
71.    return (x % y == 0);
72.  }  /* end of abc -----------  */
73.} /* end of class */

Answer:

a) 
 
 
 
b) --
 
 
 
   --
 
 

74.  Write a function, min, that receives 3 integers and returns the smallest among them.
(9%)
Answer:

75. 
76. 
77. 
78. 
79. 
80. 
81. 
82. 
83. 
84. 

LOOPS

85.  a) What are the output of the following code segment?
b) Re-write the code using while loop.
(7%)

86.    int sum = 0;
87.    for (int i = 1; i <= 3; i++)
88.    {
89.      sum = sum + (i*i);
90.      System.out.println(sum);
91.    }
92.    System.out.println(sum);

Answer:

a)
 
 
 
 
 
 
 
b)
 
 
 
 
 
 
 
 
 
 
 
 
 

93.  a) If the input are 2 and 3, what are the output of the following program?
b) Summarize the purpose of the program. Suggest a better name to replace xyz.
(10%)

94.  public static void main (String args[])
95.  {
96.    System.out.print("Enter 2 integers:");
97.    int a = Console.in.readInt();
98.    int b = Console.in.readInt();
99. 
100.       int xyz = 0;
101.       boolean c1 = false;
102.       boolean c2 = false;
103.       do
104.       {
105.         xyz++;
106.         c1 = (xyz % a == 0);
107.         c2 = (xyz % b == 0);
108.         if (c1)
109.           System.out.println(xyz);
110.         if (c2)
111.           System.out.println(xyz);
112.       } while (!(c1 && c2));
113.    
114.       System.out.println("The number is: " + xyz);
115.    
116.     }  /* end of main -----------------------------------  */

Answer:

a)
 
 
 
 
 
 
 
 
 
b) -- 
 
   -- 

-- END OF TEST --


Updated: Wednesday, August 13, 1998 - 11:52 AM. Made solely using only text editor.