0% found this document useful (0 votes)
18 views8 pages

Chapter 8

chapter 8 computer science cse 1030 beginning chapter

Uploaded by

hotredrose39
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views8 pages

Chapter 8

chapter 8 computer science cse 1030 beginning chapter

Uploaded by

hotredrose39
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

hapter

While Loops
While Loops:
A while loop is a control structure that is used when you need to repeat one or more
statements. Remember a for loop is an example of a count-controlled loop. A while loop
can either be a count-controlled loop or an event-controlled loop.
Here is the format of a while loop:
initialize loop-control variable
while (loop-control variable is not at some value)
{
statements to be repeated are written here including a statement
that can change the loop-control variable
}

Count-Controlled While Loops:


Here is an example of a count-controlled for loop:
int count;
for(count = 1; count <= 5; count++)
{
[Link](count);
}

Here is an example of a count-controlled while loop:


1

int count = 1;

2
3
4
5
6

while(count <= 5)
{
[Link](count);
count++;
}

When using a while loop, you must initialize the counter variable before the beginning of the
loop (line 1). The Boolean expression is tested (line 2). If it is true then the statements inside the
curly braces are executed. If it is false, the while loop is skipped. Inside the while loop
statements, the counter variable is incremented (line 5).

Java-Jive

kweiser 10/03- 06/04


Page 88

Questions:
1. Trace:
int count;
for(count = 2; count <= 6; count++)
{
[Link](count);
}

2. Trace:
int count=5;
while (count > 0)
{
[Link](count);
count--;
}

3. Write a for loop that sums all the integers from 1 to 100

4. Write a while loop that sums all the integers from 1 to 100

Lab # 68:
Modify Lab 51 so that it uses a while loop instead of a for loop.

Lab # 69:
Modify Lab 55 so that it uses a while loop instead of a for loop.
Java-Jive

kweiser 10/03- 06/04


Page 89

Event-Controlled While Loops:


An event-controlled loop will be repeated until some event happens. For instance you could
ask the user to enter test scores or a -1 when finished. This way the user doesn't have to tell
you in advance how many tests have been taken. The value the user enters when finished is
called a sentinel.

int score;
[Link]("Test score (-1 to end): ");
score = [Link]();
while(score != -1)
{
// process the score
[Link]("Test score (-1 to end): ");
score = [Link]();
}

Processing the score might involve counting the scores, summing the scores, or both.

Lab # 70:
Modify lab 55 again (or lab 69) again so that it calculates the average and total of test grades.
The program will read grades from the user until the user inputs -1. Don't count the 1 in the
number of grades or in the sum of the grades.
Sample run:

Requirements of this program:

YOUR TEST AVERAGE


Test
Test
Test
Test
Test

grade
grade
grade
grade
grade

(-1
(-1
(-1
(-1
(-1

to
to
to
to
to

stop) = 96
stop) = 87
stop) = 100
stop) = 91
stop) = -1

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 90

Lab # 71:
Modify Lab 58 to work for a class of any size. Ask the user to keep entering grades or enter the
letter "Z" to stop. Dont count the "Z" in the number of grades.
Sample run:
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter

a
a
a
a
a
a
a
a

grade
grade
grade
grade
grade
grade
grade
grade

(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,

5 students passed:
2 students failed:

or
or
or
or
or
or
or
or

Z
Z
Z
Z
Z
Z
Z
Z

to
to
to
to
to
to
to
to

stop):
stop):
stop):
stop):
stop):
stop):
stop):
stop):

71.43%
28.57%

A
D
C
A
F
F
B
Z

Requirements of this program:

The program output should


look similar to the run at the
left.

Percents should be accurate


to 2 decimal places.

Show three different runs.

Error Traps:
Sometimes the user doesn't enter a correct value. For instance, if you asked the user for his
birth month, he might think you said birth year and enter 1988. If the user's birth month were to
be used in some calculation, the rest of your program would not work correctly. You can trap
errors like these by putting an error trap in your program.
int month;
[Link]("Enter your birth month: ");
month = [Link]();
while((month < 1) || (month > 12))
{
[Link]("/nERROR/n");
[Link]("Enter your birth month: ");
month = [Link]();
}
[Link] ("\nYour birthday is in month # " + month);
// Calculations that happen here will work with
// a valid birth month.
Sample run:
Enter your birth month: 1988
ERROR
Enter your birth month: -53
ERROR
Enter your birth month: 4
Your birthday is in month # 4
Java-Jive

kweiser 10/03- 06/04


Page 91

Error traps make your programs more robust. A robust program is less likely to crash or
produce nonsense results due to bad data.

