Skip to content

Instantly share code, notes, and snippets.

@btforsythe
Last active January 12, 2019 18:58
Show Gist options
  • Save btforsythe/1c39a48a17c500e9fac8a69d9bee6632 to your computer and use it in GitHub Desktop.
Save btforsythe/1c39a48a17c500e9fac8a69d9bee6632 to your computer and use it in GitHub Desktop.
Java lesson plan for interview: for loops

Topics

Loops

  • What is a loop?
  • When would you use a loop?
  • Why would you use a loop?

For Loops

  • When to use a for loop
    • Counting
    • Iterating through an array/collection
  • Syntax (parts of a for loop)
    • keyword: for
    • initialization expression
    • termination expression
    • increment expression

Enhanced For Loop

  • When to use an enhanced for loop
    • Iterating through a collection
  • Syntax (parts of an enhanced for loop)
    • keyword: for

Do While Loop

  • When to use a do while loop
    • Want a chunk of code to run once regardless, but then run multiple times after if a condition is met
  • Syntax
  • Parts of a do while
    • keywords: do, while

While Loop

  • When to use a while loop
    • Want a chunk of code to run only if a condition is met first
  • Syntax
  • Parts of a while loop
    • keyword: while

Goals

  • Examine loop programming constructs.
  • Work with for loops.
  • Work with enhanced for loops.
  • Explore different loop definitions and constructions.
  • Understand some key usages of loops.
  • Understand how to use multiple loops placed inside each other (nested loops).

Loops - Say It

  • A loop is something that repeats.
    • Examples:
      • Sunrise/Sunset
      • A daily routine: drink coffee, walk the dog, breakfast, shower, drive to work, work, drive home, walk the dog, watch TV, eat dinner, watch more TV, go to bed. Repeat daily.
    • In programming, a loop is a basic construct that allows repeated execution of a fragment of source code. This means a loop allows for a chunk of code to be repeated.
  • Sometimes loops may exist within other loops. In programming, we refer to a loop within a loop as a nested loop.
    • For example: When looking at a clock, you can see how the hour hand increments around the clock, and within that is another loop for the minutes hand, and within that is a loop for the seconds.
  • In Java, there are four different types of loops we will be covering:
    • for
    • enhanced for (aka for each)
    • while
    • do while

For Loop

Say It

  • The for loop can be used for both counting and iterating through arrays and collections.
  • By using a loop, you can now print all elements of an array at once versus having to print each element one at a time.

Show It

  • Let's first try using a for loop to count from 1 to 10.

     for(int i = 1; i <= 10; i++)
     {
     	System.out.println(i);
     }
  • Let's look at this closer:

    • First we start with the keyword for followed by a set of parentheses
    • Inside the parentheses there are 3 main parts happening
      • First we have int i = 1 which is what we call the initializer. This means where are we starting the loop? In this case we want to start counting at 1, so we've created a counter variable (i) and set it at a value of 1 to start.
      • If we wanted to count from 5 to 10, we would start with int i = 5
      • The second part is the condition. Think of this condition as what controls how long this loop will continue. This condition is also extremely important because it's how we can prevent an infinite loop from occurring. Infinite loops are bad. In this case we are preventing an infinite loop by telling the program we want to continue the loop, but we must stop looping when we hit 10.
      • This is why we have a condition of i <= 10
      • The last part is what we refer to as the updater. The updater is what tells the loop how to count. Since ++ is the increment operator that adds 1, i++ means add 1 to i after each iteration.
      • For example, when the loop first begins, we set our counter variable i to start counting at 1. i++ updates our counter variable so the next time the i will be equal to 2. Then i++ happens again and now i is equal to 3, and this will continue until i is equal to 10.
    • Next, we have a set of curly braces which is the body of our For Loop
    • Whatever we put inside the body will be the code that repeatedly executes until the loop stops.
  • Now, let's create a new loop where we need to count from 50 to 100. (Have the class lead you.)

     for(int counter = 50; counter <= 100; counter++)
     {
     	System.out.println(counter);
     }
  • Now, let's use a for loop to print the elements of an array.

    • Let's start by creating a String called greeting.

       String greeting = "My name is Little Bill";
  • Next, let's use the split method on the string to create an array of the words.

    • When using the split method without passing anything into the method parameters, it will automatically split a string at the spaces:

       String greeting = "My name is Little Bill";
       String[] words = greeting.split(" ");
  • Now, we can use a for loop to iterate through the array and print each element as we iterate through them.

     for(int i = 0; i < words.length; i++)
     {
     	System.out.println(words[i]);
     }
  • Use this image to explain: {TODO need Java image -- this one is CSharp} EXAMPLE

Do It

  • Create an array called days with the elements Monday, Tuesday, and Wednesday. Using a for loop, print the elements of the days array.
  • Start with the string "Once upon a time" and create an array called storyWords using the split method. Reverse the order of the elements in the array and using a for loop, print each word.

Enhanced For Loop

Say It

  • Enhanced for loops are used to iterate over a collection, often an array or list, just as we can use the for loop
  • You can think of the structure of the enhanced for loop as the statement: For each item in the collection, do something.

Show It

  • The structure of the enhanced for loop is like so (write diagram on whiteboard)

     for (type variable: collection)
     { 
     	//loop body 
     }
  • Let's start by creating an array called months.

     String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  • When setting up our enhanced for loop, there are a few parts we need to point out.

    • Enhanced for loops always start with the enhanced for keyword, followed by a set of parentheses.
    • Inside the parentheses for the enhanced for loop we start by creating a reference for how we will call each individual element. This starts with the data type of the elements and followed by a name you would like to reference the elements by.
    • Next we use the in keyword and then the name of the collection we are iterating over. In this case, the collection will be an array.
  • Now, let's setup our enhanced for loop to print out each element of our months array

     for(String month: months)
     {
     	System.out.println(month);
     }
  • Now, let's try another example. Create an array of musicians. Using an enhanced for loop, print each musician's name.

     String[] musicians = {"U2", "Maroon 5", "Beyonce", "Ed Sheeran", "Nas"};
    
     for(String name: musicians)
     {
     	System.out.println(name);
     }

Do It

  • Write a program that takes your favorite foods and prints them out one at a time. (Use an enhanced for loop.)
  • Create an array of lucky numbers. Using an enhanced for loop, print the following:
    • If the array holds the numbers 3, 5, 7, 11, 15, then the printed result should say
       Your Lucky Number is: 3
       Your Lucky Number is: 5
       Your Lucky Number is: 7
       Your Lucky Number is: 11
       Your Lucky Number is: 15
      
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment