4. Iteration

/* 
Writer: SP
Date: March 24th
References: knowt & Fiveable
Unit 4: Iteration */

Intro to Iteration

  • A more efficient way would be to use a conditional statement that is referred to as a loop.

  • Note: On the AP Exam you will be expected to know what while and for loops are.

While Loop

while (condition) {
  do this while the condition is true
}
do this when the condition is no longer true
  • This loop cycles through again and again, while the condition is considered true.

  • If the condition is false then the loop will continue to run, until the condition returns true.

    • However, if the condition is true then it will execute the statement, and it will exit the loop, and if there is another condition present then that will start running instead.

  • However, sometimes loops aren’t well written, because sometimes there might not be any sort of statements that go through the loop to help change the value of the expression to be true.

    • This would be considered an infinite loop, which, as its name suggests, means that the loop goes on forever.

  • It has the similar feeling of Youtube Shorts freezing on you when you're on your daily Shorts spiral.

  • Note: On the AP Exam, you need to be able to trace code in multiple-choice questions and detect infinite loops. In the free-response questions, you need to write code that is free of infinite loops.

  • If there are multiple conditions found in the loop when can use boolean operators to simplify it. (View Chapter 5 for a review of boolean operators)

Break: A code that exits out of the loop immediately no matter if the loop is still true.

while (true) {
  do something
  if (certain condition is met) {
    do something else
    break;
  }
  do something if condition not met
}
  • Above code used ‘break’ statement to exit the while loop when certain condition is met.

Continue: it jumps to the next iteration of the loop and doesn’t complete the current one.

public static int sampleSum() {
  int i = 0;
  int sum = 0;
  while (i <= 10) {
    if (i == 4) {
      continue;
    }
    sum += i;
  }
  return sum;
}
  • Above code’s while loop should work until ‘i’ reaches 10, however, it will return ‘sum’ before it reaches 10 because it used ‘continue’ statement to end the loop when ‘i’ is equal to 4.

Try-Catch Statements & Exception Handling

  • When we give an invalid input to our loop, it will result InputMismatchException.

    • We can above this exception by using 'Try-Catch statements’

      • If there are errors in the loop and if we don’t use Try-Catch Statements, it will crash.

  • There are two main ways to handle the exception.

    • Throw the exception.

    • Catch the exception, and handle.

      • It uses ‘try’ block to assume the the program doesn’t have exceptions, and if it finds exception, it forces move to the catch block.

      • We put “Finally Block” that runs afterwards regardless of that is in the statement, and exceptions occurred or not.

public static int exceptionThrower(Parameter) throws 

Example Algorithms using while loop and exception handling.

  • Computing a Sum frim inputs

import java.util.Scanner;

public static int determineFrequencyOfEvens() {
  Scanner input = new Scanner(System.in); // Get User input
  int number; 
  int sum = 0;
  System.out.println("Enter a sequence of integers line by line. Enter 000 to end");
  try { // Assume it doesn't have error
    number = input.nextInt(); // Get input
    while (number != 000) {
      sum += number;
      number = input.nextInt();
    }
  } catch (Exception e) { // If there is an exception. 
    System.out.println("Invalid input. Terminating input sequence");
  } finally { // getting a correct inputs. 
    return sum;
  }
}

The for Statement

  • This is just another type of loop and is just as effective as a while loop. The only difference is that one of the loops may make the code more simplified than the other.

  • Since this loop needs more components, it can help to avoid an infinite loop in some situations.

  • Here are some steps for how a for loop executes:

    • The initializer will start first and it will start the loop off.

    • The conditions will be checked to see if they are true or false.

    • The statements will execute.

    • The incrementer will increment the number, and in turn will change it.

    • The process above starting from step 2 will continue to repeat until the value turns to false.

    • Once the value turns false the loop ends.

    • Ex:

for(int num = 1; num <= 22; num++)

  System.out.println(num);

//Explanation: The loop above will show every number and the output on the screen on separate lines.

// Above code is equivalent with below code. 
int num = 1;
while (num <= 22) {
   System.out.println(num);
   num++;
}
  • Ex:

for( int num = 1; num <= 3; num++)

   System.out.println(num);

System.out.println(“Done”);
//Explanation: The example above shows that num starts at the value of 1, and as long as the number is less than or equal to 3 the for loop will continue to execute. When the for loop executes it prints the value of num. Each time you go through the loop, the value of num increases by 1. Once the value of num hits 4, it will exit the for loop, and print done instead.
  • Note: On the AP Exam some of the multiple choice questions will show you multiple loop structures and formats, and ask you to pick which ones run the most efficiently, and which one produces the right output. The free-response questions will ask you to write a loop.

  • Note: Make sure to use your best judgment when writing your code for loops, because one loop may run more efficiently than others, and run on less code. Which means less work for us :)

  • Differences between the 2:

    • While loops perform the blocked statement, or statements once, and then it will evaluate the condition to determine if the loop should continue executing.

    • For loops evaluate the condition first, and then it performs the blocked statements if the initial condition is determined to be true.

  • What to Expect on the AP Exam:

Concepts covered on the AP CSA Exam

Primitives

int, double, boolean

Increment/Decrement Operators

x++,x--

Logical Operators

==,!=,<,>,<=,>=,&&,||,!

Conditional Statements

*if/else,****for,***while

Nested Loop:

  • Loop inside of loop.

  • Example:

// This is an algorithm to print triangle. 

public static void printPyramid(int n) {
  for (int i = 0; i < n; i++) {
      for (int j = i; j < n; j++) {