3

3.1

Java Loops

Loops

3.1.1 for() Many tasks within a program are repetitive, such as prompting for data, counting values, and so on. The for loop allows the execution of a block of code for a given control function. The following is an example format; if there is only one statement in the block then the braces can be omitted. Figure 3.1 shows a flow chart representation of this statement. for (starting condition;test condition;operation) { statement block }

where : starting condition – test condition – operation

the starting value for the loop; if test condition is TRUE the loop will continue execution; – the operation conducted at the end of the loop.

Displaying ASCII characters Program 3.1 displays ASCII characters for entered start and end decimal values. Sample run 3.1 displays the ASCII characters from decimal 40 (‘(’) to 50 (‘2’). The type conversion (char) is used to convert an integer to a char.

& Java program 3.1 public class chap3_01 { public static void main (String args[]) { int start,end,ch; start=40; end=50; for (ch=start;chjava chap3_01 40 ( 41 ) 42 * 43 + 44 , 45 46 . 47 / 48 0 49 1 50 2

Simulation of a mathematical equation The program in this section will simulate the results of the equation: y = 3 x 2 − 12 x − 1 for values of x from 0 to 100 in steps of 10. Program 3.2 gives a Java program which implements this. Test run 3.2 shows a sample run of the program. It can be seen that the value of x varies from 0 to 100, in steps of 10.

32

Mastering Java

& Java program 3.2 public class chap3_02 { public static void main (String args[]) { double x,y; System.out.println("X Y"); for (x=0;xjava chap3_02 X Y 0.0 -1.0 10.0 179.0 20.0 959.0 30.0 2339.0 40.0 4319.0 50.0 6899.0 60.0 10079.0 70.0 13859.0 80.0 18239.0 90.0 23219.0 100.0 28799.0

Boolean logic Program 3.3 is an example of how a Boolean logic function can be analysed and a truth table generated. The for loop generates all the required binary permutations for a truth table. The Boolean function used is: Z = ( A. B) + C

A schematic of this equation is given in Figure 3.2. Test run 3.3 shows a sample run. The above equation is implemented in Java with: z=~((a & b) | c)

// not ( (a and b) or c)

and as z is a 16-bit integer then to just show the first bit of the value then the following bit mask is used: z=~((a & b) | c) & 1;

// mask-off least-significant bit

which will only display the least-significant bit of the operation.

Java loops

33

A B Z C Figure 3.2 Digital circuit

& Java program 3.3 public class chap3_03 { public static void main (String args[]) { int a,b,c,z; System.out.println("A B C Z"); for (a=0;a