Object-Oriented Programming with Java, part I + II

cc

This material is licensed under the Creative Commons BY-NC-SA license, which means that you can use it and distribute it freely so long as you do not erase the names of the original authors. If you make changes in the material and want to distribute this altered version of the material, you have to license it with a similar free license. The use of the material for commercial use is prohibited without a separate agreement.

Authors: Arto Hellas, Matti Luukkainen
Translators to English: Emilia Hjelm, Alex H. Virtanen, Matti Luukkainen, Virpi Sumu, Birunthan Mohanathas, Etiënne Goossens
Extra material added by: Etiënne Goossens, Maurice Snoeren, Johan Talboom
Adapted for Informatica by: Ruud Hermans

The course is maintained by Technische Informatica Breda


For loops

By now you will have noticed that there are usually 3 important components in a loop; the initialization, condition and increment

int i = 0;              //initialization
while(i < 10) {         //condition
    System.out.println(i);
    i++;                //increment
}

These 3 parts are key to a successful loop, and for instance, forgetting the increment will result in an infinite loop. They are split up on 3 different lines, which is not good for the structure of your code. To improve the structure, java offers a for-loop. This for-loop combines these 3 parts in a single line

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

This program is identical to the while loop. The for has all 3 different components between brackets, and is therefore different than the while() or if() conditions. This for-syntax is very powerful, but can some time getting used to. For now, you can pick if you do loops with a while() statement or a for() statement

Exercise for-loop-1 Checkerboard

Write a program, using for-loops, that draws a checkerboard Note that you will be using 2 for-loops here, one to iterate over the rows, and one that iterates over the columns. Note that you use # for the black tiles, and the first, topleft tile should be a #

Expected output:

# # # # # 
 # # # # #
# # # # # 
 # # # # #
# # # # # 
 # # # # #
# # # # # 
 # # # # #
# # # # # 
 # # # # #