1. Java in two semesters by Quentin Charatan & Aaron Kans
2. Computers can repeat the same tasks over and
over, again and again
Form of program control that allows us to instruct
the computer to carry out a task by repeating a
section of code
Iteration
Loop
Types of Loops
for loop
while loop
do...while loop
9. Often used to implement the fixed repetitions
10.
11. Consider the following scenarios
A racing game that repeatedly moves a car around
until the car crashes
A ticket issuing program that repeatedly offers tickets
for sale until he user chooses to quit the program
A password checking program that does not let a user
enter into an application until he or she enters the
right password
Thenumber of repetitions is not fiexed but
depends on some condition
Non fixed Iterations
12. while (/*test goes here*/)
{
//instruction(s) to be repeated
}
simpler to construct
If not used as counter loop, then it is not required
to keep a counter
Normally used to validate the input
13.
14. import java.util.Scanner;
public class Assignment1
{
public static void main(String[] args)
{
int marks;
Scanner input = new Scanner(System.in);
marks = input.nextInt();
while(marks<0 || marks>100)
{
System.out.println("Invalid Marks - ReEnter?");
marks = input.nextInt();
}
if(marks>=40)
{
System.out.println("Congratulations... You passed");
}
else
{
System.out.println("Sorry you failed the course");
}
}
}
16. Tests the condition at beginning
If the condition is false at start, makes the loop to
not execute ever
Loop executes ZERO or MORE times
17.
18. Non – Fixed Loop
Condition is tested at the end of the loop
Makes the loop to iterate at least once
Makes the loop to iterate ONE or MORE times
while loop terminates once the program has done
its job.
Do while is suitable if we wish to re-run the same
program again based on user response
Syntax:
do
{
//instruction(s) to be repeated goes here
}while (/* test goes here*/);
19. char response;
do
{
Scanner input = new Scanner(System.in);
//program instructions go here
System.out.println(“Want to re-run? (y/n)”);
response = input.next().charAt(0);
}while(response ==‘y’);
20. do
{
System.out.println("1 - for group A");
System.out.println("2 - for group B");
System.out.println("3 - Quit");
response = sc.nextInt();
switch(response)
{
case 1:
System.out.println("10:00 AM");
break;
case 2:
System.out.println("11:00 AM");
break;
case 3:
System.out.println("Good Bye");
break;
default:
System.out.println("Invalid Input");
break;
}
}while(response!= 3);
21. For Loop
Number of repetitions required can be determined
prior to entering the loop
While Loop
Number of repetitions cannot be determined prior to
entering the loop and
Zero repetitions is allowed
Do… while loop
Number of repetitions cannot be determined before
the loop
You require at least one repetition of loop