Download Chapter 7

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Elementary mathematics wikipedia , lookup

Addition wikipedia , lookup

Transcript
hapter
For Loops
For Loops:
A for-loop is a control structure that is used when you need to repeat one or more statements a
certain number of times. The for-loop is an example of a count-controlled loop.
Here is the format of a for-loop:
for(counter variable is assigned
Boolean expression
counter
{
statements to be repeated are
}
an initial value;
containing counter variable;
variable is increased or decreased)
written here
Here is an example of a for-loop:
int count;
for(count = 1; count <= 5; count = count + 1)
{
System.out.println(count);
}
To understand the snippet above, you have to examine how the counter variable changes with
each iteration (pass through the loop).
Iteration #
count
count <= 5
output
1
1
true
1
2
2
true
2
3
3
true
3
4
4
true
4
5
5
true
5
6
false
An easier way to write
count = count + 1;
is
count++;
Java-Jive
© kweiser 10/03- 06/04
Page 67
Thus, the code above can also be written like this:
int count;
for(count = 1; count <= 5; count++)
{
System.out.println(count);
}
For-loops can also count backwards by changing the part inside the parentheses where the
counter variable is incremented.
Increment the
counter variable
Decrement the
counter variable
count = count + 1
count ++
count = count – 1
count --
Questions:
1. Trace:
int count;
for(count = 5; count >= 2; count--)
{
System.out.println(count);
}
2. Trace:
int count;
for(count = 4; count < 5; count++)
{
System.out.print(count);
}
3. Trace:
int count;
for(count = 1; count <= 5; count--)
{
System.out.println(count);
}
4. Trace:
int count;
for(count = 10; count <= 14; count++)
{
System.out.print(count + " ");
}
Java-Jive
© kweiser 10/03- 06/04
Page 68
Lab # 51:
Write a program using a for loop that prints the following output:
10
9
8
7
6
5
4
3
2
1
Blastoff!
Requirements of this program:
The program output should look similar to the
run above.
There is no input.
One run is sufficient.
Lab # 52:
Ani’s Garden Shoppe uses mailing labels for shipping boxes. Write a program to display a
mailing label for each box to be shipped.
Sample runs:
How many boxes? 2
ANI’S GARDEN SHOPPE
BURBANK, CA 91502
BOX # 1 OF 2
ANI’S GARDEN SHOPPE
BURBANK, CA 91502
BOX # 2 OF 2
How many boxes? 4
Requirements of this program:
ANI’S GARDEN SHOPPE
BURBANK, CA 91502
BOX # 1 OF 4
ANI’S GARDEN SHOPPE
BURBANK, CA 91502
BOX # 2 OF 4
•
The program output should look
similar to the run above.
•
Show three different runs.
ANI’S GARDEN SHOPPE
BURBANK, CA 91502
BOX # 3 OF 4
ANI’S GARDEN SHOPPE
BURBANK, CA 91502
BOX # 4 OF 4
Java-Jive
© kweiser 10/03- 06/04
Page 69
Questions:
5. Trace:
int counter;
System.out.println("Here we go.\n");
for (counter = 1; counter <= 5; counter++)
System.out.println("Hi guys. This is loop " + counter + " ." );
System.out.println("\nWe're done." );
RAM
Output
Explain what this program does:
6. Trace:
int count;
System.out.println("Here we go.\n");
for (count = 1; count <= 9; count++)
{
if (count % 2 == 0)
System.out.print(count + " ");
}
System.out.println("\nWe're done." );
RAM
Output
Explain what this program does:
Java-Jive
© kweiser 10/03- 06/04
Page 70
7. Trace:
int count;
System.out.println("Here we go.\n");
for (count = 0; count <= 10; count++)
if (count % 3 == 0)
System.out.print(count + " ");
System.out.println("\nWe're done." );
RAM
Output
Explain what this program does:
8. Trace:
int count;
System.out.println("Here we go.\n");
for (count = 1; count <= 9; count++)
{
if (count % 2 == 1)
System.out.print(count + " ");
}
System.out.println("\nWe're done." );
RAM
Output
Explain what this program does:
Java-Jive
© kweiser 10/03- 06/04
Page 71
9. Trace:
int count, sum = 0;
for (count = 1; count <= 5; count++)
{
sum = sum + count;
System.out.println("sum = " + sum);
}
RAM
Output
Explain what this program does:
10. Trace:
int count, sum = 0;
for (count = 1; count <= 5; count++)
{
System.out.println("sum = " + sum);
sum = sum + count;
}
RAM
Output
Explain what this program does:
Java-Jive
© kweiser 10/03- 06/04
Page 72
11. Trace:
int count, sum = 0;
for (count = 1; count <= 5; count++)
{
sum = sum + count;
}
System.out.println("sum = " + sum);
RAM
Output
Explain what this program does:
Lab # 53:
Write a program that displays all of the integers between two input numbers, inclusive. It should
work whether or not the first number is less than the second number.
Sample runs:
First number = 35
Second number = 53
35
36
37
38
39
40
41
42
43
45
46
47
48
49
50
51
52
53
44
First number = 73
Second number = 38
38
48
58
68
39
49
59
69
40
50
60
70
41
51
61
71
42
52
62
72
43
53
63
73
44
54
64
45
55
65
46
56
66
47
57
67
Java-Jive
Requirements of this program:
•
The program output should look
similar to the run above.
•
Show three different runs -- at least
one run where the first number is
less than the second, and at least
one where the first number is greater
than the second.
© kweiser 10/03- 06/04
Page 73
Lab # 54:
Write a program that lists the integers from 1 to 20, their squares, square roots, cubes, and
fourth roots, all in a five-column table. Each decimal number should be written to two decimal
places.
Sample run:
Square
Fourth
Number
Square
Root
Cube
Root
======================================================
1
1
1.00
1
1.00
2
4
1.41
8
1.19
3
9
1.73
27
1.32
4
16
2.00
64
1.41
5
25
2.24
125
1.50
6
36
2.45
216
1.57
7
49
2.65
343
1.63
8
64
2.83
512
1.68
9
81
3.00
729
1.73
10
100
3.16
1000
1.78
11
121
3.32
1331
1.82
12
144
3.46
1728
1.86
13
169
3.61
2197
1.90
14
196
3.74
2744
1.93
15
225
3.87
3375
1.97
16
256
4.00
4096
2.00
17
289
4.12
4913
2.03
18
324
4.24
5832
2.06
19
361
4.36
6859
2.09
20
400
4.47
8000
2.11
Requirements of this program:
•
The program output should look similar to the run above.
•
There is no input.
•
One run is sufficient.
•
Use the Math class' methods to calculate all of the values.
Java-Jive
© kweiser 10/03- 06/04
Page 74
Counting and Summing:
Common tasks that need to be accomplished by a program are counting and summing. A
program might need to count the number of positive numbers entered by a user. Look at the
example below:
int count, num, posCount = 0;
for(count = 1; count <= 5; count++)
{
System.out.print("Number = ");
num = input.readInt();
if (num > 0)
posCount++;
// num is positive
}
System.out.println ("You entered " + posCount + "positive numbers.");
/* Sample run:
Number
Number
Number
Number
Number
=
=
=
=
=
45
-3
234
0
3
You entered 3 positive numbers.
*/
Also a program might need to sum numbers entered by the user. An example of this can be
seen below:
int count, num, sum = 0;
for(count = 1; count <= 5; count++)
{
System.out.print("Number = ");
num = input.readInt();
sum = sum + num;
}
System.out.println ("The sum is " + sum + ".");
/* Sample run:
Number
Number
Number
Number
Number
=
=
=
=
=
45
-3
234
0
3
The sum is 279.
*/
Java-Jive
© kweiser 10/03- 06/04
Page 75
Another way of writing the statement
sum = sum + num;
is
sum += num;
So the previous example program can be written like this:
int count, num, sum = 0;
for(count = 1; count <= 5; count++)
{
System.out.print("Number = ");
num = input.readInt();
sum += num;
}
System.out.println ("The sum is " + sum + ".");
You may use this shortened version of an assignment statement with addition if you wish. Java
has several other shortened versions of assignment statements.
Regular Assignment Statement
answer = answer + num;
Shortened Assignment Statement
answer += num;
answer = answer – num;
answer -= num;
answer = answer * num;
answer *= num;
answer = answer / num;
answer /= num;
answer = answer % num;
answer %= num;
Lab # 55:
Write a program that calculates the average and total for a given number of test grades. The
program should first read in the number of grades and then read in all the grades.
Sample run:
Requirements of this program:
YOUR TEST AVERAGE
How many tests have you taken? 4
Test
Test
Test
Test
grade
grade
grade
grade
#
#
#
#
1
2
3
4
=
=
=
=
96
87
100
91
•
The program output should look
similar to the run at the left.
•
The student's average should be
printed to 3 decimal places.
•
Show three different runs.
The total of your tests is 374
Your test average is 93.500
Java-Jive
© kweiser 10/03- 06/04
Page 76
Lab # 56:
Write a program that displays the sum of all of the integers between two input numbers,
inclusive. The program should ask the user whether (s)he wants to sum odd integers, even
integers, or all integers. Assume that the first number entered will always be less than or equal
to the second number.
Sample runs:
***********
Sum
**********
(O)dd, (E)ven, or (A)ll? O
First number = 4
Second number = 11
The sum of the odd integers from 4 to 11 is 32.
***********
Sum
**********
(O)dd, (E)ven, or (A)ll? A
First number = 4
Second number = 11
The sum of the integers from 4 to 11 is 60.
***********
Sum
**********
(O)dd, (E)ven, or (A)ll? E
First number = 4
Second number = 11
The sum of the even integers from 4 to 11 is 28.
Requirements of this program:
•
The program output should look similar to the runs above.
•
Three different runs are required – one where it sums odd numbers, one where it sums
even numbers, and one where it sums all numbers.
Java-Jive
© kweiser 10/03- 06/04
Page 77
Lab # 57:
Write a program that reads in letter grades for a Computer Programming class of 20 students,
and displays the number of students who passed (received a D or better) and the number who
failed (received an F).
Sample run:
Computer Programming Grades
===========================
Enter
Enter
Enter
Enter
Enter
a grade:
a grade:
a grade:
a grade:
a grade:
...
Requirements of this program:
A
D
C
A
F
•
The program output should look
similar to the run at the left.
•
Show three different runs.
< 20 grades are entered >
16 students passed
4 students failed.
Lab # 58:
Modify Lab 57 to work for a class of any size. First ask the user how many students are in the
class. Next pick up the correct amount of letter grades. The output should also display the
percentage of students passing and failing.
Sample run:
How many students are there?
25
Requirements of this program:
Enter
Enter
Enter
Enter
Enter
a grade: A
a grade: D
a grade: C
a grade: A
a grade: F
...
< 25 grades are entered >
20 students passed:
5 students failed:
•
The program output should look
similar to the run at the left.
•
Percents should be accurate to 2
decimal places.
•
Show three different runs.
80.00%
20.00%
Java-Jive
© kweiser 10/03- 06/04
Page 78
Lab # 59:
Write a program to print a temperature conversion table. Calculate and print the Celsius
equivalents of all Fahrenheit temperatures at 10-degree intervals from 00 to 2500. The
conversion formula is C=5/9(F-32).
Sample run:
Temperature Conversion Table
=============================
Fahrenheit
Celsius
--------------------------------0
-17.78
10
-12.22
20
-6.67
30
-1.11
40
4.44
50
10.00
60
15.56
70
21.11
80
26.67
90
32.22
100
37.78
110
43.33
120
48.89
130
54.44
140
60.00
150
65.56
160
71.11
170
76.67
180
82.22
190
87.78
200
93.33
210
98.89
220
104.44
230
110.00
240
115.56
250
121.11
Requirements of this program:
•
The program output should look similar to the run above.
•
There is no input.
•
One run is sufficient.
•
Celsius temperature should be shown to 2 decimal places.
Java-Jive
© kweiser 10/03- 06/04
Page 79
Lab # 60:
The factorial of a positive number is the product of all positive integers less than or equal to the
number. For example, 5 factorial (written 5!) is equal to 5 * 4 * 3 * 2 * 1, or 120.
Write a program that reads a positive integer from the user and displays its factorial.
Sample runs:
FACTORIAL
Enter a positive integer:
5! = 120
Requirements of this program:
5
FACTORIAL
Enter a positive integer:
10! = 3628800
•
The program output should look
similar to the run at the left.
•
Show three different runs.
10
Lab # 61:
Write a program to produce a table of factorials. Prompt the user for the upper limit of the table,
i.e., how many numbers it should contain.
Sample run:
FACTORIALS
Upper Limit =10
1
2
3
4
5
6
7
8
9
10
factorial
factorial
factorial
factorial
factorial
factorial
factorial
factorial
factorial
factorial
=
=
=
=
=
=
=
=
=
=
Requirements of this program:
1
2
6
24
120
720
5040
40320
362880
3628800
Java-Jive
•
The program output should look
similar to the run at the left.
•
Show three different runs.
© kweiser 10/03- 06/04
Page 80
Lab # 62:
Modify Lab 61. Prompt the user for the lower limit and the upper limit of the table. Print out all
the factorials from the lower limit to the upper limit.
Sample run:
FACTORIALS
Requirements of this program:
Lower Limit = 5
Upper Limit = 10
5
6
7
8
9
10
factorial
factorial
factorial
factorial
factorial
factorial
=
=
=
=
=
=
120
720
5040
40320
362880
3628800
•
The program output should look
similar to the run at the left.
•
Show three different runs.
Nested For Loops:
A nested for loop is seen when one for loop is placed inside of another. One of the statements
in the outer for loop is another for loop. The entire inner for loop must be completed before
another iteration of the outer for loop.
Here is an example:
int count1, count2;
for(count1 = 1; count1 <= 3; count1++)
{
for (count2 = 1; count2 <= 5; count2++)
System.out.print(count2 + " ");
System.out.println("\t" + count1);
}
System.out.println ("The sum is " + sum + ".");
/* Sample run:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1
2
3
*/
Java-Jive
© kweiser 10/03- 06/04
Page 81
Questions:
12. Trace:
int count1, count2, sum;
for(count1 = 1; count1 <= 4; count1++)
{
for (count2 = 1; count2 <= 5; count2++)
{
sum = count1 + count2;
System.out.print(sum + " ");
}
System.out.println();
}
RAM
Output
Explain what this program does:
13. Trace:
int count1, count2, sum;
for(count1 = 1; count1 <= 4; count1++)
{
for (count2 = 1; count2 <= count1; count2++)
{
System.out.print("*");
}
System.out.println();
}
RAM
Output
Explain what this program does:
Java-Jive
© kweiser 10/03- 06/04
Page 82
Lab # 63:
Write a program that asks the user for a length, a width, and a particular character. It then
prints out a rectangle using that character.
Sample run:
RECTANGLE
Requirements of this program:
Length = 8
Width = 5
Character = ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
ô
•
The program output should look
similar to the run at the left.
•
Show three different runs.
Java Vocabulary:
1.
for-loop
2.
count-controlled loop
3.
counter variable
4.
iteration
5.
increment the counter variable
6.
decrement the counter variable
7.
nested for loops
8.
initialize the counter variable
9.
infinite loop
Java-Jive
© kweiser 10/03- 06/04
Page 83
More Review Questions:
14. Trace:
int count;
for(count = 5; count >= 12; count--)
{
System.out.print(count);
}
15. Simulate a run:
int count;
for(count = 4; count <= 5; count--)
{
System.out.print(count);
}
16. Trace:
int count;
System.out.println("Here we go.\n");
for (count = 6; count <= 12; count++)
{
if (count % 4 == 0)
System.out.print(count + " ");
}
System.out.println("\nWe're done." );
17. Trace:
int count;
System.out.println("Here we go.\n");
for (count = 0; count <= 10; count++)
if (count % 3 == 0)
System.out.print(count + " ");
System.out.println("\nWe're done." );
Java-Jive
© kweiser 10/03- 06/04
Page 84
18. Trace:
int count, sum = 0;
for (count = 6; count > 2; count--)
{
sum = sum + count;
System.out.println("sum = " + sum);
}
19. Trace:
int count1, count2;
for(count1 = 1; count1 <= 3; count1++)
{
for (count2 = 3; count2 <= 5; count2++)
{
System.out.print(count2);
}
System.out.println();
}
20. Trace:
int count1, count2;
for(count1 = 1; count1 <= 3; count1++)
{
for (count2 = 3; count2 <= 5; count2++)
{
System.out.print(count1);
}
System.out.println("\t" + count2);
}
Java-Jive
© kweiser 10/03- 06/04
Page 85
hapter
Extended
Review from Chapters 0 - 7
Lab # 64:
Write a program that asks the user for the number of minutes and seconds for two different
times, adds the two times together and prints out the resulting number of hours, minutes and
seconds. Note: the resulting minutes and seconds must be less than 60.
Sample Run:
Time # 1:
Minutes
Seconds
Time # 2
Minutes
Seconds
Requirements of this program:
= 42
= 45
= 23
= 32
•
The program output should look
similar to the run at the left.
•
Show three different runs.
The total time is 1:06:17
Lab # 65:
Fractions (Part I)
Write a program that asks the user for the numerator and denominator of a fraction. The
program should calculate and print the fraction in reduced form.
Sample Run:
Requirements of this program:
Numerator = 2
Denominator = 8
2/8 reduced is 1/4
•
The program output should look
similar to the run at the left.
•
Show three different runs.
Numerator = 14
Denominator = 21
14/21 reduced is 2/3
Java-Jive
© kweiser 10/03- 06/04
Page 86
Lab # 66:
Fractions (Part II)
Start with Lab 65 to create a program that asks the user for the numerator and denominator of
two different fractions. Add the two fractions together and print out the sum (in reduced form).
Sample Run:
first fraction:
Numerator =
Denominator
second fraction:
Numerator =
Denominator
Requirements of this program:
2
= 3
14
= 15
•
The program output should look
similar to the run at the left.
•
Show three different runs.
2/3 + 14/15 = 8/5 or 1 3/5.
Lab # 67:
Fractions (Part III)
Start with Lab 66. Add to and modify the program so that it will ask the user if s/he wants to
add, subtract, multiply, or divide 2 fractions. Then have it get the two fractions from the user,
perform the operation on the fractions, and print out the result in reduced form.
Sample Run:
FRACTION ARITHMETIC
===================
Do you want to (A)dd, (S)ubtract, (M)ultiply, or (D)ivide? D
first fraction:
Numerator =
Denominator
second fraction:
Numerator =
Denominator
2
= 3
14
= 15
2/3 / 14/15 = 5/7.
Requirements of this program:
•
The program output should look similar to the run above.
•
Show one run for each arithmetic operation.
Java-Jive
© kweiser 10/03- 06/04
Page 87