Young Coders: Week 2 Notes

Loops, Arrays, Methods, and Recursion

Loops
If statements are one way to control how your program flows. Loops are another way.
When you need the computer to execute code over and over, use loops! We looked at two types of loops. 
A while loop won’t stop until its condition(s) is false.









public class WhileLoop1{
   public static void main(String[] args) {
      int i = 1;
      while(i <= 10) {
        System.out.println(i); 
        i++;
      }
   }
}
The format of a while loop is pretty simple:
INITIALIZE COUNTER VARIABLE 
while(CONDITION) {
   CODE
    INCREMENT/DECREMENT COUNTER VARIABLE
}
While CONDITION is true, the CODE will run. The while loop in the example above checks if i <= 10 is true each time before it executes the code inside the loop. On Line 6, i++ increases i by 1. We could also write i = i + 1, or i is assigned to i + 1. Don't forget about i++ – then you'll be stuck with an infinite loop!
Here is another example of a while loop:
1
2
3
4
5
6
7
8
9
public class WhileLoop2{
   public static void main(String[] args) {
      int i = 20;
      while(i >= 1) {
        System.out.println(i); 
        i--;
      }
   }
}
This is almost the same as the first example, except i starts out at 20 and decreases to 1. On Line 6, i– decreases i by 1. Just like i++ above, we could also write i = i – 1, but i-- looks nicer. 
Here's a third and final example of a while loop.









public class WhileLoop3{
   public static void main(String[] args) {
      int i = 30;
      while(i <=90) {
        System.out.println(i); 
        i+=3;
      }
   }
}
We start at 30, and increment by 3's up to 90. i+=3 is shorthand for i = i + 3.
We then looked at for loops
Here's a typical for loop:







public class ForLoop{
  public static void main(String[] args) {
      for(int i = 0; i < 10; i++) {
        System.out.println(i);
      }
   }
}
The variable i starts at 0, then increments to 1, 2, 3…until it reaches 9, when the loop stops.
This is the general format of a for loop:
for(INITIALIZE COUNTER VARIABLE; CONDITION ; INCREMENT/DECREMENT) {
CODE
}
Here are the problems we solved in class:
1) Using a for loop, print out the multiples of 5 from 10 to 90.

2) Using a while loop, print out the odd numbers from 3 to 101.

3) Read in a String with a Scanner. Print out that String 50 times.

4) Read in 10 integers with a Scanner. Print out their sum.
To read in an integer with a Scanner:
• Instead of using nextLine(), use nextInt() to read in an integer with a Scanner.
• Or, use Integer.parseInt() 

Arrays
An array stores a list of things. 
public class ArrayExample {
  public static void main(String[] args) {
    int[] numbers = {2,4,-7,0,8};    
    for(int i = 0; i < numbers.length; i++) 
      System.out.println(numbers[i]); 
    String[] food = {"pineapple", "crocodile", "fish", "ants"};
    for(int i = 0; i < food.length; i++) 
      System.out.println(food[i]); 
  }
}

When referring to the elements of an array, we write array_name[index]. Notice the index starts at 0, not 1. To get the length of an array, use array_name.length. Here's one  more example with an array: 

import java.util.Scanner; 
public class MoreArrays {
  public static void main(String[] args) {
    Scanner s = new Scanner(System.in); 
    int[] numbers = new int[5]; 
    
    for(int i = 0; i < numbers.length; i++) 
      numbers[i] = s.nextInt(); 
    
    for(int i = 0; i < numbers.length; i++)
      System.out.println(numbers[i]); 
  }
}
Finally, we worked on these problems during class: 
Hint: Use loops!

1) Using a Scanner, read in 5 Strings into an array. Then, print out the contents of the array.

2) Using a Scanner, read in 5 numbers into an array. Then, print out the contents of the array multiplied by 2.

3) Using a Scanner, read in 10 integers into an array. Then, find the largest value in the array.

4) Using a Scanner, read in 10 integers into an array. Return the product of the smallest value and largest value.

5) Using a Scanner, read in 10 integers into an array. Print out “positive” if most of them are positive. Print out “negative” if most of them are negative. Print out “balanced” if five of them are positive and five of them are negative. (Assume none of the integers are zero.)

6) Read in 5 integers into an array using a Scanner. Print out the numbers shifted left by one.
For example,
{1,2,3,4,5} becomes {2,3,4,5,1} 


(Numbers 5 and 6 are part of this week's Candy Challenges.) 

Methods

Next, we learned about methods. A function in math is like a machine – you input something and the machine returns an output. A method is a function. Methods are great for organizing your program. An example of a (silly) method: 


public class MethodExample {
  public static int sum(int x, int y) {
    return x+y;  
  }
  
  public static void main(String[] args) {
    System.out.println(sum(Integer.parseInt(args[0]), Integer.parseInt(args[1]))); 
  }
}


Here are the methods' signatures, color coded:


public static int sum(int x, int y

public static void main(String[] args

public - method can be accessed from any class protected - method can be accessed only from subclasses private - method can be accessed only in that class

this is the type that the method returns

the name of the method

the parameter(s) or input 


Recursion

Our final topic was recursion. Recursion is when a method calls itself, a powerful concept. 

An example of a method using recursion: 


1
2
3
4
5
6
public static int factorial(int N) {
   if (N == 1)
     return 1;
   else
      return N * factorial(N-1);
}
Base Case – Lines 2, 3
Reduction Step – Lines 4, 5
Don’t forget either part!
On the whiteboards, we traced the method: 
We also created a method that returns the nth Fibonacci number (this is not the best way to calculate the Fibonacci numbers!). 


public class Fibonacci {
  public static int fib(int N) {
    if(N == 0)
      return 0;
    if(N == 1)
      return 1; 
    return fib(N-1) + fib(N-2); 
  }
  
  public static void main(String[] args) {
    System.out.println(fib(4)); 
  }
}

We also traced this on the whiteboards: 
Here are the problems that we ran out of time to solve:


1) Create a method called power that takes two parameters: base and exp. It returns the value of base to the exp power. For example:

power(2,3) = 8 
power(5,3) = 125 
power(4,0) = 1

2) Create a method called remove that takes one parameter: a String. It returns the same String, except all the ‘o’ or ‘O’ characters have been removed.
For example,

remove(“to be or not to be”) = “t be r nt t be”


3) Create a method called reflection. It has at least one parameter: an integer array. You decide if it should take any other parameters. The method should recursively check if the array contains two consecutive values such that one integer is the negative of the other. Return true or false (a boolean).
For example,

{1,4,-4,5,6,7,5} will return true because 4 and -4 are “reflections” of each other, and the two integers are right next to each other. 


Hope you all enjoyed today! Same time, same place next week: Sunday, 1-3 pm. We will cover classes and data structures. 

Popular posts from this blog

Building A Toy Language Interpreter in Go

Space Race: a simple Rust game built on the Bevy framework

Building a Toy Language Compiler in Go