Iteration Lesson
Iteration
Importance
- 25% of the AP test
- to simplify code that would otherwise be repeated
Operators
- ++ - increment by 1
- -- - decrement by 1
While loop
- while a specific condition is executed the condition will run
For loop
- for each thing in a sequence it will loop
- will run for each thing that is true
Recursion Loop
- Put your function inside its own functions
Nested Iteration
- technique that coders use
- any of the three loops can be used
- put a loop inside a loop
import java.util.Scanner;
public class Checker
{
public static void main(String[] args)
{
int number;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get a number from the user.
System.out.print("Enter a number in the range of 1 through 100: ");
number = keyboard.nextInt();
while (number > 100 || number < 1)
{
System
.out.print("Invalid input. Enter a number in the range " +
"of 1 through 100: ");
number = keyboard.nextInt();
}
}
}
Checker.main(null)
public class LoopConversion
{
public static void main(String[] args)
{
int count = 0;
//convert to for loop
for (count=0; count < 5;)
{
System.out.println("count is " + count);
count++;
}
}
}
LoopConversion.main(null);
public class ForLoop
{
public static void main(String[] args)
{
int i = 0;
//convert to for loop
for (i=0; i < 5;)
{
System.out.println("i is " + i);
i++;
}
}
}
ForLoop.main(null);
public class WhileLoop
{
public static void main(String[] args)
{
int i = 0;
//convert to for loop
while (i < 5)
{
System.out.println("i is " + i);
i++;
}
}
}
WhileLoop.main(null);
import java.util.Scanner;
public class Numberguesser {
public static void
guessnumber()
{
Scanner scanner = new Scanner(System.in);
int number = 1 + (int)(100* Math.random());
int i, guess;
System.out.println(
"A number is chosen between 1 to 100."
+ "Guess the number"
+ " within 5 trials.");
for (i = 0; i < 5; i++) {
System.out.println(
"Guess a number:");
guess = scanner.nextInt();
if (number == guess) {
System.out.println("You guessed the number.");
break;
}
else if (number > guess&& i != 5 - 1) {
System.out.println("The number is greater than " + guess);
}
else if (number < guess && i != 5 - 1) {
System.out.println("The number is less than " + guess);
}
}
if (i == 5) {
System.out.println(
"You have used all 5 trials.");
System.out.println(
"The number was " + number);
}
}
// Driver Code
public static void
main(String arg[])
{
// Function Call
guessnumber();
}
}
Numberguesser.main(null);