UF 06: JAVA¶

Iteration (Loops)¶

Alta Formazione Professionale - ITT Marconi

February 2021

4.1 While Loops¶

only need it if:

  • number of iterations not known a priori
  • ... or must add / remove elements from sequence you are iterating

While loop - example¶

In [11]:
String s = "abracadabra";

int i = 0;                                         // PROGRESS VAR(s)
boolean found = false;

System.out.println("BEFORE");

while (i < s.length() && !found) {                 // BOOLEAN CONDITION ON PROGRESS VAR(s)
  
  System.out.println("Checking " + s.charAt(i));   // STATEMENTS
    
  if (s.charAt(i) == 'c'){            
      System.out.println("Found it!");      
      found = true;
  }
  
  i++;                                             // MUTATE PROGRESS VAR !
}

System.out.println("AFTER");
BEFORE
Checking a
Checking b
Checking r
Checking a
Checking c
Found it!
AFTER

1) Three Steps to Writing a Loop

2) Tracing Loops

3) Common Errors with Loops

4) Input-Controlled Loops


import java.util.Scanner;

Scanner in = new Scanner (System.in);
String statement = "";

while (!statement.equals("bye"))
{            
        System.out.println ("Tell me something..");
        System.out.print ("> ");
        statement = in.nextLine();
        System.out.println ("You told me: " + statement);
}
System.out.println("Goodbye!");
Tell me something..
> Ciao
You told me: Ciao
Tell me something..
> You are a parrot
You told me: You are a parrot
Tell me something..
>

Exercise: prepare sandwiches¶

We need to prepare sandwiches with cheese: we have a certain number of pieces of bread and cheese slices, not necessarily in the same quantity. We will couple bread and cheese until we run out of one type of ingredient. At the end we will say if there is any ingredient left (or no ingredient at all). Write a function prepare which takes two parameters and PRINTS the procedure.

public static void prepare(int bread, int cheese){
    throw new UnsupportedOperationException("TODO IMPLEMENT ME!");
}

Example

prepare(3,5);
Prepared a sandwich: 2 remaining pieces of bread, 4 remaining slices of cheese
Prepared a sandwich: 1 remaining pieces of bread, 3 remaining slices of cheese
Prepared a sandwich: 0 remaining pieces of bread, 2 remaining slices of cheese
Two slices of cheese are left.

Try also:

//prepare(5,3);
//prepare(4,4);

Follow up: In the main, add another while with a Scanner that keeps asking how much bread/cheese we have and then calls prepare.

Exercise - paperboard¶

✪ Print integer numbers from 0 to k INCLUDED using a while, and for each number prints to its side one among the strings "PA", "PER" and "BOARD" alternating them

Ex - for k=8 prints

0 PA
1 PER
2 BOARD
3 PA
4 PER
5 BOARD
6 PA
7 PER
8 BOARD

Exercise - converge¶

Given two numbers x and k, using a while modify and print x until it reaches k included. NOTE: k can either be greater or lesser than x, you must handle both cases

In [2]:
int x = 3, k = 5;

prints:

3
4
5

Other example:

In [3]:
int x = 6, k = 2;

prints:

6
5
4
3
2
In [4]:
int x = 3, k = 5;    // 3 4 5
int x = 6, k = 2;    // 6 5 4 3 2
int x = 4, k = 4     // 4

4.2 For Loops¶

Need it:

  • if number of iterations is known in advance
  • you don't want to add/remove elements from the sequence you are iterating!

If possible, prefer it to while

1) Three Parts of a For Loop

2) Decrementing Loops

3) Turtle Loops

4) Programming Challenge : Turtles Drawing Shapes

Exercise - sghiribizzo¶

Write some code which given the string s PRINTS all the possible combinations of row couples such that a row begins with the first characters of s and the successive continues with the following characters.

String s = "sghiribizzo";
s
 ghiribizzo
sg
  hiribizzo
sgh
   iribizzo
sghi
    ribizzo
sghir
     ibizzo
sghiri
      bizzo
sghirib
       izzo
sghiribi
        zzo
sghiribiz
         zo
sghiribizz
          o
sghiribizzo

Exercise - DNA¶

Given two DNA strings s1 and s2 of equal length, write some code which PRINTS among the first and second string another string made by spaces ` and pipe|` where equal characters are found.

HINT: instead of keeping building a string with + which is an expensive operation, consider using System.out.print() without the final ln

Example - given:

