LESSON 1 Flashcards
(15 cards)
It allows us to execute a statement or group of statements multiple times and on the side is the general form of a __ statement in most of the programming
languages.
Loop
Parts of Loop
Initialization
Condition
Change of State
Statement
It is used to execute a statement or a
group of statements repeatedly as
long as the supplied condition is true.
Iteration Statement
A statement in Java programming language repeatedly executes a target statement as long as a given condition is true. Is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use ___.
While Loop
While Loop syntax:
Syntax:
Initialization;
while(Condition) {
Statements;
Change of State;
}
While loop syntax example:
Output:
1
2
3
4
5
class Main {
public static void main(String[] args) {
// declare variables
int i = 1, n = 5;
// while loop from 1 to 5
while(i <= n) {
System.out.println(i);
i++;
}
}
}
A ___ is similar to a while loop, except that a ___is guaranteed to execute at least one time. The Java is used to iterate a part of the program several times. Use it if the number of iteration is not fixed and you must have to execute the loop at least once.
Do While Loop
Do while syntax:
Initialization;
do {
Statements;
Change of state;
}while(Condition);
Do while syntax example:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int i = 1, n = 5;
// do…while loop from 1 to 5
do {
System.out.println(i);
i++;
} while(i <= n);
}
}
Java __ is used to run a block of code for a certain number of times. The Java ___is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use .
For Loop
For loop syntax:
for(initialization; Condition; ChangeOfState)
{
// Statements
}
For loop syntax example:
Program to print a text 5 times
class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println(“Java is fun”);
}
}
}
If a loop exists inside the body of
another loop, it’s called a __
Nested loop
Nested loop syntax:
// outer loop
for (int i = 1; i <= 5; ++i) {
// codes
// inner loop
for(int j = 1; j <=2; ++j) {
// codes
}
}
Nested loop syntax example:
public class Main {
public static void main(String[] args) {
int rows = 5;
// outer loop
for (int i = 1; i <= rows; ++i) {
// inner loop to print the numbers
for (int j = 1; j <= i; ++j) {
System.out.print(j + “ “);
}
System.out.println(“”);
}
}
}