Week 8 - Loops
Repeating Functionality (LOOPS)¶
Learning Objectives¶
- Loop Familiarity and Creation: You possess a solid understanding of loops and can proficiently construct programs that incorporate them.
- Effective Loop Termination: You can skillfully employ the “break” command to gracefully halt the execution of a loop when a certain condition is met.
- Loop Control with “continue”: You have the ability to employ the “continue” command to efficiently return to the beginning of a loop and manage the flow of program execution.
- User Input Handling: You are proficient in developing programs that solicit and process user inputs until a specific predefined input (e.g., “0” or “end”) is provided, after which the program responds appropriately with information about the collected inputs.
- While Loop Proficiency: You have a strong grasp of the condition used in a while loop and can effectively work with it in your programs.
- Competence in For Loops: You are proficient in utilizing for loops to control program flow and iteration.
- Loop Selection Aptitude: You can discern between situations that warrant the use of a while loop and those where a for loop is a more suitable choice, demonstrating a keen understanding of loop selection based on the specific task or problem at hand.
Why We Use Loops¶
- Increases flexibility in code (looping mechanisms can be variable)
- Eliminates repetition in code (no typing the same commands over and over)
Consider this code
Read in 5 numbers, sum them, and print the output | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Now consider this alternative
Read in 5 numbers, sum them, and print the output | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
What is a Loop and Loop Control¶
Info
Loops are grouped statements that are repeated until a control expression determines whether or not the loop should stop.
While Loop¶
Form¶
1 2 3 |
|
Loop Control¶
- A while loop will continue executing as long as the boolean expression is true.
- It’s easy to create an infinite loop by makeing the boolean expression always true.
1 2 3
while ( true ) { // This will never stop. }
- To stop a while loop, we must either make the boolean expression false, or add another conditional to break from the loop.
1 2 3 4 5 6 7 8 9 10 11 12
int number = 1; while (true) { System.out.println(number); if (number >= 5) { break; } number++; } System.out.println("Ready!");
Question
Why do we declare the int number = 1
outside the while loop?
Answer
If we didn’t, the local variable number would get redefined on each loop iteration causing it to never increment to 5. Thus, causing an infinite loop.
- Let’s look at another way to stop a loop, via user-input:
1 2 3 4 5 6 7 8 9 10 11 12 13
Scanner scanner = new Scanner(System.in); while (true) { System.out.println("Exit? (y or Y exits)"); String input = scanner.nextLine(); if (input.toLowerCase().equals("y")) { break; } System.out.println("Ok! Let's carry on!"); } System.out.println("Left the loop!");
Excercise
Write a program by using the loop example that asks “Shall we carry on?” until the user inputs the string “no”.
Answer
1 2 3 4 5 6 7 8 9 10 11 |
|
- Other variables of types of User Input can be used to crontrol loops. Consider the following:
1 2 3 4 5 6 7 8 9 10 11 12 13
Scanner scanner = new Scanner(System.in); while (true) { System.out.println("Input a number, 0 to quit"); int command = Integer.valueOf(scanner.nextLine()); if (command == 0) { break; } System.out.println("You input " + command); } System.out.println("Done, thank you!");
- Here an integer input by the user is used.
How Does a Loop Start Over¶
- When the execution reaches the end of the loop, the execution starts again from the start of the loop.
- You can also return to the beginning from other places besides the end with the command continue.
- When the computer encounters the continue command, it goes back to the start of the loop in the program.
Continue Example | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Excercise
Write a program, according to the preceding example, that asks the user to input values until they input the value 6.
Answer
1 2 3 4 5 6 7 8 9 10 11 |
|
Question
What is wrong with the above loop?
Answer
Its INFINITE! There is no break or boolean expression to exit this loop.
Excercise
What does the program below print?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Answer
5 plus a space so: “5 “
Excercise
Write a program that asks the user for numbers. If the number is negative (smaller than zero), the program prints for user “Unsuitable number” and asks the user for a new number. If the number is zero, the program exits the loop. If the number is positive, the program prints the number to the power of two.
Answer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
A Common Loop Mistake¶
- Declaring a variable inside the loop:
Program to print 1's input by user 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
Scanner scanner = new Scanner(System.in); // The task is to read an input from the user while (true) { // The task is to keep count of number ones int ones = 0; System.out.println("Input a number (0 exits): "); // The task is to read a user inputted number int number = Integer.valueOf(scanner.nextLine()); // The task is to exit the loop if the user // has inputted zero if (number == 0) { break; } // The task is to increase the amount of ones // if the user inputs a number one if (number == 1) { ones = ones + 1; } } // The task is to print out the total of ones // This doesn't work because the variable ones has been // introduced within the loop System.out.println("The total of ones: " + ones);
- The variable ones is introduced within the loop so its value is initialized on each iteration.
- An attempt is also made to use it after the loop at the end of the program, but by that time the variable is out of scope.
So what’s the fix? Some of you might consider putting the sout in the loop like so:
sout in the loop | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
- Though this works for the ones variable, we only want it to print once, and this prints on every iteration.
- The answer is to decalre the variable before the loop so that we don’t re-initialize it on each iteration and so we can use it outside the loop’s scope.
The Right Way | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
Exercise
Write a program that reads values from the user until they input a 0. After this, the program prints the total number of inputted values. The zero that’s used to exit the loop should not be included in the total number count.
Answer
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Rewrite My Loops¶
- So far we’ve exited our loops with a separate conditional and with break, but we can use the boolean expression instead.
- Consider the last example:
1 2 3 4 5 6 7 8 9 10 11 12
Scanner s = new Scanner(System.in); int input; int numInputs = 0; while(true) { System.out.print("Give me numbers: (0 exits): "); input = Integer.parseInt(s.nextLine()); if(input == 0) { break; } numInputs++; } System.out.printf("Read %d inputs!", numInputs);
- This can be re-written like so:
1 2 3 4 5 6 7 8 9
Scanner s = new Scanner(System.in); int input; int numInputs = 0; System.out.print("Give me numbers: (0 exits): "); while((input = Integer.parseInt(s.nextLine())) != 0 ) {; numInputs++; System.out.print("Give me numbers: (0 exits): "); } System.out.printf("Read %d inputs!", numInputs);
- Consider the last example:
For Loops¶
-
Consider the following while loop:
1 2 3 4 5
int i = 0; while (i < 10) { System.out.println(i); i++; }
-
While this works, its fairly verbose.
- Let’s introduce a different style of loop to reduce our complexity.
1 2 3
for (int i = 0; i < 10; i++) { System.out.println(i); }
Form and Parts of the For Loop¶
1 2 3 |
|
- Introduce Variables
- Loop Condition
- Increase, Decrease, or Change loop counter values
- Body of the loop
Let’s talk about loop execution…
Question
What would the following program print?
1 2 3 4 5 |
|
Answer
1 2 3 4 |
|
Excercise
Write a program that reads an integer from the user. Next, the program prints numbers from 0 to the number given by the user with a for loop. You can assume that the user always gives a positive number.
Answer
1 2 3 4 5 6 |
|
Loop Control¶
break
andcontinue
work the same way in a for loop as they do in a while loop!!!