Lab # 72:
Modify Lab 70 to trap any user input errors for test scores over 100 or less than 0.
Sample run:

Requirements of this program:

YOUR TEST AVERAGE


Test grade (-1 to
Test grade (-1 to
ERROR. Test grade
ERROR. Test grade
Test grade (-1 to
Test grade (-1 to
Test grade (-1 to

stop) = 96
stop) = 187
(-1 to stop) = -87
(-1 to stop) = 87
stop) = 100
stop) = 91
stop) = -1

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, each with


user data errors.

The total of your tests is 374


Your test average is 93.500

Lab # 73:
Modify Lab 71 to trap user input errors for grades.
Sample run:
Enter
Enter
Enter
Enter
ERROR
Enter
ERROR
Enter
Enter
Enter
Enter
Enter

a
a
a
a

grade
grade
grade
grade

(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,

or
or
or
or

Z
Z
Z
Z

to
to
to
to

stop):
stop):
stop):
stop):

A
D
C
E

Requirements of this program:

The program output should


look similar to the run at the
left.

Percents should be accurate


to 2 decimal places.

Show three different runs,


each with user data errors.

a grade (A,B,C,D,F, or Z to stop): Q


a
a
a
a
a

grade
grade
grade
grade
grade

(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,

5 students passed:
2 students failed:

or
or
or
or
or

Z
Z
Z
Z
Z

to
to
to
to
to

stop):
stop):
stop):
stop):
stop):

A
F
F
B
Z

71.43%
28.57%

Lab # 74:
You deposit $2500.00 in a new super Certificate of Deposit (CD) at your bank. Write a program
to calculate how many years it will take for your CD to be worth $5000.00 or more, if it pays 4%
interest compounded annually.
Requirements of this program:

There is no input.

One run is sufficient.

Java-Jive

kweiser 10/03- 06/04


Page 92

Lab # 75:
An interesting problem in number theory is sometimes called the bracelet problem. This
problem begins with two single-digit numbers. The next number is obtained by adding the first
two numbers together and saving only the ones-digit. This process is repeated until the
necklace closes by returning to the original two numbers. For example, if the starting numbers
are 1 and 8, 12 steps are required to close the bracelet.
Sample Run:
BRACELET PROBLEM
Enter a 1-digit number: 1
Enter a 1-digit number: 8
1 8 9 7 6 3 9 2 1 3 4 7 1 8
It took 12 steps to close the bracelet.

Requirements of this program:

The program output should look similar to the run above.

Three different runs are required

Lab # 76:
Add error traps to lab 75.

Lab # 77:
Write a "smart" program that plays a guessing game where the computer tries to guess a
number picked by the user. The program asks the user to think of a secret number and then
asks the user a sequence of guesses. After each guess, the user must report whether it is too
high, too low or correct. The program should count the guesses. (HINT: Have the computer
maintain highestPossible and lowestPossible variables, and always have the computer
guess half way between the two.)
Sample Run:
Think of a number between 1 and 100.
Is
Is
Is
Is

the
the
the
the

number
number
number
number

50
25
13
19

(Correct,
(Correct,
(Correct,
(Correct,

Low,
Low,
Low,
Low,

High)?
High)?
High)?
High)?

H
H
L
C

It took me 4 guesses to find 19.

Requirements of this program:

The program output should look similar to the run above.

Three different runs are required

Java-Jive

kweiser 10/03- 06/04


Page 93

Lab # 78:
Add an error trap to lab 77.

Lab # 79:
The integer 36 has a peculiar property--it is a perfect square, and is also the sum of the integers
from 1 through 8. The next such number is 1225, which is 352, as well as the sum of 1 through
49. Find the next number that is a perfect square and is also the sum of the series 1..n.
Requirements of this program:

There is no input.

One run is sufficient.

Java Vocabulary:
1.

while loop

2.

count-controlled loop

3.

event-controlled loop

4.

sentinel

5.

error trap

6.

robust

More Review Questions:


Trace:
5.

6.

int count = 3, num = 3;

int count = 10, num = 5;

while (count < 5)


{
count++;
num+=count;
[Link](num);
}

while (count < 20)


{
count++;
num+=count;
[Link](count +
" " + num);
}

[Link](Done!);
[Link]("No more!");

Java-Jive

kweiser 10/03- 06/04


Page 94

7.

8.

int count = 0, num = 20;

int count = 0, num = 20;

while (num < 70)


{
if (count%2==0)
{
num+=10;
}

while (count < 6)


{
if (count%2==0)
{
[Link] (num);
num+=10;
}
count++;
}

count++;
}
[Link]("count = " +
count);
[Link]("\nnum= " +
num);

Write a program:
9. Write a program that asks the user for a score (0 to 100 points) and reports his/her
grade. The scale should be: 90-100 = A; 80-89 = B; 70-79 = C; 60-69 = D; 59-below =
F. The program should end when the user enters a (-1). Assume that the user will not
enter an incorrect value. The output should look like:
Enter your
Your
Enter your
Your
Enter your
Your
Enter your

score: 72
grade = C
score: 92
grade = A
score: 65
grade = D
score: -1

10. Write a program that asks the user to enter a number divisible by three. If the user
enters an incorrect value, print an error message and ask again. Continue asking for a
correct value until the user enters a value divisible by 3. Then print out a statement
letting the user know what correct value s/he entered.
Enter a number divisible by 3:

That is an error.
Enter a number divisible by 3:

10

That is an error.
Enter a number divisible by 3:

-2

That is an error.
Enter a number divisible by 3:

24

The number you entered is 24.

Java-Jive

kweiser 10/03- 06/04


Page 95

Common questions

Powered by AI

Robust error handling in Java user input can be achieved by using error traps. For example, input constraints can repetitively prompt the user if invalid data is entered. A common scenario is when a user is required to enter their birth month; the program checks if the entered value is between 1 and 12. If not, it displays an error message and prompts again . Similarly, error trapping ensures that numerical inputs like test scores fall within a valid range, such as between 0 and 100, and continues to prompt until valid input is received .

The 'bracelet problem' involves generating a sequence of numbers where each subsequent number is the sum of the previous two numbers, and only the units digit is retained. This problem naturally introduces concepts of recursion and modular arithmetic, as it requires the computation of sums and wrapping around using digits. Teaching this through a 'bracelet' visually aids in understanding recurrence relations and highlights the cyclical nature of sequences, making it a practical exercise in recursive problem-solving .

To calculate the doubling time of a CD with annual compounding interest, you can use a loop to repeatedly apply interest until the value of the investment doubles. For example, starting with an initial amount of $2500 at an interest rate of 4%, you keep a balance variable initialized at $2500 and increment it each year by 4% until it reaches $5000, counting the years as the loop control variable .

Using loops to sum series of numbers in programming illustrates the concept of iteration, a foundational programming construct. This demonstrates how to transition from mathematical formulas, such as the sum of integers formula n(n+1)/2, to iterative computation in code using constructs like for or while loops. This transition helps programmers understand loop initialization, condition evaluation, and loop body execution, critical for implementing more complex algorithms and managing program control flow .

The strategy involves maintaining two variables, highestPossible and lowestPossible, to represent the range within which the secret number lies. The computer guesses the midpoint of this range. Depending on the user’s feedback (too high, too low, correct), it adjusts the range accordingly. If the guess is too high, it sets highestPossible to one less than the guess. If the guess is too low, it sets lowestPossible to one more than the guess. This binary-search-like strategy efficiently narrows down the possible numbers .

To convert a for loop to a while loop for summing integers from 1 to 100, you need to initialize the sum and counter variables, then use a while loop with a condition to iterate while the counter is less than or equal to 100, and finally, increment the counter within the loop. Here's a simple implementation: ```java int sum = 0; int i = 1; while (i <= 100) { sum += i; i++; } ``` .

To handle user input errors for grades entered as letters, employ error checking loops that prompt the user again if an invalid grade is entered. Valid grades are typically 'A', 'B', 'C', 'D', 'F', and possibly 'Z' to stop. If a user enters any other letter, the program outputs an error message and requests re-entry. This loop continues until valid input is received, ensuring data integrity .

A sentinel value acts as a signal to terminate a loop. In user input loops, it indicates that no more data will be entered. For example, a loop might prompt users to enter test scores and use -1 as a sentinel; the loop continues reading and processing scores until the user inputs -1 . This allows for flexible input length without needing to specify how many entries will be provided in advance.

Proper input validation prevents errors caused by incorrect or unexpected user input, leading to more robust programs. For numerical calculations, input validation ensures that operations use meaningful and acceptable data, avoiding computational errors or crashes. For example, in programs calculating averages or sums, validating input ensures all numerical data contributes correctly to results, and prevents negative or excessively large values that may skew computations .

A count-controlled loop is a loop where the number of repetitions is predetermined, usually by a counter variable. For example, a for loop is typically a count-controlled loop . An event-controlled loop, on the other hand, continues to execute until a specific condition or event occurs. This type of loop does not have a predetermined number of iterations and stops when an event like user input or a specific condition is met .

You might also like