Lesson
What are the loops in java
Loops in Java is a feature used to execute a particular part of the program repeatedly if a given condition evaluates to be true. While all three types’ basic functionality remains the same, there’s a vast difference in the syntax and how they operate.
Known examples are:
- while
- for
For loop
The structure of the for statement is the same as above. As long as the condition is true, the codes are repeated, and when it becomes false, the loop stops. At first, the initialization (the first value is stored in a variable) is executed.
- **Initialization**: This is the part that initializes variables to be used in the loop, and is performed only once at the beginning.
- for(int i=1 ;i<=10;i++){ }
- for(int i=1, j=1;i<=10;i++){ }
- **Condition**: Iteration continues as long as the value of the condition is true, and if it is false, iteratipon stops and exits the for code.
- for(int i=1; **i<=10;** i++){ }
- **Iteration** Increases or decreases the value of the variable that controls the loop. Each time the code is executed, the value of the variable increases or decreases, and later the condition becomes false and the for repetition stops.
- for(int i=1;i<=10;**i++**){ }
- for(int i=10;i>=1;**i--**){ }
- for(int i=1;i<=10;**i+=2**){ }
The three elements can be written by joining two or more sentences together using commas. Additionally, these elements can be omitted if not necessary, and can be omitted altogether.
–> for( ; ; ) { } Infinite loop
for loop in array
for(type : array or collection) {
Values stored in an array or collection are read one by one in order at each repetition and stored in variables.
}
The structure of the for loop in array is the same as above, and is separated by a colon (:) rather than a semicolon (;). Variable name: After declaring it as an array name, when the variable name is output, the array element value is output according to the corresponding index. Unlike the general for loop, the for loop in array can only be used to read elements stored in arrays and collections.
for (int k: score) {
System.out.print(k + " ");
}
while loop
while (condition) {
<code1>;
<code2>;
<code3>;
...
}
Infinite loop
In Java, an infinite loop can be implemented with a while statement. Among the programs we use, infinite loops are used so often that there is not a single one that does not use the concept of infinite loops.
while (true) {
<code1>;
<code2>;
...
}
break
The while statement repeatedly executes the contents of the while statement while the conditional statement is true. However, there are times when you have to forcefully exit the while statement.
For example, consider a coffee vending machine. Whenever there is enough coffee in the vending machine, a while statement with the conditional statement ‘Give coffee when money is received’ is executed. In order for the vending machine to function properly, it would have to separately check the amount of coffee, stop the while loop when the coffee runs out, and display the phrase ‘Selling stopped’ on the vending machine. **break** is used when you need to force a while statement to stop.
break also works on for loop
public class Coffee {
public static void main(String[] args) {
int coffee = 10;
int money = 300;
while (money > 0) {
System.out.println("Give coffee when money is received");
coffee--;
System.out.println("The amount of coffee remaining is " + coffee);
if (coffee == 0) {
System.out.println("We're out of coffee. stop selling.");
break;
}
}
}
}
Coffee.main(null)
Give coffee when money is received
The amount of coffee remaining is 9
Give coffee when money is received
The amount of coffee remaining is 8
Give coffee when money is received
The amount of coffee remaining is 7
Give coffee when money is received
The amount of coffee remaining is 6
Give coffee when money is received
The amount of coffee remaining is 5
Give coffee when money is received
The amount of coffee remaining is 4
Give coffee when money is received
The amount of coffee remaining is 3
Give coffee when money is received
The amount of coffee remaining is 2
Give coffee when money is received
The amount of coffee remaining is 1
Give coffee when money is received
The amount of coffee remaining is 0
We're out of coffee. stop selling.
continue
When the continue command is met, the Java Virtual Machine jumps to the next iteration of the loop without executing more of the while loop body.
continue also works on for loop
public class Ex1 {
public static void main(String[] args) {
int a = 0;
while (a < 10) {
a++;
if (a % 2 == 0) {
continue; // if it is even, go back to the condition
}
System.out.println(a); // print only odd number.
}
}
}
Ex1.main(null);
1
3
5
7
9
While vs For, Which is more faster
For the experiment, declare an ArrayList to contain integers as shown below.
At this time, by placing test_data in memory,
so that it can be used anywhere within the class
Place it as a global variable (member variable) in the field of public class WhichLoopIsFaster.
public static ArrayList<Integer> test_data = InputTestData();
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
public class WhichLoopIsFaster {
public static ArrayList<Integer> test_data = InputTestData();
public static void main(String[] args) {
WhichLoopIsFaster evaluate = new WhichLoopIsFaster();
evaluate.For();
evaluate.While();
}
public void For() {
System.out.println("\n--- For ---\n");
long startTime = new Date().getTime();
int i;
for (i = 0; i < test_data.size(); i++) {
int v = test_data.get(i);
}
long endTime = new Date().getTime();
long elapsed = endTime - startTime;
System.out.println("For :: time: "+elapsed+ " ms " );
}
public void While() {
System.out.println("\n--- While Loop ---\n");
long startTime = new Date().getTime();
int i = 0;
while (i < test_data.size()) {
int v = test_data.get(i);
i++;
}
long endTime = new Date().getTime();
long elapsed = endTime - startTime;
System.out.println("While :: time: "+elapsed+ " ms" );
}
public static ArrayList<Integer> InputTestData() {
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int i = 0; i < 15000000; i++) {
arr.add(i);
}
return arr;
}
}
WhichLoopIsFaster.main(null);
--- For ---
For :: time: 33 ms
--- While Loop ---
While :: time: 26 ms
Result
The execution speed of the For statement and While statement seem to be almost similar.
public static ArrayList<Integer> InputTestData() {
ArrayList arr = new ArrayList();
for (int i = 0; i < 15000000; i++) {
arr.add(i);
}
return arr;
}
length
- length is used when you want to know the length of an array.
- arrays(int[], double[], String[])
length()
- String related Object(String, StringBuilder etc)
- length() is used when you want to know the length of a string.
Q37 concatWords method with String array
Now that you’ve learned the basics of for loop and while loop manipulation, it’s time to tie this into the 2015 CollegeBoard MCQ we took. Today, we will be going over question 37. which is the following:
popcorn hack
Analyze the code and fill out the blank in the line
startIndex is equal to 2
1.
for(k = startIndex; k< words.length; k++) {
result+= words[k] + words[words.length - k -1];
}
k starts with 2 and become 3 and 4. Eventually, it will stop when k reaches to 5 (words.length)
When k = 2 –> words[k] = ___ , words[words.length - k -1] = ____
When k = 3 –> words[k] = ___ , words[words.length - k -1] = ____
When k = 4 –> words[k] = ___ , words[words.length - k -1] = ____
Then describe the reason why this is possible or not.
_______________________
2.
int k = words.length - 1;
while (k > = startIndex) {
result += words[k];
k--;
}
Since the words.length is 5, the k will start as 4 and become 3 and 2. it will stop when k becomes lower than 2
when k = 4 –> words[k] = ___
when k = 3 –> words[k] = ___
when k = 2 –> words[k] = _____
Then describe the reason why this is possible or not.
_______________________
3.
String[] temp = new String[words.length];
for (int k= 0; k<=words.length/2; k++) {
temp[k] = words[words.length - k - 1];
temp[words.length - k - 1] = words[k];
}
for (int k = 0; k< temp.length - startIndex; k++) {
result += temp[k];
}
The k for fist loop will be 0 and become 1 and 2 in the second and third loop. (because words.length/2 = 2)
The array temp will have 5 numbers stored in it.
When k = 0 –> words[words.length - k - 1] = __ , words[k] = ___
When k = 1 –> words[words.length - k - 1] = __ , words[k] = ___
When k = 2 –> words[words.length - k - 1] = __ , words[k] = ___
temp = [_, __, __, __, ___]
For the second loop the k starts with 0 and become 1 and 2 like the first loop.
The result will be sum of first, second, and third elements on the array
hen describe the reason why this is possible or not.
_______________________
Hack
- Create the new method so that when the code segment is executed, the string “CarHouseGorilla” is printed.
- Calculate the time of the codes and compare the all of those.