Arithmetic, Simple Loops

ORF 201
COMPUTER METHODS FOR PROBLEM SOLVING
Lecture 2
Arithmetic, Simple Loops
(C) Princeton University
Hello World
The file Hello.java
Every file must have
one public class
Point of entry
is main()
public class Hello
{
public static void main(String[] args)
{
All code must
System.out.println("Hello, World!");
be in a class
}
}
To compile:
To run (execute):
Output:
javac Hello.java
java Hello
Hello, World!
2
Fahrenheit to Celsius
Anything between /*
and */ is ignored by
the compiler.
/* Program to print a Fahrenheit to Celsius
conversion table for fahr = 0, 20, …, 300 */
public class FahrCels
{
public static void main(String [ ] args)
int is the
{
integer data
fahr and cels are instances of int
int fahr, celsius;
type
fahr = 0;
celsius = 5 * (fahr-32) / 9;
System.out.println(fahr + "\t" + celsius);
= is the
assignment
operator.
fahr = 20;
celsius = 5 * (fahr-32)
System.out.println(fahr
.
.
fahr = 300;
celsius = 5 * (fahr-32)
System.out.println(fahr
Arithmetic
operators:
+, -, *, /
/9;
+ "\t" + celsius);
Statements are
executed in
sequence. End
with semicolon.
"\t" is the
tab string
/ 9;
+ "\t" + celsius);
}
}
3
Fahrenheit to Celsius 2
/* Program to print a Fahrenheit to Celsius conversion
table for fahr = 0, 20, …, 300 */
public class FahrCels2
{
public static void main(String [ ] args)
{
int fahr, celsius;
Declare
int lower, upper, step;
Initialize
lower = 0;
upper = 300;
step = 20;
Compute
fahr = lower;
while (fahr <= upper) {
celsius = 5 * (fahr-32) /9;
System.out.print(fahr);
System.out.print("\t");
System.out.println(celsius);
fahr = fahr + step;
}
}
}
while (…) {…}
Logical operators:
<, >, <=, >=,
==, !=
/* lower limit of temp table */
/* upper limit */
/* step size */
print vs.
println
4
Run It
To compile:
javac FahrCels2.java
To run:
java FahrCels2
The output:
0
20
40
60
80
100
120
140
160
180
200
220
240
260
280
300
-17
-6
4
15
26
37
48
60
71
82
93
104
115
126
137
148
5
Fahrenheit to Celsius 3
/* Program to print a Fahrenheit to Celsius conversion table
for fahr = 0, 20, …, 300 (floating point version) */
import java.text.DecimalFormat;
import DecimalFormat
gives us DecimalFormat
objects
public class FahrCels3
{
public static void main(String [ ] args)
{
double fahr, celsius;
double vs. float
int lower, upper, step;
DecimalFormat floating = new DecimalFormat("##,##0.#");
lower = 0;
upper = 300;
step = 20;
}
}
/* lower limit of temp table */
/* upper limit */
5/9=0 whereas
/* step size */
5.0/9.0=0.555...
fahr = lower;
while (fahr <= upper) {
celsius = (5.0/9.0) * (fahr-32);
System.out.println(floating.format(fahr) +
"\t" + floating.format(celsius));
fahr = fahr + step;
}
Floating.format(x)
6
The Output
0.0
20.0
40.0
60.0
80.0
100.0
120.0
140.0
160.0
180.0
200.0
220.0
240.0
260.0
280.0
300.0
-17.8
-6.7
4.4
15.6
26.9
37.8
48.9
60.0
71.1
82.2
93.3
104.4
115.6
126.7
137.8
148.9
7