Transcript Loops

Loops
• body - statements to be repeated
• control statement - decides whether another repetition
needs to be made
• leading decision loop - control statement before body
(min 0)
• trailing decision loop - control statement after
body (min 1)
• logical loop - based on some condition in the data
while
do..while
• counted loop - based on some iteration
for
The WHILE Loop
while (expression)
statement
• Leading decision
• Min 0
• Most common loop
use S-T-A-R method with most while loops
System.out.println("Enter grade, -1 to quit");
//start
numberGrade = console.nextInt();
//start
while (numberGrade != -1)
//Test
{
letterGrade = ConvertGrade(numberGrade);
//action
System.out.println("Letter grade is " + letterGrade);//action
System.out.println("Enter grade, -1 to quit");
//restart
numberGrade = console.nextInt();
//restart
}
better
System.out.println("Enter grade, -1 to quit");
//start
numberGrade = console.nextInt();
//start
while ((numberGrade > 0) && (numberGrade < 110))
//Test
{
letterGrade = ConvertGrade(numberGrade);
//action
System.out.println("Letter grade is " + letterGrade);//action
System.out.println("Enter grade, -1 to quit");
//restart
numberGrade = console.nextInt();
//restart
}
Caution:
while (ans = ‘y’)
while (ans == ‘y’);
while ((ans == ‘Y’) && (ans == ‘y’))
While loops
•
•
•
•
Sentinel Controlled
End of File Controlled
Flag Controlled
Count Controlled
Sentinel loops
•
•
•
•
•
•
Sentinel value – some ending value
999
XXX
-1
0
Easy to implement
Sentinel-Controlled Loop
item = console.nextInt();
while (item != Sentinel)
{
Process(item)
item.console.nextInt();
}
//start
//test
//action
//restart
Sentinel controlled loop
total = 0;
System.out.println( "Enter a bill (-1 to stop ) ";
bill = console.nextInt();
while (bill > -1)
// while not sentinel
{
total = total + bill;
System.out.println( "Enter a bill (-1 to stop ) ";
bill = console.nextInt();
}
System.out.println(total);
//start
// test
//action
//restart
LOOP EXERCISES
• Start by writing the control statement (TEST) for
each. Then write the priming step (START). Next
write the body (ACTION) and don’t forget
RESTART
• Input numbers until 0 is entered and print
whether odd or even.
START
TEST
ACTION
RESTART
1. Input names until XXX and print Hello
and the corresponding name.
2. Input test scores, print pass or fail.
Choose a sentinel.
3. Input temperatures, printing if above or
below freezing, choose a sentinel.
4. Repeat above problem, asking the user
each time if they want to enter a
temperature.Advantages and
disadvantages?
4. Given the input data 5 10 20 -1 what is the output of the following code
fragment? (All variables are of type int.)
sum = 0;
number = console.nextInt();
while (number != -1)
{
sum = sum + number;
number = console.nextInt();
}
System.out.println(sum);
Do a Problem Until the User Wants to Quit
Often you want to allow the user to do some task repeatedly.
A simple way to allow this is to ask the user whether or not
to do another of whatever the task at hand might be.
System.out.println("Play (y/n)? ");
reply = console.next();
while (reply.compareTo("y")== 0)
{
DoSomething();
System.out.println("Do another (y/n)? ");
reply = console.next();
}
Counter:
• initialize :
count = 0;
• increment : count++;
Adding a Counter to a
Sentinel-Controlled While Loop
int count;
count = 0;
// initialize
item = console.nextInt();
while (item != sentinel)
{
count++;
// increment
Process(item);
item = console.nextInt();
}
Accumulator:
• Initialize: total = 0;
• Update: total = total + num;
Adding a Running Total to a SentinelControlled While Loop
total = 0;
item = console.nextInt();
while (item != Sentinel)
{
total = total + item;
item = console.nextInt();
}
Finding an Average in a Sentinel-Controlled While Loop
Since we know how to total and count the data items read in by a sentinel-controlled
while loop, we can now easily find the average of these data items.
int count;
count = 0;
total = 0;
Item = console.nextInt();
while (item != Sentinel)
{
count++;
total = total + item;
item = console.nextInt();
}
if (count > 0)
{
average = total / count;
System.out.println("Average: " + average);
}
else
System.out.println("No data. The average cannot be computed.");
Flag Controlled Loop
numAttempts = 0;
isMatch = false;
// initialize Boolean flag
start
while (!isMatch)
test
{
code = console.next();
action
if ( code.equals (PASSWORD))
restart
isMatch = true;
// change flag value
else
numAttempts++;
}
System.out.println(numAttempts);
• Use a flag called done to write a loop that
only sums positive numbers and quits
when a negative number is entered
Count Controlled Loop
int count ;
count = 0;
// initialize loop variable
while (count < 10)
// test expression
{
System.out.println(count); // action
count++ ; // restart -update loop variable
}
System.out.println ("Done");
Designing WHILE Loops
• If a loop is needed:
– what is the loop's logical expression? => test
– what needs to be initialized before the while
loop? (priming condition) => start
– what statements should be repeated in the
loop? => action
– what needs to be updated in the logical
expression? => restart
– what is known when the loop finishes
The DO..WHILE Loop
do
statement
while (expression);
do.. while
do
{
DisplayMenu();
choice = console.nextInt();
switch (choice)
{
case 1:
PlayBeginner();
break;
case 2:
PlayAdvBeginner();
break
case 3:
PlayIntermediate();
break
case 4:
break;
default:
System.out.println(“ Invalid option” );
break;
}
} while (choice != 4);
Loop Exercises:
1. What is the final value of j?
j = 2;
while (j < 10)
j = 2 * j;
2. What is the final value of k?
k = 5;
do
{
k = k + 10;
} while (k < 3);
3. Write a program that will prompt for, receive, and total a
collection of payroll amounts entered at the terminal
until the value –99 is entered. Display the total.
4. Write a program that asks the user if they want to enter a
state code, quitting when the user answers ‘N’.
5. Write a program to print the even numbers from 2 to
2000.
The FOR Loop
This type of loop is usually used when you know
how many times you wish to execute the same section of code (the
loop count may be a variable).
for (initialization; condition; update)
statement
for loop
Example:
int k;
System.out.println("counting...");
for (k = 0; k < 10; k++)
{
System.out.println(k);
}
Can be used to count down:
Example:
int n;
for (n = 10; n > 0; n--)
System.out.println(n);
System.out.println("Blast
off!”);
Can count by 2, 10's whatever:
Example:
int n;
for (n = 2; n < 60; n +=13)
System.out.println(n);
prints 2,15,28,41,54
You can count by characters
instead of numbers
Example:
char ch;
for (ch = 'a';ch <= 'z';ch++)
System.out.println(ch);
You can test any condition, not just
the iteration
Example:
int num;
System.out.println("n
n cubed);
for (num = 1;num*num*num <= 216;num++)
System.out.println(num + " " + num*num*num);
Increment step can do anything i.e.can increase a quantity geometrically
Example:
float debt;
for (debt = 100.0; debt < 150.0; debt *= 1.1)
System.out.println("You debt is now $" +debt);
Expression1, 2,and 3 are optional
for (;;)
{
... /* infinite loop */
}
First and third expression not
limited to initialization and
incrementation
for(System.out.println("Keep entering numbers!");num==6;)
num = console.nextInt();
Can alter parameters from inside
loop
for (n = 1; n < 10000; n++)
{
if ((n % 10) == 0)
n++;
}
Not a good idea!
Comma used to allow more than
on expression
for (x = 0, y = 0; x + y < 1000; x++,y++)
System.out.println(x + y);
Exercises:
1. What is the final value of sum?
int i, j, k, sum;
sum = 0;
for (i = 0; i < 10; i = i + 2)
sum = sum + i;
2. What is the output of the following fragment:
int i, j;
for (i = 10; i <= 50; i += 10)
{
j = i/2;
System.out.println(j);
}
3. 3 Why does Yoda not print even once?
for ( i=0; i>10; i++)
{
System.out.println("Yoda");
}
4 Show the output:
for (q=2; q<=6; q++)
{
System.out.println("Hee Hee!! That tickles!");
}
5.Show the output:
for ( c=1; c=5; c++)
{
System.out.println("The computer has run amok!");
}
6. Show the output:
for (count = 10; count >0; count--)
{
System.out.println(count);
}
System.out.println(" Ready or not, here I come!");
7. Show the output:
for (w=2; w<10; w+=2)
System.out.print(w + “ “ );
System.out.println(“who do we appreciate? Java!");
8. Write a program using a for loop that prints the statement "Java
knows loops." 5 times and then prints the statement: "Java knows
when to stop." once.
9. Write a program using a for loop that asks the user to enter 8 numbers
and prints the total and average of the eight numbers.
10. Write a for loop that prints 1 2 4 8 16 32 64 128.
Nested Loops
• placing of one loop inside the body of
another loop is called nesting.
• When you "nest" two loops, the outer loop
takes control of the number of complete
repetitions of the inner loop.
• All types of loops may be nested, the most
commonly nested loops are for loops.
• When working with nested loops, the outer
loop changes only after the inner loop is
completely finished
Exercises:
1. Show screen output:
for (outer = 0; outer < 2; outer++)
{
for (inner = 0; inner <=2; inner++)
{
System.out.println( outer + “ “ + inner);
}
}
2. Show screen output:
for (outer = 0; outer < 3; outer++)
{
for(inner = 2; inner <=4; inner++)
{
System.out.println( inner );
}
System.out.println();
}
3. The following set of nested loops is NOT working. Can you find what is
wrong??
for (ctr1 = 1; ctr1 <=10; ctr1++);
{
for(ctr2 = 1; ctr2 <=5; ctr2++)
{
number = ctr1 * ctr2;
System.out.println(number );
}
}
4. Show the output for the following program fragment:
for (ctr1 = 8; ctr1 > 5; ctr1--)
{
for(ctr2 = 1; ctr2 < 3; ctr2++)
{
System.out.println(ctr1 " + " ctr2 + " ");
}
System.out.println();
}
5. Show the output:
for(j=1; j<=5; j++)
{
for(k=1; k<=j; k++)
{
System.out.print (" * “);
}
System.out.println();
}
6.
Write a program using nested loops to produce the following design:
A
AB
ABC
ABCD
ABCDE
ABCDEF
7. Write a program using nested loops to produce a rectangle of *'s with
6 rows and 20 *'s per row.
8. Give the output
i = 0;
while (i < 3)
{
j = 1;
while (j < 3)
{
System.out.println( "i = ", i," j = ",j);
j++;
}
System.out.println();
i++;
}
break
• exits one level of iteration
• used with switch, while, for, do..while
• Example:
int x;
for ( x = 1; x <= 10; x++ )
{
if ( x == 7 )
break; // break loop only if x is 7
System.out.print(x + " ");
}
System.out.println();
System.out.println("Broke out of loop at x of " + x);
•
• Note: If break is located inside nested structures, control exits only
the innermost structure containing it.
continue
• used with while, for, do..while
• Goes to next iteration
• Example:
int x;
for ( x = 1; x <= 10; x++ )
{
if ( x == 7 )
continue;
System.out.print(x + " ");
}
System.out.println();
System.out.println("Used continue to skip printing value “);
• Note: continue terminates the current loop iteration, but not the
entire loop
break and continue
• Use with caution
• In exceptional occurrences
• One use of break and continue
– the part of the loop that follows is extremely
complicated and deeply nested, so that
adding an IF statement to bypass this code
and indenting another level would nest the
program too deeply