Loops and Iteration

  • way to simplify code that would be repeated multiple times
  • examples : while loop, for loop, recursion loop, nested iteration
  • while loop : sequence of code that runs while a condition is met
  • for loop : loops for each time the condition is met
  • nested iteration : technique to simplify the code
    • basically loop inside of a loop

New Vocab

For loop

  • for loops allow us to repeat code a fixed number of times Ex: for (int i = 0; i < COUNT; i++) { blah }
  • The first part initializes the loop variable, the second part tests some condition and the third part increments or decrements the loop variable. Each part of the for loop is separated by a semicolon (;)

Enhanced for loop

  • The enhanced for loop repeatedly executes a block of statements by iterating over a array or collection elements. Ex: for (T item : elements_of_type_T)
      {
          //custom code
      }

While loop vs Do while While

  • As long as the boolean expression remains true, code within the while loop will be executed
  • The moment that the boolean expression becomes false, code outside of the while loop will be executed; the loop is done.
  • You must exercise caution when using while loops to avoid the dreaded infinite loop Ex: while(boolean expression) { // code block inside of while loop to execute if the boolean expression is true } Do while
  • do-while loop executes all of the phrases inside the loop precisely once before assessing the loop’s requirement, and it runs at least once irrespective of whether the situation is fulfilled
  • do at start and while condition at end

Nested Loops

  • A nested iteration statement is an iteration statement that appears in the body of another iteration statement. Ex: for (int row = 1; row < 6; row++) { // Original loop inside for(int count = 1; count < 6; count++) {
      System.out.print(count * row + " " );
    
    }

for loop tangible

for(int i = 0; i < 10; i++)
        {
            System.out.println(i);
        }
0
1
2
3
4
5
6
7
8
9

while loop tangible

int i = 5;
System.out.println("Initiating countdown:");
while(i >= 0) {
  System.out.println(i + "...");
  i--;
}
Initiating countdown:
5...
4...
3...
2...
1...
0...

do while loop tangible

boolean bool = false;

do {
    System.out.println("x is 1");
  } while (bool);
x is 1

nested loop tangible

for (int row = 1; row < 6; row++) {
    // Original loop inside
    for(int count = 1; count < 6; count++) {
        System.out.print(count * row + " " );
    }
    System.out.println();
}
1 2 3 4 5 
2 4 6 8 10 
3 6 9 12 15 
4 8 12 16 20 
5 10 15 20 25 
public class LoopConversion 
{
    public static void main(String[] args) 
    {
        int count = 0;
        //convert to for loop
        while (count < 5) //while loop example
        {
            System.out.println("count is " + count);
            count++;
        }
    }
}
public class LoopConversion 
{
    public static void main(String[] args) 
    {
        int count = 0;
        //convert to for loop
        for (int x =0 ; x<5; x++)
        {
            System.out.println("count is " + count);
            count++;
        }
    }
}
import java.util.Scanner;
 
public class GFG {
    public static void
    guessingNumberGame()
    {
        // Scanner Class
        Scanner sc = new Scanner(System.in);
 
        // Generate the numbers
        int number = 1 + (int)(100 * Math.random());
        int guessNumber = 5;
 
        int i, guess;
 
        System.out.println(
            "A number is chosen between 1 and 100 --> try to guess the number with 5 tries!");

        
        for (i = 0; i < guessNumber; i++) {
            System.out.println("Guess the number:");
            guess = sc.nextInt();  // user input
            if (number == guess) {
                System.out.println("Congratulations! You guessed the number!");
                break;
            }
            else if (number > guess && i != guessNumber - 1) {
                System.out.println("The number is greater than " + guess);
            }
            else if (number < guess && i != guessNumber - 1) {
                System.out.println("The number is less than " + guess);
            }
        }
 
        if (i == guessNumber) {
            System.out.println("You have used all " + guessNumber + " tries.");
 
            System.out.println("The number was " + number);
        }
    }

    public static void main(String arg[])
    {
 
        guessingNumberGame(); //starting the game
    }
}
GFG.main(null);