Universidad Carlos III de Madrid

Ingeniería de Telecomunicación

Enero-Mayo 2010 / January-May 2010

Review: Fundamentals of Java

Lab Section1.  Session 2 (lab): Review exercises

We advise the students to program according to usual Java conventions. The document Java Coding Guidelines presents a brief introduction to the most important conventions, as well as instructions on how to configure Eclipse according to them.

Exercise Section1.1.  Exercises about arrays

Objective

Review arrays with some basic exercises.

Exercise

  • Return the biggest integer number of an array of integers.

  • Return the average of the elements of an array.

  • Show the elements of an array that are even (divisible by 2).

  • Show the sumatory of the elements of an array.

Exercise Section1.2.  Displaying a Chess Board in text format on console

Objective

Practice for loops.

Exercise

Implement a program that displays a text based Chess Board on the console (standard output) as follows:

        
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB
BWBWBWBW
WBWBWBWB

      

You must implement TWO SOLUTIONS. The first one must use just loops and commands to print on the screen. The second solution must create an array, fill it in with the appropriate values, and finally, display it on the screen.

Exercise Section1.3.  Loop conversion (for -> while)

Objective

Practice loops.

Exercise

Translate the following for loop into a while loop:

for (int i = 0; i < 10; i++) {
  System.out.print(i);
}
System.out.println("");

Exercise Section1.4.  Conversion of loops (while -> for)

Objective

Practice loops.

Exercise

Translate the following while loop into a for loop:

final int MAX_ITEMS = 10;

int [] items = { 2, 4, 6, 8, 10, 9, 7, 5, 3, 1};
boolean found = false;
int find  = 10;

// loop while
int i = 0;
while ( (!found) && (i < MAX_ITEMS) ) {
  found = (items[i] == find);		
  i++;
}	
System.out.println(i-1);

Homework Section2.  Homework

Exercise Section2.1.  Check whether a phrase or a word is a palindrome

Objective

Review loops.

Exercise

A palindrome is a word or a phrase that is read the same forwards or backwards. Implement a program that determines whether a given string is a palindrome or not.

Exercise Section2.2.  Calculation of factorial using loops

Objective

Practice loops.

Exercise

Implement a method that returns the factorial of a given number, first using a for loop and then using a while loop.

Exercise Section2.3.  2-dimension arrays

Objective

Practice with bi-dimensional arrays.

Exercise

Implement a class Matrix that includes a method for adding matrixes, taking into account that the result of the sum can not modify the instance over which the method is invoked.

Explanation

The number of rows and columns of the matrix must be given at the instance object's creation.