| |
|
|
| |
- Write a program to print the numbers from 1 to 50
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR01
// Author: Joshua S. Hodas
// Date: October 22, 1996
// Purpose: Prints the numbers from 1 to 50
import HMC.HMCSupport;
class LAB05PR01 {
public static void main(String args[]) {
HMCSupport.out.println("This program prints the numbers 1-50.");
HMCSupport.out.println();
for (int count = 1 ; count <= 50 ; count++) {
HMCSupport.out.println(count);
}
}
}
|
- Modify the last program so that it also prints the sum of the numbers at the end.
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR01b
// Author: Joshua S. Hodas
// Date: October 22, 1996
// Purpose: Prints the numbers from 1 to 50 and their sum
import HMC.HMCSupport;
class LAB05PR01b {
public static void main(String args[]) {
int sum = 0;
HMCSupport.out.println("This program prints the numbers 1-50"
+ " and their sum.");
HMCSupport.out.println();
for (int count = 1 ; count <= 50 ; count++) {
HMCSupport.out.println(count);
sum = sum + count;
}
HMCSupport.out.println();
HMCSupport.out.println("The sum is " + sum);
}
}
|
- Modify the last program to first ask the user for a number and then to print the sum of the numbers from 1 to that number (but not to print the numbers themselves).
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR01c
// Author: Joshua S. Hodas
// Date: October 22, 1996 (Modified October 4, 1998)
// Purpose: Prints the numbers from 1 to a user supplied number
// and their sum. (But not the numers themselves)
import HMC.HMCSupport;
class LAB05PR01c {
public static void main(String args[]) {
int topValue, sum = 0;
HMCSupport.out.println("This program prints the sum of "
+ " through a number you type.");
HMCSupport.out.println();
HMCSupport.out.print("What number should we go to? ");
topValue = HMCSupport.in.nextInt();
for (int count = 1 ; count <= topValue ; count++) {
sum = sum + count;
}
HMCSupport.out.println("The sum is " + sum);
}
}
|
- Modify the last number to ask the user for a lower number and an upper number, and to then print the numbers from the lower number to the upper number, and their sum.
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR01d
// Author: Joshua S. Hodas
// Date: October 22, 1996
// Purpose: Prints the numbers in a user supplied range
// and their sum.
import HMC.HMCSupport;
class LAB05PR01d {
public static void main(String args[]) {
int bottomValue, topValue, sum = 0;
HMCSupport.out.println("This program prints the numbers in"
+ " a range you specify and their sum.");
HMCSupport.out.println();
HMCSupport.out.print("What number should we start with? ");
bottomValue = HMCSupport.in.nextInt();
HMCSupport.out.print("What number should we go to? ");
topValue = HMCSupport.in.nextInt();
for (int count = bottomValue ; count <= topValue ; count++) {
HMCSupport.out.println(count);
sum = sum + count;
}
HMCSupport.out.println();
HMCSupport.out.println("The sum is " + sum);
}
}
|
|
|
| |
Ask the user for 5 numbers (by using a for loop) and tell them the product of those numbers.
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR02
// Author: Joshua S. Hodas
// Date: October 22, 1996
// Purpose: Prints the product of 5 user-supplied numbers.
import HMC.HMCSupport;
class LAB05PR02 {
public static void main(String args[]) {
int product = 1;
HMCSupport.out.println("This program prompts for 5 numbers"
+ " and calculates their product.");
HMCSupport.out.println();
for (int count = 1 ; count <= 5 ; count++) {
int value;
HMCSupport.out.print("Please enter value #" + count + ": ");
value = HMCSupport.in.nextInt();
product = product * value;
}
HMCSupport.out.println();
HMCSupport.out.println("The product is " + product);
}
}
|
|
|
| |
Ask the user for 5 numbers (by using a for loop) and tell which of those numbers is largest.
|
| Solution A |
This first solution is simple. The basic idea is to keep track of the largest
number the user has typed so far. Each time through the loop they type another number,
and we compare it to the stored value of the largest number so far. If the new number is
larger than the largest so far, we replace the largest so far with the new number.
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR03a
// Author: Joshua S. Hodas
// Date: October 22, 1996
// Purpose: Prints the largest of 5 user-supplied numbers.
// To find the largest number they type, we will check each
// number against the largest typed so far. If the new number
// is larger, then we replace the largest-so-far with the
// new number.
import HMC.HMCSupport;
class LAB05PR03a {
public static void main(String args[]) {
int largestSoFar = 0;
HMCSupport.out.println("This program prompts for 5 numbers"
+ " and determines the largest.");
HMCSupport.out.println();
for (int count = 1 ; count <= 5 ; count++) {
int value;
HMCSupport.out.print("Please enter value #" + count + ": ");
value = HMCSupport.in.nextInt();
if (largestSoFar < value) {
largestSoFar = value;
}
}
HMCSupport.out.println();
HMCSupport.out.println("The largest of those is "
+ largestSoFar);
}
}
|
|
| Solution B |
The last solution is fine, unless the user types negative numbers for each of their
inputs. Since we started by setting the largest so far to zero, it will never get
overwritten, and we will tell the user that zero is the largest number they typed,
even though they never typed it!
One solution is to put some really big (or is that small?) negative number for the
initial value of the largest so far. In fact, in Java we know that the largest
(smallest?) negative value for an int variable is -2,147,483,648.
But what if we decide to use longs instead? Also, some languages
don't guarantee you anything about the possible range of each type. So it is
better to come up with a more general solution. The solution is to start
off the value of the largest so far with the first value they enter. Then it
will certainly end up being one of the values they type.
In this version of the solution we get the first input outside the loop, putting
the value directly into the variable holding the largest value seen so far.
Then the loop executes to get the second through fifth inputs.
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR03b
// Author: Joshua S. Hodas
// Date: October 22, 1996
// Purpose: Prints the largest of 5 user-supplied numbers.
// To find the largest number they type, we will check each
// number against the largest typed so far. If the new number
// is larger, then we replace the largest-so-far with the
// new number.
// To make it most general, we start the largest-so-far
// with the first number they type. Otherwise it won't
// work if they type all negative values.
import HMC.HMCSupport;
class LAB05PR03b {
public static void main(String args[]) {
int largestSoFar;
HMCSupport.out.println("This program prompts for 5 numbers"
+ " and determines the largest.");
HMCSupport.out.println();
HMCSupport.out.print("Please enter value #1: ");
largestSoFar = HMCSupport.in.nextInt();
for (int count = 2 ; count <= 5 ; count++) {
int value;
HMCSupport.out.print("Please enter value #" + count + ": ");
value = HMCSupport.in.nextInt();
if (largestSoFar < value) {
largestSoFar = value;
}
}
HMCSupport.out.println();
HMCSupport.out.println("The largest of those is "
+ largestSoFar);
}
}
|
|
| Solution C |
This version of the solution uses the same idea as the last version, but instead of
actually moving the first prompt and input out of the loop, we leave it in the
loop. Now, in order to get the first value typed into the variable for the largest so far,
we just modify the conditional so that on the first pass through the loop the value
of the largest so far will be overwritten by the input, regardless of its value:
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR03c
// Author: Joshua S. Hodas
// Date: October 22, 1996
// Purpose: Prints the largest of 5 user-supplied numbers.
// To find the largest number they type, we will check each
// number against the largest typed so far. If the new number
// is larger, then we replace the largest-so-far with the
// new number.
// To make it most general, we start the largest-so-far
// with the first number they type. Otherwise it won't
// work if they type all negative values.
// Here we get that value in the first pass through the loop.
import HMC.HMCSupport;
class LAB05PR03c {
public static void main(String args[]) {
int largestSoFar = 0;
HMCSupport.out.println("This program prompts for 5 numbers"
+ " and determines the largest.");
HMCSupport.out.println();
for (int count = 1 ; count <= 5 ; count++) {
int value;
HMCSupport.out.print("Please enter value #" + count + ": ");
value = HMCSupport.in.nextInt();
if ( (count == 1) || (largestSoFar < value) ) {
largestSoFar = value;
}
}
HMCSupport.out.println();
HMCSupport.out.println("The largest of those is "
+ largestSoFar);
}
}
|
|
|
| |
Print those numbers from 1 to 50 that are divisible by 2.
Here again, there are two possible solutions. We have included them together in one program.
In the first solution, we recognize that 1 will not qualify, and that we can therefore run the
loop from 2 to 50. All we need to do then is increment the loop counter by 2 each time rather
than by 1.
In the second solution, we have the loop count all the numbers from one to fifty, but we
only print those for which the remainder when divided by 2 is 0. That is, the even ones.
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR04
// Author: Joshua S. Hodas
// Date: October 10, 1997 (Modified 10/4/98)
// Purpose: Prints the numbers from 1 to 50 divisible by 2
import HMC.HMCSupport;
class LAB05PR04 {
public static void main(String args[]) {
HMCSupport.out.println("This program prints the numbers 1-50 which ");
HMCSupport.out.println("are divisible by 2. This is done in two ways.");
HMCSupport.out.println();
// Here we count from 2 to 50 by 2's, only touching the even numbers
for (int count = 2 ; count <= 50 ; count = count + 2) {
HMCSupport.out.println(count);
}
HMCSupport.out.println();
// Here we count from 1 to 50 and test each number to see if it is even.
for (int count = 1 ; count <= 50 ; count++) {
if (count % 2 == 0) {
HMCSupport.out.println(count);
}
}
HMCSupport.out.println();
}
}
|
|
|
| |
Print (in order) those numbers from 1 to 50 that are divisible by 2 or divisible by 3.
For this problem, only the latter solution from the last problem will work. We
count off all the numbers, but only print those that are divisible by either
2 or 3. (Well, we could count off by three and see which are divisible by two.
That would work too.)
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR05
// Author: Joshua S. Hodas
// Date: October 10, 1997
// Purpose: Prints the numbers from 1 to 50 divisible by 2 or 3
import HMC.HMCSupport;
class LAB05PR05 {
public static void main(String args[]) {
HMCSupport.out.println("This program prints the numbers 1-50 which are ");
HMCSupport.out.println("divisible by 2 or by 3.");
HMCSupport.out.println();
for (int count = 1 ; count <= 50 ; count++) {
if (count % 2 == 0 || count % 3 == 0) {
HMCSupport.out.println(count);
}
}
HMCSupport.out.println();
}
}
|
|
|
| |
Ask the user for a number and tell them all the factors of the number (i.e. the numbers
between 1 and the number that the number is divisible by).
The structure of this program is similar to the last one. But instead of testing whether
the loop counter is divisible by 2 or 3, we test whether the user's value is divisible
by the loop counter.
Note that we start the loop at 2, since 1 is not counted as a factor, even though the
number will be divisible by it. Similarly, a number is not considered a factor of
itself, so we stop the loop at one less than the user's value. We can do this either
by writing count <= (userValue - 1) or, alternately, by
count < userValue. The latter is the more usual style, and the one we use.
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR06
// Author: Joshua S. Hodas
// Date: October 10, 1997
// Purpose: Prints the factors of a user supplied number.
import HMC.HMCSupport;
class LAB05PR06 {
public static void main(String args[]) {
int userValue;
HMCSupport.out.println("This program prints the factors of" +
" a number you type.");
HMCSupport.out.println();
HMCSupport.out.print("What number should we use? ");
userValue = HMCSupport.in.nextInt();
for (int count = 2 ; count < userValue ; count++) {
if (userValue % count == 0) {
HMCSupport.out.println(count + " is a factor of " + userValue);
}
}
HMCSupport.out.println();
}
}
|
|
|
| |
Ask the user for a number and tell them whether it is prime.
How do we solve this problem? The first thought might be to modify the
last program so that when the loop counter does divide into the user's
value we print that the user's value is not prime, and when it does
not, we print that the user's value is prime (by adding an
else to the if statement inside the loop.
The problem is, suppose the user's value is 24. Then when we test the
first number, 2, we will print that the number is not prime. But a
moment later, when we test 3, we will print that the number is
prime. Obviously, we can't make the decision based on whether one
value or another divides into the user's value. It must be that none
does.
The solution is to use a boolean flag variable that will
keep track of whether we have seen any factors of the user's value. We
begin by setting it to false, and then set it to true if we encounter
a number that is a factor. If this value is still false at the end of
the loop (that is, after we have tested all the possible factors) then
the user's number is prime.
Of course, once we have tested that the number is not even, we only
need to test odd number to see whether they are factors, so the test
for divisibility by two is broken off at the front.
|
| Note that we only need to test the
values of the number up to the square root of the user's number to see
if the user's number is prime. If there is a factor that is greateer
than the square root, then there has to be a factor that is less than
the square root as well.
We could write the loop header as:
for (int count = 3 ; count <= Math.ceil(Math.sqrt(userValue)) ; count += 2)
but then we would compute the square root of a fixed value each time
through the loop. This would be inefficient. Instead, we will compute
it once at the beginning and store it off: [Macro error: String
constant isn't correctly specified. Must be of the form
"abcd".]
WARNING: the following program has a bug. 2 is prime, but this
program will identify it as not prime.
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR07
// Author: Joshua S. Hodas
// Date: October 10, 1997 (Modified 10/4/98)
// Purpose: Tests whether a user supplied number is prime.
import HMC.HMCSupport;
class LAB05PR07 {
public static void main(String args[]) {
int userValue, topValue;
boolean sawFactor;
HMCSupport.out.println("This program tests whether a number you type" +
" is prime or not.");
HMCSupport.out.println();
HMCSupport.out.print("What number should we test? ");
userValue = HMCSupport.in.nextInt();
if (userValue % 2 == 0) { // number is even
HMCSupport.out.println("The value " + userValue + " is not prime.");
}
else {
sawFactor = false;
topValue = (int) Math.ceil(Math.sqrt(userValue));
for (int count = 3 ; count <= topValue ; count += 2) {
if (userValue % count == 0) {
sawFactor = true;
}
}
if (sawFactor) {
HMCSupport.out.println("The value " + userValue + " is not prime."); }
else {
HMCSupport.out.println("The value " + userValue + " is prime.");
}
HMCSupport.out.println();
}
}
}
|
|
|
| |
Modify the program
StudentAverage
so that it is possible for each student to have a different number of grades to be averaged.
That is, ask for the number of homeworks for each student, rather than just once.
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR08
// Author: Joshua S. Hodas
// Date: October 4, 1998
// Purpose: A student grade averager. Modified version from notes to
// ask for number of assignments for each student individually.
import HMC.HMCSupport;
class LAB05PR08 {
public static void main(String args[]) {
int numStudents, numHomeworks;
HMCSupport.out.println("This computes students' average grades.");
HMCSupport.out.print("How many students are there? ");
numStudents = HMCSupport.in.nextInt();
for (int studentNum = 1 ; studentNum <= numStudents ; studentNum++) {
double grade, sum = 0, average;
HMCSupport.out.print("How many homework assignments are there " +
"for this student? ");
numHomeworks = HMCSupport.in.nextInt();
for (int gradeNum=1 ; gradeNum <= numHomeworks ; gradeNum++) {
HMCSupport.out.print("Please enter grade #" + gradeNum
+ " for student #" + studentNum + ": ");
grade = HMCSupport.in.nextDouble();
sum = sum + grade;
}
average = sum / numHomeworks;
HMCSupport.out.println("The average of the grades for student #" +
studentNum + " is " + average);
}
}
}
|
|
|
| |
Further modify the last program so that at the end it prints the average of the students'
average grades.
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR09
// Author: Joshua S. Hodas
// Date: October 4, 1998
// Purpose: A student grade averager. Modified version from notes to
// ask for number of assignments for each student individually.
// Also prints the average of the averages.
import HMC.HMCSupport;
class LAB05PR09 {
public static void main(String args[]) {
int numStudents, numHomeworks;
double sumAverages, averageAverage;
HMCSupport.out.println("This computes students' average grades.");
HMCSupport.out.print("How many students are there? ");
numStudents = HMCSupport.in.nextInt();
sumAverages = 0; // We set the sum of the averages to zero
for (int studentNum = 1 ; studentNum <= numStudents ; studentNum++) {
double grade, sum = 0, average;
HMCSupport.out.print("How many homework assignments are there " +
"for this student? ");
numHomeworks = HMCSupport.in.nextInt();
for (int gradeNum=1 ; gradeNum <= numHomeworks ; gradeNum++) {
HMCSupport.out.print("Please enter grade #" + gradeNum
+ " for student #" + studentNum + ": ");
grade = HMCSupport.in.nextDouble();
sum = sum + grade;
}
average = sum / numHomeworks;
HMCSupport.out.println("The average of the grades for student #" +
studentNum + " is " + average);
sumAverages += average; // Add this average into the sum of averages
}
averageAverage = sumAverages / numStudents;
HMCSupport.out.println("The average of the students' averages is: " +
averageAverage);
}
}
|
|
|
| |
Further modify the last program so that at the end it prints the average of all the homework grades. Since each student may have a different number of homeworks, this may
not be the same as the average added in the last problem.
| Click Here To Run This Program On Its Own Page |
// Program: LAB05PR10
// Author: Joshua S. Hodas
// Date: October 4, 1998
// Purpose: A student grade averager. Modified version from notes to
// ask for number of assignments for each student individually.
// Also prints the average of the averages.
// Also prints average of all assignments
import HMC.HMCSupport;
class LAB05PR10 {
public static void main(String args[]) {
int numStudents, numHomeworks, totalNumHomeworks;
double sumAverages, averageAverage,
sumSums, averageAll;
HMCSupport.out.println("This computes students' average grades.");
HMCSupport.out.print("How many students are there? ");
numStudents = HMCSupport.in.nextInt();
sumAverages = 0; // We set the sum of the averages to zero
sumSums = 0; // and the same for the sum of the sums.
totalNumHomeworks = 0; // and for the total number of assignments.
for (int studentNum = 1 ; studentNum <= numStudents ; studentNum++) {
double grade, sum = 0, average;
HMCSupport.out.print("How many homework assignments are there " +
"for this student? ");
numHomeworks = HMCSupport.in.nextInt();
for (int gradeNum=1 ; gradeNum <= numHomeworks ; gradeNum++) {
HMCSupport.out.print("Please enter grade #" + gradeNum
+ " for student #" + studentNum + ": ");
grade = HMCSupport.in.nextDouble();
sum = sum + grade;
}
average = sum / numHomeworks;
HMCSupport.out.println("The average of the grades for student #" +
studentNum + " is " + average);
sumAverages += average; // Add this average into the sum of averages
sumSums += sum; // Add this sum of homeworks into sum of sums
totalNumHomeworks += numHomeworks; // similarly for HW count
}
averageAverage = sumAverages / numStudents;
HMCSupport.out.println("The average of the students' averages is: " +
averageAverage);
averageAll = sumSums / totalNumHomeworks;
HMCSupport.out.println("The average of all homeworks is: " +
averageAll);
}
}
|
|