Purdue CS 18000 - Repetition Statements & Arrays

Unformatted text preview:

WEEK 2Repetition Statements & ArraysCS 180Prof. Sunil PrabhakarDepartment of Computer Science Purdue UniversityReviewLooping constructs:while, do-while, fornested looping statementsArraysDeclare and use arraysArrays as arguments and return valuesMulti-dimensional arrays.3while ( number <= 100 ) { sum = sum + number; number = number + 1;}The while Statementwhile ( <boolean expression> ) <statement>4Control Flow of whilenext statement;truefalsesum = sum + number;number = number + 1;int sum = 0, number = 1previous statement;number <= 100 ?while (number <= 100) { sum = sum + number; number = number + 1;}5More ExamplesKeeps adding the numbers 1, 2, 3, … until the sum becomes larger than 1,000,000.Computes the product of the first 20 odd integers.int sum = 0, number = 1;while ( sum <= 1000000 ) { sum = sum + number; number = number + 1;}1int product = 1, number = 1, count = 20, lastNumber;lastNumber = 2 * count - 1;while (number <= lastNumber) { product = product * number; number = number + 2;}26String inputStr;int age;inputStr = JOptionPane.showInputDialog(null, "Your Age (between 0 and 130):");age = Integer.parseInt ( inputStr);while (age < 0 || age > 130) { JOptionPane.showMessageDialog ( null, "An invalid age was entered. Please try again."); inputStr = JOptionPane.showInputDialog ( null, "Your Age (between 0 and 130):"); age = Integer.parseInt ( inputStr); }Example: Testing Input DataPriming Read7Watch Out for Pitfalls1. Watch out for the off-by-one error (OBOE).2. Make sure the loop body contains a statement that will eventually cause the loop to terminate.3. Make sure the loop repeats exactly the correct number of times. 4. If you want to execute the loop body N times, then initialize the counter to 0 and use the test condition counter < N or initialize the counter to 1 and use the test condition counter <= N.Loop Pitfall - 1Infinite Loops Both loops will not terminate because the boolean expressions will never become false.int count = 1;while ( count != 10 ) { count = count + 2;}2int product = 0;while ( product < 500000 ) { product = product * 5;}19OverflowAn infinite loop often results in an overflow error.An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can hold.In Java, an overflow does not cause program termination. With types float and double, a value that represents infinity is assigned to the variable. With type int, the value “wraps around” and becomes a negative value.10Loop Pitfall - 2Using Real Numbers Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer’s memory.float count = 0.0f;while ( count != 1.0f ) { count = count + 0.33333333f;} //eight 3s2float count = 0.0f;while ( count != 1.0f ) { count = count + 0.3333333f;} //seven 3s111Loop Pitfall – 2aint result = 0; double cnt = 1.0;while (cnt <= 10.0){ cnt += 1.0; result++;}System.out.println ( result);1int result = 0; double cnt = 0.1;while ( cnt <= 1.0){ cnt += 0.1; result++;}System.out.println ( result);2Using Real Numbers Loop 1 prints out 10, as expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory.101112Loop Pitfall - 3Goal: Execute the loop body 10 times.count = 1;while ( count < 10 ){ . . . count++;}1count = 0;while ( count <= 10 ){ . . . count++;}3count = 1;while ( count <= 10 ){ . . . count++;}2count = 0;while ( count < 10 ){ . . . count++;}41 3and exhibit off-by-one error.QuizWhat is the value of x after this code is executed?13int n = 1;switch ( n ) { case 1: x = 10; break; case 2: x = 20; case 3: x = 30; break; default: x = 0;}A. 0B. 10C. 20D. 3014The do-while Statementdo <statement>while ( <boolean expression> ) ;do { sum += number; number++;} while ( sum <= 1000000 );Statement(loop body)Boolean Expression15Control Flow of whilenext statement;truefalseint sum = 0, number = 1previous statement;sum += number;number++;number <= 100 ?16The for Statementint i, sum = 0, number;for (i = 0; i < 20; i++) { number = scanner.nextInt( ); sum += number;}These statements are executed 20 times ( i = 0, 1, 2, … , 19).17for ( i = 0 ; i < 20 ; i++ ) { number = scanner.nextInt(); sum += number;}for statement syntaxfor ( <initialization>; <boolean expression>; <increment> ) <statement>InitializationBoolean ExpressionIncrementStatement(loop body)18Control flow of fornext statement;truefalsei=0;previous statement;number = scanner.nextInt();sum += number;i++;i < 20?for (i = 0; i < 20; i++) { number = scanner.nextInt(); sum += number;}19More for Loop Examplesfor (int i = 0; i < 100; i += 5)1 i = 0, 5, 10, … , 95for ( int j = 2; j < 40; j *= 2)2 j = 2, 4, 8, 16, 32for ( int k = 100; k > 0; k--) )3k = 100, 99, 98, 97, ..., 1NOTE: Local variable20The Nested-for StatementNesting a for statement inside another for statement is a commonly used technique in programming.Let’s generate the following table using a nested-for statement. Cost of materialat $19 per sq. ft for different lengthsand widths (in feet)21Generating the Tableint price;System.out.println(“ 5 10 15 20 25”);for ( int width = 11; width <=20; width++){ System.out.print ( width + “ “); for ( int length = 5; length <=25, length+=5) { price = width * length * 19; //$19 per sq. ft. System.out.print (" " + price); } //finished one row; move on to next row System.out.println ("");}INNEROUTER22Multiple statements in for loopint sum;for (int i=0,sum=0; i<=10; sum+=i,i++);System.out.println("Sum from 1 to 10 is:" + sum);The initialization and increment of a for loop can contain multiple statements separated by commas.for (int i=0, sum=0; i<=10; i++); { sum += i;}System.out.println("Sum from 1 to 10 is:" + sum);CAUTION: inadvertent empty loop body!!23breaking out of a loopIn some cases, it is necessary to get out of a loop.This is achieved using a break statement.int price;System.out.print(“ 5 10 15 20 25”);for (int width = 11; width <=20; width++){ for (int length = 5; length <=25; length+=5){ price = width * length * 19; //$19 per sq. ft. System.out.print (" " + price); if(price > 2000) break; } //finished one row; move on to next row System.out.println("");}24breaking out of outer loopint price;System.out.print(“


View Full Document

Purdue CS 18000 - Repetition Statements & Arrays

Download Repetition Statements & Arrays
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Repetition Statements & Arrays and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Repetition Statements & Arrays 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?