CS 1110/1111: Introduction to Programming

Lecture 12

Announcements

Talking Points

3 kinds of loops:

while (guard) { action; } is like an if statement except it repeats over and over again as long as the guard expression is true.

for (initializer; guard; update) { action; } is shorthand for

initializer;
while (guard) {
action;
update;
}

do { action; } while (guard); is shorthand for

action;
while (guard) {
action;
}

The do-while loop is rarely used and will not be tested in exams in this class.

While: unknown number of times

While loops are used when you don't know how many times the loop needs to repeat, but do know when you are done.

Scanner s = new Scanner(System.in);
System.out.print("Enter numbers to sum (Ctrl+Z to end): ");
int sum = 0;
while (s.hasNextInt()) {
    int number = s.nextInt();
    sum += number;
}
System.out.println("The sum is " + sum);

Ctrl+Z is a special key combination that tells the console there is not more input.

x += y; is shorthand for x = x + y; (there's -=, %=, etc, too).

In a has-next loop, make sure the has and the next match (e.g., match hasNextLine with nextLine, etc)

For: known number of times

Scanner s = new Scanner(System.in);
System.out.print("Enter a line of text: ");
String line = s.nextLine();
int capitals = 0;
for(int i = 0; i < line.length(); ++i) {
    char c = line.charAt(i);
    if (c >= 'A' && c <= 'Z') {
        capitals += 1;
    } 
}
System.out.println("There are " + capitals + " capitals letters in \"" + line + "\"");

++x is shorthand for x += 1

In Java, we always start counting with 0, not 1.

It is traditional to use i as the counter variable in a for loop.

Copyright © 2014 by Luther Tychonievich. All rights reserved.