Welcome to Lesson 11!By the end of today's class, you should know...
1. Lesson 10 Practice Exam Questions
int count = 1; while (count <= 10) { System.out.println(count); count++; }
int count = _________; while (___________________________) { count++; System.out.println(count); }
Loop 1: String repeat = "y"; while (repeat.equals("y")) { System.out.println("Playing an exciting game!\n"); System.out.println("Want to play again? (y/n): "); Loop 2: int counter = 1; while (counter <= 10) { System.out.println(counter); } 2. Counting Loops
For Statements
Another For Loop Examplepublic static void main(String[] args){
int max = 0; Scanner input = new Scanner(System.in); System.out.println("This program uses a loop to count!"); System.out.print("Enter the maximum number: "); max = input.nextInt(); for (int i = 1; i <= max; i++) { System.out.println(i); } input.close(); }
Anatomy of the For Loop
for loop is reached, execute the initialize statement (starting point).
condition is true.
update statement.
Diagram of
|
|
int number = 0; Scanner input = new Scanner(System.in); System.out.print("Enter a number and I will show its" + " bar graph.\nEnter your number: "); number = input.nextInt(); System.out.println("\nBar graph:"); for (int i = 0; i < number; i++) { System.out.print('*'); } System.out.println(); input.close(); |
Summing Numbers
- One common looping task is to input a list of numbers and calculate their sum
- For example, if we want to add the sum of the first four integers:
sum = 1 + 2 + 3 + 4 = 10
- As another example, we can add a list of 5 numbers:
sum = 1 + 2 + 3 + 4 + 5 = 15
- We can generalize our examples to sum from 0 to any number n.
Example Application to Sum a Sequence of Numbers
public static void main(String[] args) {int number = 0;
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter the number to sum to: ");
number = input.nextInt();
for (int i = 1; i <= number; i++) {
sum = sum + i; //using the counter as a value to add to the sum
}
System.out.println("The sum is: " + sum);
input.close();
}
Activity 11.2: Tracing a Loop (10 pts)
- In this exercise, we will trace the execution of the following for loop.
- DO NOT run the below code. Instead, can you figure out what this code would print to the console if you were to run it?
for (int i = 10; i <= 15; i++){if (i == 11 || i == 13 || i== 15)System.out.print("*");elseSystem.out.print("!");}
- Locate the assignment on Canvas and click submit so that you can see the textbox.
- In the text box, type what the output of the above for loop would be to the console (trace it through by hand!).
- In other words, what sequence of characters will be printed to the console?
- Note, you should do this without running the code.
- Then, change the statement i <=15 to be i < 15.
- Type the output of the for loop with this alteration.
- How is it different?
- The instructor will be going over the examples so you can verify your answers and understanding.
- Don't forget to submit your work!
4. More Loopy Errors
- A common problem with counting loops is the off-by-one error
- Finding the correct upper and lower bounds can be confusing
- Should you start at 0 or 1?
- Are you counting up to a number (<), or up to and including a number (<=)?
- To understand the counting loop you need to count iterations.
- For instance, the following loop executes b - a times:
for (int i = a; i < b; i++)
- However, the following loop is executed b - a + 1 times:
for (int i = a; i <= b; i++)
- The "+1" is the source of many errors
- For example, to sum the numbers from 1 to 5, what is wrong with the following:
public static void main(String[] arg){
int sum = 0;
for (int count = 0; count < 5; count++)
{
sum += count;
}
System.out.println(sum);
}
- One way to visualize the "+1" error is by looking at a fence

- How many posts do you need for a fence with three sections?
- It is easy to be "off-by-one" with problems like this
- Forgetting to count the last value is sometimes called a fence-post error
Debugging Technique: Tracing Variables
- One good way to discover loopy errors is to display the variables that are part of the loop
- Tracing variables means watching their values change as the program executes
- You can insert temporary output statements in your program to watch the variables, like:
System.out.println("count= " + count + ", sum=" + sum);
4. More Loopy Errors
- A common problem with counting loops is the off-by-one error
- Finding the correct upper and lower bounds can be confusing
- Should you start at 0 or 1?
- Are you counting up to a number (<), or up to and including a number (<=)?
- To understand the counting loop you need to count iterations.
- For instance, the following loop executes b - a times:
for (int i = a; i < b; i++)
- However, the following loop is executed b - a + 1 times:
for (int i = a; i <= b; i++)
- The "+1" is the source of many errors
- For example, to sum the numbers from 1 to 5, what is wrong with the following:
public static void main(String[] arg){ int sum = 0; for (int count = 0; count < 5; count++) { sum += count; } System.out.println(sum); }
- One way to visualize the "+1" error is by looking at a fence
- How many posts do you need for a fence with three sections?
- It is easy to be "off-by-one" with problems like this
- Forgetting to count the last value is sometimes called a fence-post error
Debugging Technique: Tracing Variables
- One good way to discover loopy errors is to display the variables that are part of the loop
- Tracing variables means watching their values change as the program executes
- You can insert temporary output statements in your program to watch the variables, like:
System.out.println("count= " + count + ", sum=" + sum);
Activity 11.3: Summing and Averaging (10 pts)
- Let's write a program that uses a for loop to sum a list of numbers and computer their average.
- Open up a new class named Sum.java and add it to your Activity11 folder.
- First, declare and initialize 3 variables at the top of main:
- Next, write a print statement to display a welcome message to the user:
Give me a list of numbers and I will compute their sum and average!
- We
will need to know the number of user inputs in advance so that we will
know the ending condition of our for loop (in other words, how many
numbers the user is planning to input).
- Prompt the user to enter the quantity of numbers and read in the value to a variable named quantity:
System.out.print("Enter the quantity of numbers: ");
quantity = input.nextInt();
- Next, we will write a for loop to read in that number of user inputs.
for (int i = 1; i <= quantity; i++) {
//body of loop goes here
}
- Inside the loop we ask for each value and add it to the sum
System.out.print("Enter value #" + i + ": ");
number = input.nextDouble();
sum = sum + number; //add number to our running total for the sum
- The for loop will take care of adding up all of the numbers and storing the result in the sum variable.
- Finally, below the for loop, we can print out the sum, and also compute the average.
- Add a print statement to print the sum. Note that we will print both sum and average out to two decimal places.
System.out.printf("The sum of the numbers is: %.2f\n", sum);
- Then, add a second print statement to print out the average.
- Recall that the formula for calculating the average is:
- Therefore, we can computer the average by dividing sum by quantity.
System.out.printf("The average of the numbers is: %.2f\n", (sum / quantity));
- When your program is correctly displaying the sum and average as in the example output below, submit your work to Canvas.
Example Output
Your Program Should Look Identical to the Following:
Activity 11.4: Unicode (10 pts)
- In this exercise we continue exploring some uses of counter-controlled loops.
Background
- Recall that a
char
data type is stored by the computer as a number using Unicode (Unicode Table). Since a char
is stored as an int
by the computer, Java lets you cast an int
to a char
.
int count = 65;
System.out.println((char) count); //What does the (char) do?
- This casting feature lets us construct our own Unicode table.
Specifications
- Copy and paste the starter code into a file called Unicode.java
public static void main(String[] args) {
//displaying the characters from 33 to 122
for (int i = ???; i <=???; i++) {
System.out.println(i);
}
}
- Alter the
for
-loop so that it counts from 33 to 122
- Inside the for-loop, alter the System.out.println statement as follows:
- Compile and run your modified program and make sure your output looks like:
(some output not shown)
65 A
66 B
67 C
(more output not shown)
- When you are finished, play around with the starting and ending values of your for loop.
- What other characters will display?
- Submit the final version of your file to Canvas when you are finished.
Activity 11.3: Summing and Averaging (10 pts)
- Let's write a program that uses a for loop to sum a list of numbers and computer their average.
- Open up a new class named Sum.java and add it to your Activity11 folder.
- First, declare and initialize 3 variables at the top of main:
- Next, write a print statement to display a welcome message to the user:
Give me a list of numbers and I will compute their sum and average!
- We will need to know the number of user inputs in advance so that we will know the ending condition of our for loop (in other words, how many numbers the user is planning to input).
- Prompt the user to enter the quantity of numbers and read in the value to a variable named quantity:
System.out.print("Enter the quantity of numbers: "); quantity = input.nextInt();
- Next, we will write a for loop to read in that number of user inputs.
for (int i = 1; i <= quantity; i++) {
//body of loop goes here
}
- Inside the loop we ask for each value and add it to the sum
System.out.print("Enter value #" + i + ": "); number = input.nextDouble(); sum = sum + number; //add number to our running total for the sum
- The for loop will take care of adding up all of the numbers and storing the result in the sum variable.
- Finally, below the for loop, we can print out the sum, and also compute the average.
- Add a print statement to print the sum. Note that we will print both sum and average out to two decimal places.
System.out.printf("The sum of the numbers is: %.2f\n", sum);
- Then, add a second print statement to print out the average.
- Recall that the formula for calculating the average is:
- Therefore, we can computer the average by dividing sum by quantity.
System.out.printf("The average of the numbers is: %.2f\n", (sum / quantity));
- When your program is correctly displaying the sum and average as in the example output below, submit your work to Canvas.
Example Output
Your Program Should Look Identical to the Following:
Activity 11.4: Unicode (10 pts)
- In this exercise we continue exploring some uses of counter-controlled loops.
Background
- Recall that a
char
data type is stored by the computer as a number using Unicode (Unicode Table). Since achar
is stored as anint
by the computer, Java lets you cast anint
to achar
.
int count = 65;
System.out.println((char) count); //What does the (char) do?
- This casting feature lets us construct our own Unicode table.
Specifications
- Copy and paste the starter code into a file called Unicode.java
public static void main(String[] args) {
//displaying the characters from 33 to 122
for (int i = ???; i <=???; i++) {
System.out.println(i);
}
}
//displaying the characters from 33 to 122
for (int i = ???; i <=???; i++) {
System.out.println(i);
}
}
- Alter the
for
-loop so that it counts from 33 to 122 - Inside the for-loop, alter the System.out.println statement as follows:
- Compile and run your modified program and make sure your output looks like:
(some output not shown) 65 A 66 B 67 C (more output not shown)
- When you are finished, play around with the starting and ending values of your for loop.
- What other characters will display?
- Submit the final version of your file to Canvas when you are finished.
Wrap Up
- Rewrite the below while loop as the equivalent for loop:
int count = 0;
while (count < 10) {
System.out.println(count);
count++;
}
- Trace the output of the below loop:
for (int i = 0; i <= 5; i++) {
if( i % 2 == 0 || i % 3 == 0) {
if( i % 2 == 0 || i % 3 == 0) {
System.out.print("$");
} else {
System.out.print("!");
}
}
Upcoming Assignments
- Activities 11.1-11.4 due Tuesday at 11:59pm
- Assignment 11 due Friday at 11:59pm
- Quiz 6 due Friday at 11:59pm
~Have a Great Day!~