Download presentation
Presentation is loading. Please wait.
1
COMP 110 Loops Tabitha Peck M.S. February 11, 2008 MWF 3-3:50 pm Philips 367 1
2
Announcements Office hours THIS WEEK ONLY! Monday 4:00-5:00 Tuesday 1:30-2:30 in Sitterson 252!!!!!!! Program 2 Due Wednesday by 3:00 Grades online 2
3
Questions? 3
4
Today in COMP 110 Loops Body Initializing Statements Ending a loop Bugs 4
5
Loop Body count = 1; while (count <= num) { System.out.print(count + “, “); count++; } Repeated code Write pseudocode and turn repeated statements into loops 5
6
Pseudocode for loop Get user input sum = sum + input Get user input sum = sum + input Get user input sum = sum + input Average sum 6 Repeated statements in pseudocode become your loop
7
Body of our loop Get user input sum = sum + input
8
Initializing Statements sum = sum + input Variables in your loop must be initialized (set to a value) before the loop What is initialization of sum? What if we found the product? sum = sum * input 8
9
Ending a loop 9 If you know number of loop iterations? Count-controlled loops for(count = 0; count < iterations; count++) User controlled ending Ask-before-iterating Sentinel value Booleans
10
Count-Controlled Loops for(count = 0; count < iterations; count++) { System.out.print(“I have iterated “ + (count + 1) + “times\n”); }
11
Ask-Before-Iterating do { //do stuff in your code here System.out.print( “Continue? yes/no”); answer = keyboard.next(); } while (answer.equalsIgnoreCase(“yes”)); 11
12
Sentinel Value 12 Signal end of input System.out.print(“enter a negative number to end the loop”); next = keyboard.nextInt(); sum = 0; while ( next >= 0 ) { sum = sum + next; System.out.print(“enter a number”); next = keyboard.nextInt(); }
13
Booleans int next, sum = 0; boolean numbersLeft = true; Scanner keyboard = new Scanner(System.in); while ( numbersLeft) { next = keyboard.nextInt(); if (next < 0) numbersLeft = false; else sum = sum + next; } System.out.print(“the sum is “ + sum); 13
14
What is the output? int count, count2; for (count = 0; count <= 3; count++) for(count2 = 0; count2 < count; count2++) System.out.println(count2); 14 Count = Count2 = 0 0 1 1 2 2 3 3 4
15
Writing code Give a Java loop statement that will set the variable result equal to 2 5. 15
16
Bugs Infinite loops Off-by-one errors 16
17
Infinite Loops count = 0; while (balance < 0) { balance = balance - penalty; balance + deposit; count++; } System.out.print(“You will have a nonnegative” + “balance in “ + count + “days”); 17
18
Off-by-one errors Loop repeats one too many or one too few times for (count = 1; count < 10; count++); Loop 9 times 18
19
Finding errors Error checking System.out.print(variable); Run on simple input Debugger 19
20
Wednesday Read 4.1 Program 2 Due Office hours Today after class and Tuesday at 1:30 20
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.