|
The For StatementJava isn't as redundant as perl, but there's still almost always more than one way to write any given program. The following program produces identical output to the Fahrenheit to Celsius program in the preceding section. The main difference is the for loop instead of a while loop.// Print a Fahrenheit to Celsius table class FahrToCelsius { public static void main (String args[]) { int fahr, celsius; int lower, upper, step; lower = 0; // lower limit of temperature table upper = 300; // upper limit of temperature table step = 20; // step size for (fahr=lower; fahr <= upper; fahr = fahr + step) { celsius = 5 * (fahr-32) / 9; System.out.println(fahr + + celsius); } // for loop ends here } // main ends here } The only difference between this program and the previous one is that here we've used a for loop instead of a while loop. The for loop has identical syntax to C's for loops. i.e. for (initialization; test; increment) The initialization, in this case setting the variable fahr equal to the lower limit, happens the first time the loop is entered and only the first time. Then the first time and every time after that when control reaches the top of the loop a test is made. In our example the test is whether the variable fahr is less than or equal to the upper limit. If it is we execute the code in the loop one more time. If not we begin executing the code that follows the loop. Finally at the end of each loop the increment step is made. In this case we increase fahr by step .If that's unclear let's look at a simpler example: //Count to ten class CountToTen { public static void main (String args[]) { int i; for (i=1; i <=10; i = i + 1) { System.out.println(i); } System.out.println("All done!); } } |
Bhopal news
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100