Programming and Computer Science in Java:

See Course Home Page.

*This document is also available as lab1.doc,
a Word document.*

**P&CS Programming Labs
Lab #1: Programs 1-10 + Additional Exercises**

Instructions

Program 1: Hello World

Program 2: The Sum of Two Integers

Program 3: Reading Integers

Program 4: Reading Integers More Gracefully

Program 5: If Statements

Program 6: If-Else Statements

Program 7: While Statements

Program 8: While Statements and Running Sums

Program 9: While(true) Statements and Infinite Loops

Program 10: Integer Math

Summary

Additional Exercises

Extra Credit Exercises

For each of the programs below, follow these steps:

- Run the sample program in JCreator (instructions below…)
- Study the learning points for that sample program
- At this point, if you have questions, ask for help.
- Try the exercises to demonstrate your mastery of the learning points.
- Save each of your exercises on your lab floppy disk
- Do this using "File / Save As" in JCreator
- If you are doing program 3, exercise 2, name the file "p3e2.java"

- When you have mastered the exercises, inform the teacher and proceed to the next sample program.

How to create, compile, and run a sample program in JCreator:

- Launch JCreator
- Select "File / Close Workspace" if one is open.
- Select "File / New / Files / Java File" ; Give it any name (say, "p1")
- Type in the Java program below, exactly as it appears!

a. Change <your name> and <the date> appropriately - Select "Build / Compile File" (do not use "Compile Project" nor F7!)
- Look at the "Build" window at the bottom of the screen:

a. If there is an error, it will be reported here.

b. Wait to see the report. Do not go to Step 7 until you see the report.

c. If there is an error, hit F4 to go to the line number where the error occurred, then read the description of the error, try to fix it, and go back to Step 5.

