Documente Academic
Documente Profesional
Documente Cultură
• Repetition Statements
• while statement
• do..while statement
• for statement
• Nested loops
• Repetition Control
Structures
Repetition Statements
Repetition statement (or loop) a block of code to be executed for a fixed number of times or
until a certain condition is met.
Syntax:
while (expression/condition)
Statement(s);
Examples While…
int i=1;
while (i<5){ Output ?
System.out.print(i + “”); 1234
i++;
}
Syntax
do
statement(s);
while (expression);
Output ?
int sum=0, number =2;
do{ SUM : 2
sum+=number; SUM : 9
number = number + 5;
System.out.println(“SUM :” + sum);
} while (number <= 10);
The for statement
Usually used when a loop will be executed a set number of times.
Syntax:
for(initial statement; loop condition; update statement)
statement(s);
2) The loop
expression/condition is
evaluated. If it is TRUE, the
loop statement is
executed followed by the
execution of the update
statement
import java.util.Scanner;
class sentinelLoop {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an Integer, or -1 to stop: ");
int choice= input.nextInt();
while (choice!=-1)
{
System.out.println("INSIDE LOOPING");
System.out.print("Enter an Integer, or -1 to stop: ");
choice= input.nextInt();
}
System.out.println("Sentinel value detected. Good Bye.");
}
}
{
number = number *2;
if (number <15)
System.out.println(number);}
}
}
How many times is the following loop body repeated?