03 Loops
January 5, 2024 · 1 min read
If you have any questions, feel free to comment below. Click the block can copy the code.
And if you think it's helpful to you, just click on the ads which can support this site. Thanks!
Use == to compare primitive data types for equality; for other types (such as strings and functions), use equals to compare them.
while Loops
#
Note: In C++, you can write while(n--), but in Java you must write while(n-- > 0), or the code will not compile.
Find the nth term of the Fibonacci sequence. f(1) = 1, f(2) = 1, f(3) = 2, f(n) = f(n-1) + f(n-2)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a = 1, b = 1, i = 1;
while (i < n) {
int c = a + b;
a = b;
b = c;
i ++ ;
}
System.out.println(a);
}
}
do while Loops
#
do while loops are not commonly used.
A do while statement is very similar to a while statement. The only difference is that a do while statement checks the condition after executing the loop body. Regardless of the condition’s value, the loop body executes at least once.
public class Main {
public static void main(String[] args) {
int x = 1;
while (x < 1) {
System.out.println("x!");
}
int y = 1;
do {
System.out.println("y!");
} while (y < 1);
}
}
for Loops
#
Find the nth term of the Fibonacci sequence. f(1) = 1, f(2) = 1, f(3) = 2, f(n) = f(n-1) + f(n-2).
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a = 1, b = 1;
for (int i = 1; i < n; i ++ ) {
int c = a + b;
a = b;
b = c;
}
System.out.println(a);
}
}
Jump Statements #
break #
Exits a loop early, usually together with an if statement.
continue #
Jumps directly to the end of the current loop iteration.
Find the sum of all even numbers from 1 to 100.
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i ++ ) {
if (i % 2 == 1) continue;
sum += i;
}
System.out.println(sum);
}
}
Related readings
If you want to follow my updates, or have a coffee chat with me, feel free to connect with me: