Continue
Part of the Fundamentals section of Coddy's Java journey — lesson 46 of 73.
The continue statement stops the current iteration and continues to the next iteration. For example:
for (int i = 3; i < 9; i++) {
if (i == 5) {
continue;
}
System.out.println(i);
}The loop will iterate through all of the numbers. When it reaches i=5 it will skip that iteration and continue to the next one. The output is:
3
4
6
7
8Notice, number 5 is not in the output.
Challenge
BeginnerYou are given a code that prints the numbers from 1 to 20 (including).
Your task is to add if and continue statements so that only even numbers will be printed (2, 4, 6, ...).
Cheat sheet
The continue statement stops the current iteration and continues to the next iteration:
for (int i = 3; i < 9; i++) {
if (i == 5) {
continue;
}
System.out.println(i);
}This will print all numbers except 5:
3
4
6
7
8Try it yourself
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
System.out.println(i);
}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else