d. If there is no error, wait for this screen to say "Process completed". Then, and only then, proceed to Step 7. - Your program has now successfully compiled! (Congratulations!)
- Select "Build / Execute File" (do not use "Execute
Project" nor F5!)

// Program #1: Hello World // <your name>, <the date>, p&cs

class HelloWorld { public static void main(String[] args) { System.out.println("Hello world!"); System.out.println("This is my first program!"); } }

**Learning Points:**

1. A program is really a class with a main method.

2. The only part you really care about is the code inside the main.

2a. The rest, you do not need to understand, but you do need to type in.

3. Java is very particular about the syntax.

3a. Java is case-sensitive (you must get upper and lower case exactly correct)

3b. Semicolons must follow statements

3c. Your code can only go inside the main. Anywhere else is an error.

4. Good programmers (like you!) are very particular about style.

4a. Use squiggly braces and indent your code exactly as noted above

4b. Use comments to explain what the code does, who wrote it, etc.

4c. Many more style rules to follow…

5. A line beginning with // is a comment, and Java ignores the line.

6. System.out.println("foo") prints the word "foo" followed
by a newline.

**Exercises:**

1.1. Write a Java program which prints out your name.

1.2. Write a Java program which prints out a knock-knock joke.

**P&CS Program #2: The
Sum of Two Numbers**

// Program #2: The Sum of Two Numbers // <your name>, <the date>, p&cs

class SumOfTwoNumbers { public static void main(String[] args) { // declare two integer variables int x, y;

// assign their values x = 10; y = 4;

// print out the variable values System.out.println(x); System.out.println(y);

// now print out their sum System.out.println(x + y); } }

**Learning Points:**

1. Variables have names (like "x" and "y") and hold
values (like 10 and 4).

2. Integer variables have integer values

2a. Some legal integer values: 2, 0, -20, 1234321

2b. Some illegal values: 3.14, "hello"

3. You must declare variables before you use them.

3a. This tells Java that these are variables, and what type (here, integers)

3b. The line "int x, y;" declares the variables x and y to be integers

4. You can assign values to variables

4a. "x = 10;" assigns the value 10 to the variable "x"

5. You can print out variables using System.out.println

6. You can even print out their sum using System.out.println

**Exercises:**

2.1. Write a Java program which prints out the product of two integers.
Note that in Java, multiplication is performed with an asterisk (*).

2.2. Write a Java program which prints out the sum of three integers.

**P&CS Program #3: Reading
Integers**

// Program #3: Reading Integers // <your name>, <the date>, p&cs

class ReadingIntegers { public static void main(String[] args) { // declare two integer variables int x, y;

// read their values from the user x = readInt(); y = readInt();

// print out their sum System.out.println(x); System.out.println(y); System.out.println(x + y); } }

**Learning Points:**

1. This is the same program as #2, except here the user enters the values

2. Thus, this program works for any values, and not just 10 and 4.

3. Unfortunately, as you learn when you enter this, it does not compile.

4. The problem is that Java does not know how to readInt().

5. To fix this, you must add the readInt() method, as on the following page.

6. You can download the readInt() code from the course home page.

7. You must include it if you use readInt() in your code.

**Exercises:**

3.1. Enter the whole Java program on the next page, including the readInt()
method.

3.2. Write a Java program which reads in three integers and prints out their
sum.

**P&CS Program #3: Reading
Integers (Full Listing)**

// Program #3: Reading Integers // <your name>, <the date>, p&cs

class ReadingIntegers { public static void main(String[] args) { // declare two integer variables int x, y;

// read their values from the user x = readInt(); y = readInt();

// print out their sum System.out.println(x); System.out.println(y); System.out.println(x + y); }

// Include this method if you use readInt() in your code. // You may copy this code from the course web site. public static int readInt() { int result, sign, c; result = 0; sign = 1; try { // skip non-integer characters while (true) { c = System.in.read(); if ((c >= '0') && (c <= '9')) break; if (c == '-') sign = -sign; } // now read digits while (true) { result = 10 * result + (c - '0'); c = System.in.read(); if ((c < '0') || (c > '9')) break; } } catch (java.io.IOException e) { System.out.println("Error while reading integer."); } return result * sign; } }

**P&CS Program
#4: Reading Integers More Gracefully**

// Program #4: Reading Integers More Gracefully // <your name>, <the date>, p&cs

class ReadingIntegersMoreGracefully { public static void main(String[] args) { // declare two integer variables int x, y;

// read their values from the user System.out.print("Enter an integer: "); x = readInt(); System.out.print("Enter another integer: "); y = readInt();

// print out their sum System.out.print(x); System.out.print(" + "); System.out.print(y); System.out.print(" = "); System.out.println(x + y); }

// NOTE: insert readInt() code here... }

**Learning Points:**

1. To run this program, you must include the readInt() code from program #3.

2. Here, we prompt the user ("Enter an integer: "), so the user knows
what the program is asking.

3. Use System.out.print instead of System.out.println to stay on the same line.

4. We also print out the answer in a prettier format.

5. print(x) prints the value of the variable x

6. print("foo") prints whatever is inside the quotes.

7. All your Java programs for now on should use prompts and pretty output.

**Exercises:
**4.1. Write a Java program which reads in 3 integers and prints their sum and
average.

4.2. Write a Java program which reads in a distance in yards and outputs the same distance in feet. Note that 1 yard = 3 feet.

4.3. Write a Java program which reads in a distance in feet and outputs the same distance in yards. Note what happens when the input is not a multiple of 3. This is known as truncation.

4.4. Write a program which reads in the number of free throws a player has attempted, and then the number she made, and prints out her free throw percentage. This is slightly trickier than the previous problems, due to truncation.

**P&CS Program #5: If
Statements**

// Program #5: If Statements // <your name>, <the date>, p&cs

class IfStatements { public static void main(String[] args) { // declare an integer variable int x;

// read its value from the user System.out.print("Enter an integer: "); x = readInt();

// use if statements to compare x to other values if (x < 20) { System.out.println(x + " is less than 20"); } if (x == 7) { System.out.println(x + " is equal to 7"); } if (x != 19) { System.out.println(x + " is not equal to 19"); } if (x > 3) { System.out.println(x + " is greater than 3"); } } // NOTE: insert readInt() code here... }

**Learning Points:
**

1. To run this program, you must include the readInt() code from program #3.

2. An "if" statement is of the form:

if (test)

{

BODY

}

3. An "if" statement executes its body only if its test is true

4. Important note: There is no semicolon after the test!!!

5. A test for equality uses double-equals, as in (x == y)

6. A test for inequality uses exclamation-equals, as in (x != y)

5.2. Write a Java program which reads in 2 integers and prints whether they sum to 0.

**P&CS Program #6: If-Else
Statements**

// Program #6: If-Else Statements // <your name>, <the date>, p&cs

class IfElseStatements { public static void main(String[] args) { // declare an integer variable int x;

// read its value from the user System.out.print("Enter an integer: "); x = readInt();

// use if-else statements to find the sign of x if (x < 0) { System.out.println(x + " is negative"); } else if (x == 0) { System.out.println(x + " is equal to 0"); } else { System.out.println(x + " is positive"); } } // NOTE: insert readInt() code here... }

**Learning Points:**

1. To run this program, you must include the readInt() code from program #3.

2. Following an "if", you may have an "else if" which
provides another test

3. The last "else" can omit the test, in which case its body is
executed only if all the preceding tests fail.

4. In any case, at most one body will be executed within in if-else
statement. Think about this!

**Exercises:**

6.1. Write a Java program which reads in an integer, and if it is positive, prints out the square of the integer, but if it is negative, prints out the cube of the integer, and if it is zero, prints out the message "carpe diem".

**P&CS Program #7: While
Statements**

// Program #7: While Statements // <your name>, <the date>, p&cs

class WhileStatements { public static void main(String[] args) { // This program uses a while statement to print out // the numbers from 1 to 10, inclusive.

// declare the counter variable, which runs from 1 to 10 int counter;

// initialize the counter to 1 counter = 1;

// now, so long as the counter is <= 10, loop, printing // out the current value of the counter, then increasing // the value of counter by 1. while (counter <= 10) { // print out the current counter value System.out.println(counter); // and increment the counter by one counter = counter + 1; }

// Let's confirm that counter is not <= 10. In particular, // we expect its value here to be 11. Let's prove it: System.out.println("Counter final value: " + counter); } }

**Learning Points:
**1. A "while" statement is of the form:

while (test)

{

BODY

}

2. A "while" statement repeatedly executes its body so long as its test is true

3. Important note: There is no semicolon after the test!!!

7.2. Write a Java program which reads in two integers, and prints out the integers which are between them. Your program must work whether the first or second number is the smaller one. Hint: introduce two more variables, lo and hi, and use an "if" statement to set the values of lo and hi based on the numbers entered.

**P&CS Program
#8: While Statements and Running Sums**

// Program #8: While Statements and Running Sums // <your name>, <the date>, p&cs

class RunningSums { public static void main(String[] args) { // This program uses a while statement to compute the sum // from 0 to 100.

// declare the counter variable and the sum variable. int counter, sum;

// initialize the counter to 0 and the sum to 0 counter = 0; sum = 0;

// now use a while statement to step the counter from 0 // to 100. At each step, increment the sum by the counter. while (counter <= 100) { // increment the sum by the counter sum = sum + counter; // and increment the counter by one counter = counter + 1; }

// and report our results System.out.println("The sum from 1 to 100 is: " + sum);

} }

**Learning Points:**

1. Study the code carefully to understand how the "sum" variable
holds a running tally and in the end holds the sum of the numbers from 0 to 100.

**Exercises:**

8.1. Write a Java program which reads in 2 integers and prints out the sum of
the integers which lie between them (exclusively).

8.2. The sum of the integers from 1 to n equals n*(n+1)/2. Write a Java
program which confirms this empirically (that is, by observation, rather than by
mathematical proof) by reading in a positive integer n, and using a while loop
to compute the sum from 1 to n, and printing this sum out. Then, also use
the formula to directly compute n*(n+1)/2. Finally, compare these two
values in your program to confirm they are indeed the same.

**P&CS Program #9:
while (true) -- Infinite Loops**

// Program #9 while (true) -- Infinite Loops // <your name>, <the date>, p&cs

class InfiniteLoop { public static void main(String[] args) { // This program uses a while (true) statement to // loop until the user enters the number 0. // To do something interesting, it prints out the // sum of all the numbers entered.

// declare the input variable and the sum variable. int n, sum;

// initialize the sum to 0 sum = 0;

// now loop "forever" while (true) { System.out.print("Enter an integer [0 to quit]: "); n = readInt(); if (n == 0) { // n is zero, so break out of the enclosing while loop break; } sum = sum + n; }

// and report our results System.out.println("The sum of the numbers is: " + sum); } // NOTE: insert readInt() code here... }

**Learning Points:**

1. while (true) loops forever.

2. To exit a loop (including an infinite loop), use the break statement.

**Exercises:**

9.1. Write a Java program which repeatedly reads in an integer n, stopping
when n is negative, and prints out the sum from 0 to n.

9.2. Write a Java program which reads in integers, stopping only when the same
integer is entered in twice in a row. Print out the total number of
integers read.

**P&CS Program #10: Integer
Math**

// Program #10: Integer Math // <your name>, <the date>, p&cs

class Integer Math { public static void main(String[] args) { // declare two integer variables int x, y;

// read their values from the user System.out.print("Enter an integer: "); x = readInt(); System.out.print("Enter another integer: "); y = readInt();

// Math.abs(x) is the absolute value of x System.out.println("abs(" + x + ") = " + Math.abs(x));

// % (pronounced "mod") is the remainder System.out.println(x + " % " + y + " = " + (x%y)); System.out.println(y + " % " + x + " = " + (y%x));

// Math.max(x,y) and Math.min(x,y) do what you expect System.out.println("max: " + Math.max(x,y)); System.out.println("min: " + Math.min(x,y)); } // NOTE: insert readInt() code here... }

**Learning Points:**

1. Math.abs(x) is the absolute value of x

2. x % y, pronounced "x mod y", is the remainder of x divided by y.

3. Math.max(x,y) is the larger of x and y.

4. Math.min(x,y) is the smaller of x and y.

**Exercises:**

10.1. Write a Java program which reads in two integers and uses Math.abs to
print out the positive difference between the two numbers on the number line.

10.2. Write a Java program which reads in two integers and uses Math.min and
Math.max to print out the positive difference between the two numbers on the
number line.

**P&CS Labs: Summary of Lab 1
Programs 1-10 + Additional Exercises**

**Learning Points:
**1. A program is really a class with a main method.

2. The only part you really care about is the code inside the main.

a. The rest, you do not need to understand, but you do need to type in.

3. Java is very particular about the syntax.

b. Java is case-sensitive (you must get upper and lower case exactly correct)

c. Semicolons must follow statements

d. Your code can only go inside the main. Anywhere else is an error.

4. Good programmers (like you!) are very particular about style.

e. Use squiggly braces and indent your code exactly as noted above

f. Use comments to explain what the code does, who wrote it, etc.

g. Many more style rules to follow…

5. A line beginning with // is a comment, and Java ignores the line.

6. System.out.println("foo") prints the word "foo" followed by a newline.

7. Variables have names (like "x" and "y") and hold values (like 10 and 4).

8. Integer variables have integer values

a. Some legal integer values: 2, 0, -20, 1234321

b. Some illegal values: 3.14, "hello"

9. You must declare variables before you use them.

a. This tells Java that these are variables, and what type (here, integers)

b. The line "int x, y;" declares the variables x and y to be integers

10. You can assign values to variables

a. "x = 10;" assigns the value 10 to the variable "x"

11. You can print out variables using System.out.println

12. You can even print out their sum using System.out.println

13. To run programs which call readInt(), you must include the readInt() code from program #3.

14. In general, we should prompt the user ("Enter an integer: "), so the user knows what the program is asking.

15. Use System.out.print instead of System.out.println to stay on the same line.

16. In general, we should also print out the answer in a prettier format.

17. print(x) prints the value of the variable x

18. print("foo") prints whatever is inside the quotes.

19. All your Java programs for now on should use prompts and pretty output.

20. An "if" statement is of the form:

if (test)

{

BODY

}

21. An "if" statement executes its body only if its test is true

22. Important note: In an "if" statement, there is no semicolon after the test!!!

23. A test for equality uses double-equals, as in (x == y)

24. A test for inequality uses exclamation-equals, as in (x != y)

25. Following an "if", you may have an "else if" which provides another test

26. The last "else" can omit the test, in which case its body is executed only if all the preceding tests fail.

27. In any case, at most one body will be executed within in if-else statement. Think about this!

28. A "while" statement is of the form:

while (test)

{

BODY

}

29. A "while" statement repeatedly executes its body so long as its test is true

30. Important note: In a "while" statement, there is no semicolon after the test!!!

31. Study the code in Program #8 carefully to understand how the "sum" variable holds a running tally and in the end holds the sum of the numbers from 0 to 100.

32. while (true) loops forever.

33. To exit a loop (including an infinite loop), use the break statement.

34. Math.abs(x) is the absolute value of x

35. x % y, pronounced "x mod y", is the remainder of x divided by y.

36. Math.max(x,y) is the larger of x and y.

37. Math.min(x,y) is the smaller of x and y.

**Exercises:
**1. Write a Java program which prints out your name.

2. Write a Java program which prints out a knock-knock joke.

3. Write a Java program which prints out the product of two integers. Note that in Java, multiplication is performed with an asterisk (*).

4. Write a Java program which prints out the sum of three integers.

5. Write a Java program which reads in three integers and prints out their sum.

6. Write a Java program which reads in 3 integers and prints their sum and average.

7. Write a Java program which reads in a distance in yards and outputs the same distance in feet. Note that 1 yard = 3 feet.

8. Write a Java program which reads in a distance in feet and outputs the same distance in yards. Note what happens when the input is not a multiple of 3. This is known as truncation.

9. Write a program which reads in the number of free throws a player has attempted, and then the number she made, and prints out her free throw percentage. This is slightly trickier than the previous problems, due to truncation.

10. Write a Java program which reads in 2 integers and prints just the larger integer.

11. Write a Java program which reads in 2 integers and prints whether they sum to 0.

12. Write a Java program which reads in an integer, and if it is positive, prints out the square of the integer, but if it is negative, prints out the cube of the integer, and if it is zero, prints out the message "carpe diem".

13. Write a Java program which reads in a positive integer n and prints out the integers from 0 to n, inclusive.

14. Write a Java program which reads in two integers, and prints out the integers which are between them. Your program must work whether the first or second number is the smaller one. Hint: introduce two more variables, lo and hi, and use an "if" statement to set the values of lo and hi based on the numbers entered.

15. Write a Java program which reads in 2 integers and prints out the sum of the integers which lie between them (exclusively).

16. The sum of the integers from 1 to n equals n*(n+1)/2. Write a Java program which confirms this empirically (that is, by observation, rather than by mathematical proof) by reading in a positive integer n, and using a while loop to compute the sum from 1 to n, and printing this sum out. Then, also use the formula to directly compute n*(n+1)/2. Finally, compare these two values in your program to confirm they are indeed the same.

17. Write a Java program which repeatedly reads in an integer n, stopping when n is negative, and prints out the sum from 0 to n.

18. Write a Java program which reads in integers, stopping only when the same integer is entered in twice in a row. Print out the total number of integers read.

19. Write a Java program which reads in two integers and uses Math.abs to print out the positive difference between the two numbers on the number line.

20. Write a Java program which reads in two integers and uses Math.min and Math.max to print out the positive difference between the two numbers on the number line.

**Additional Exercises
**21. Write a Java program which converts Kilometers to Miles using integer
math. If you do not know the conversion, use the Internet to look it up.

22. Write a Java program which converts from Fahrenheit to Celsius using integer math. To do this conversion, subtract 32 and then multiply by (5/9). The trick, though, is with integer math, 5/9 is zero, so you have to be clever about this. Be sure to include a clear user interface (that is, a clear prompt for input, and a clear explanation of the output).

23. Write a Java program which reads in four integers: x1, y1, x2, y2 (in order), which represent two points (x1,y1) and (x2,y2) on a grid. Print out the "Manhattan" distance from (x1,y1) to (x2,y2). As we discussed, this is the distance one must walk in Manhattan from an intersection at (x1,y1) to an intersection at (x2,y2). As there are buildings in your way, you must walk straight down the x axis, and then straight down the y axis. The answer would simply be the sum of (x2 - x1) and (y2 - y1), except that x2 might be smaller than x1 (and, similarly, y2 might be smaller than y1). Hint: you may wish to use either Math.abs or Math.min/Math.max to solve this problem.

24. Write a Java program which first reads in an integer N, followed by N
more integers, and then prints out the following information (not counting the
number N in your statistics):

a) The largest integer entered;

b) The smallest integer entered;

c) The sum of all the integers entered;

d) The average of all the integers entered.

25. Write a Java program which repeatedly reads in a positive integer n (quitting when n <= 0), and prints out n factorial, where n! = n * (n-1) * (n-2) * ... * 1. Thus, 3 factorial, written 3! = 3 * 2 * 1 = 6. And 4 factorial, written 4! = 4 * 3 * 2 * 1 = 24.

26. Write a Java program which reads in the width and height (as integers) of a triangle, and prints out the area of that triangle.

27. Write a Java program which reads in an integer in [0,100), and makes appropriate change for that many cents. So, if the user enters, say, 73, your program should print that the change is 2 quarters, 2 dimes, and 3 pennies.

28. Write a Java program which reads in three sides (as integers) of a triangle, and prints out whether or not those sides constitute a legal triangle. Note that a triangle is only legal if the sum of any two sides is greater than the third side. So, 2, 3, 10 is not legal, since 2+3<10.

29. Write a Java program which repeatedly reads in a positive integer n
(quitting when n <= 0), and prints out the sum of the perfect squares which
are less than or equal to n. That is, print out 1^{2} + 2^{2}
+ 3^{2} + ... + k^{2}, where k^{2} <= n and (k+1)^{2}
> n. Thus, if n == 12, your program would sum up to 3^{2}, and
would *not* include 4^{2}, because 4^{2} >12. So
the answer for n == 12 is 1^{2} + 2^{2} + 3^{2} == 1 + 4
+ 9 == 14.

30. Write a Java program which reads in an integer N, and prints out whether or not N is even. Hint: You will want to use the mod operator (%) for this, since a number is even if the remainder when that number is divided by 2 is zero.

31. Write a Java program which reads in an integer N, and prints out whether or not N is prime. Hint: once again, you will want to use the mod operator (%), only here you will want to use a while loop to try every number between 2 and n-1.

32. Write a Java program which repeatedly reads in an integer N, quitting when N is non-positive (that is, when N <= 0), and prints out whether or not N is prime.

33. Write a Java program which reads in an integer n and prints out the prime factorization of n. That is, the product of prime numbers which equals n. For example, if you read in 45, your program should print out 45 = 3*3*5. Hint: you do not need a prime test for this program. Just start a counter at 2, and if the counter divides n evenly, print the counter out and divide n by the counter, otherwise increment the counter by one. Stop this process when n equals 1. Try this by hand to verify it works. Also, be sure to get the asterisks right.

34. Write a Java program which finds the single-digit numbers a, b, c, and d
such that a^{b}c^{d} = abcd. So, for example, the answer
is *not* 4253, because 4^{2}5^{3} = 16 * 125 = 2000
!= 4253. Output the 4-digit number abcd. Note that
your program must compute the answer, and not just print it out directly.

*Hint #1: don't be too clever here. Just use nested while loops to
try every combination of a,b,c,d where each digit is in the range [0,9].
Hint #2: To compute the integer value of x*

(int)Math.pow(x,y);

Thus, for example, to assign the variable "z" the value of x

z = (int)Math.pow(x,y); // set z to x^y

See Course Home Page.