In most programming, there are 3 main kinds of loops. The For Loop, the While Loop, and the Do Until(While) loop. We will look at each individually below. There are also several statements, such as break
and continue
, that we will demonstrate their use for.
basic syntax:
for (initialization expr; test expr; update exp) {
// body of the loop
// statements we want to execute
}
example:
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
// simply loops from 1 to 10 outputting the number of the current iteration.
// where.....
// int i = 1 is the initialization parameter
// i <= 10 is the conditional parameter
// i++ is the incremental parameter
basic syntax:
for (type var : array) {
statements using var;
}
example:
// array declaration
int ar[] = { 10, 50, 60, 80, 90 };
for (int element : ar) {
System.out.print(element + " ");
}
basic syntax
while (test_expression)
{
// statements
update_expression;
}
example
int i=0;
while (i<=10)
{
System.out.println(i);
i++;
}
}
basic syntax
do {
// Loop Body
Update_expression
} while (test_expression); // Condition check
example:
// initial counter variable
int i = 0;
do {
// Body of loop that will execute minimum
// 1 time for sure no matter what
System.out.println("Print statement");
i++;
} while (i < 0);
// Checking condition
// Note: It is being checked after
// minimum 1 iteration