230 likes | 433 Views
Looping. Yong Choi School of Business CSU, Bakersfield. Objectives. Learn about the loop structure Use a while loop Use shortcut arithmetic operators Use a for loop Learn how and when to use a do…while loop Learn about nested loops. Learning about the Loop Structure.
E N D
Looping Yong Choi School of Business CSU, Bakersfield
Objectives • Learn about the loop structure • Use a while loop • Use shortcut arithmetic operators • Use a for loop • Learn how and when to use a do…while loop • Learn about nested loops
Learning about the Loop Structure • Loop: A structure that allows repeated execution of a block of statements • Loop body: A block of statements; as long as the expression is true, the loop body executes • Iteration- One execution of any loop
Using the while Loop • while Loop: execute a body of statements continually as long as the Boolean expression continues to be true • Consists of the keyword while followed by a Boolean expression within parentheses followed by the body of the loop • Use when you need to perform a task a predetermined number of times
Using a while Loop • Incrementing – Altering a loop by adding one to loop control variable • Decrementing – Altering a loop by subtracting one from a loop control variable
While Loop Example public class loopExample { public static void main (String[] args ) { int count = 1;// start count out at one while ( count <= 3 )// loop while count is <= 3 { System.out.println( "count is:" + count ); count = count + 1;// add one to count, same as (count++) } System.out.println( "Done with the loop" ); } }
Syntax of the while statement while ( condition ) loop body // a statement or block statement • When the condition is true, the loop body is exectued. • When the condition is false, the loop body is skipped, and the statment after the loop is executed. • Once execution has passed to the statement after the loop, the while statement is finished, at least for now. • If the condition is false the very first time it is evaluated, the loop body will not be executed even once.
Using Shortcut Arithmetic Operators To increase a variable’s value by exactly one: • prefix ++ • Used before the variable name • ++someValue; • postfix ++ (recommend) • Used after the variable name • anotherValue++;
Counting Upwards by Two's int count = 0; // count is initialized while ( count <= 6 ) // count is tested { System.out.println( "count is:" + count ); count = count + 2; // count is changed by 2 } System.out.println( "Done counting by two's." );
Decrementing the Loop Control Variable • The loop control variable in a counting loop can be changed by a negative value. • Here is a program fragment that decrements the loop control variable at the bottom of each iteration: int count = 2; // count is initialized while ( count >= 0 ) // count is tested { System.out.println( "count is:" + count ); count = count - 1; // count is changed by -1 } System.out.println( "Done counting down." );
Infinite Loop • What’s the result of below loop? int count = 13; int decrement = -1; while ( count >= 0 ) { System.out.println( "count is:" + count ); count = count - decrement; } System.out.println( "Count was " + count + " when it failed the test");
Using a for Loop • For loop: A special loop that is used when a definite number of loop iterations is required • Keyword for • Use a set of parentheses • Three sections within parentheses • Initializing the loop control variable • Testing the loop control variable • Updating the loop control variable
Example of For Statement public class loopExample { public static void main (String[] args ) { int count, sum; sum = 0; for ( count = 0; count <= 5; count++ ) { sum = sum + count ; System.out.print( count + " " ); } System.out.println( "sum is: " + sum );
Syntax of for Statement • Java (and several other languages) has a for statement which combines the three aspects of a loop into one statement. In general, it looks like this: for ( initialize ; test ; change ) loopBody ; • The initialize, test , and change are statements or expressions that (usually) perform the named action. The loopBody can be a single statement or a block statement. • Here is an example of a for statement: for ( count = 0; count < 10; count++ ) System.out.print( count + " " );
for loop int count, sum; sum = 0; for ( count = 0; count <= 5; count++ ) { sum = sum + count ; System.out.print( count + " " ); } System.out.println( "sum is: " + sum ); While loop int count, sum; sum = 0; count = 0; while ( count <= 5 ) { sum = sum + count ; System.out.print( count + " " ); count++ ; } System.out.println( "sum is: " + sum ); Side By Side
Using a do…while Loop • The while loop can be used to implement any loop. • However, the for loop is very convenient. • The do…while loop is occasionally convenient. • Of the three looping statements, it is used the least. • Some programmers prefer not to use it at all.
Learning How and When to Use a do…while loop • Checks at the bottom of the loop after one repetition has occurred • Bottom-driven loop • Loop body executes at least one time • The loop starts with the keyword do • The body of the loop is contained within curly braces
Example of do…while Statement int count = 0; // initialize count to 0 do { System.out.println( count ); // loop body: includes code to count++ ; // change the count } while ( count < 10 ); // test if the loop body should be // executed again.
while Loop with Alternatives import java.io.* ; public class SqrtCalc { public static void main( String[] args ) throws IOException { String chars ; double x; BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in) ); chars = "yes" ; while ( chars.equals( "yes" ) || chars.equals( "YES" ) || chars.equals( "y" ) || chars.equals( "Y" ) ) { System.out.print("Enter a number-->"); chars = stdin.readLine(); x = (Double.valueOf(chars)).doubleValue(); System.out.println("Square root of " + x + " is " + Math.sqrt( x ) ); System.out.print("Do you wish to continue? (yes or no) -->"); chars = stdin.readLine(); } } }
Nested Loops • Loops can be nested much like if statements • You can place a while loop within a while loop, a for loop within a for loop, a do…while loop within a do…while loop, or use any combination of these loops • Try the program on page 196 – 198