In [5]:
String s1 = "ATACATATAGGGCCAATTATTATAAGTCAC";
String s2 = "CGCCACTTAAGCGCCCTGTATTAAAGTCGC";

Prints:

ATACATATAGGGCCAATTATTATAAGTCAC
   ||  || |  |  |   |  ||||| |
CGCCACTTAAGCGCCCTGTATTAAAGTCGC

4.3. Loops and Strings¶

Remember StringBuilder:

In [6]:
StringBuilder sb = new StringBuilder();
sb.append("Building ");
sb.append("a string ");
sb.append("incrementally...");
String result = sb.toString(); // final conversion 
System.out.println(result);
Building a string incrementally...

1) While Find and Replace Loop

I don't like the book example. Try rewriting it with a StringBuilder

2) For Loops: Reverse String

I don't like the book example. Try rewriting it with a StringBuilder

3) Programming Challenge : String Replacement Cats and Dogs

I don't like the book example. Try rewriting it with a StringBuilder

4.4. Nested For Loops¶

nested-for

1) Nested Loops with Turtles

2) Programming Challenge : Turtle Snowflakes

Exercise - cover the plane¶

✪ Given the integers a and b, write some code which prints all the possible couples of numbers x and y such that $1 \leq x \leq a$ and $1 \leq y \leq b$

For example, given:

In [7]:
int a = 5, b = 3;

it must print:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
4 1
4 2
4 3
5 1
5 2
5 3

Exercise - triangular¶

✪ Given the integer a, write some code which prints all the possible couples of numbers x and y such that $0 \leq x \leq y < a$

For example, for

In [8]:
int a = 5;

it must print:

0 0
0 1
0 2
0 3
0 4
1 1
1 2
1 3
1 4
2 2
2 3
2 4
3 3
3 4
4 4

Exercise - FBI Crime unit¶

The FBI Crime unit is trying to infiltrate a powerful mob organization - so far, they managed to obtain the services of an informant who now and then gives precious tips. All the investigations are then recorded in classified documents, which need to be anonimized according the reader clearence level. In order to mark possibly sensitive information, the detective place symbols such as > and < to delimit pieces of text to anonimize.

Write some code which anonimizes the text, substituting words in sensitive sequences with the proper number of asterisks.

Example - given:

In [9]:
String text =   "Our > informant Mr Big Ears <, who's operating within > the Organization, < told us "
              + "about a possible encounter among suspects we're following. The > suspect Mr Wrong Do " 
              + "(also known as Mr Cut Throat) < was in fact seen last night near > Vice Palace < while "
              + "talking with > Mr So Bad <. They nervously glanced around, and > after a while, " 
              + "they quickly exchanged two suitcases. < The details of the deal are yet to be discovered.";

String punctuation = "().;,";

your code should print:

"Our  ********* ** *** **** , who's operating within  *** ************,  told 
us about a possible encounter among suspects we're following. The  ******* ** 
***** ** (**** ***** ** ** *** ******)  was in fact seen last night near  **** 
******  while talking with  ** ** *** . They nervously glanced around, and  
***** * *****, **** ******* ********* *** *********.  The details of the deal 
are yet to be discovered."

NOTE 1: Sometimes detectives place > < with punctuation around, your program should handle those cases as well, preserving punctuation in the output. I.e.

Our > informant Mr Big Ears <, who's

should become

Our  ********* ** *** **** , who's


NOTE 2: Your program should also preserve punctuation in anonimized words, i.e.

> suspect Mr Wrong Do (also known as Mr Cut Throat)

should become:

******* ** ***** ** (**** ***** ** ** *** ******)


IMPORTANT: HAVE YOU READ THE ABOVE NOTES?

Making a rough version of the program should be relatively straightforward, making the details also work may be more challenging

HINT: to build the output string incrementally, use a StringBuilder

4.5. Loop Analysis¶

1) Tracing Loops

2) Counting Loop Iterations

3) Programming Challenge : POGIL Analyzing Loops

5) Loop Analysis Game

CodingBat exercises - DO THEM !¶

  • Warmup-1
  • Warmup-2 (not arrays)
  • String 1
  • Logic 1
  • Logic 2
  • String 2

Edabit exercises - DO THEM !¶

https://edabit.com/challenges/java

  • Select Strings as tag
  • filter from Easy to Medium included
  • ignore exercises with regex tag
  • if you have to create strings, prefer StringBuilder to + operator !!

Pros should take care of:

  • null
  • empty case
  • one char
  • repetitions
  • lowercase / uppercase
  • performance on very long strings