University of Toronto - Fall 2000
Department of Computer Science

Week 7 - Loop patterns (schemas)

Counting Loops

Schema

	// Process the n natural numbers, from 0..n-1 (for some n >= 0)
	int k = 0;
	while (k != n) {
		Process k
		k = k + 1;
	}
	// at this point, all 0..n-1 have been processed

An Example

	int k = 0;
	int x = 0;
	while (k != s.length()) {
		if (s.charAt(k) == 'w') {
			x = x + 1;
		}
		k = k + 1;
	}

Read and process loops

Schema

	String s;
	Read the first input into s
	while (s is not the stopping input) {
		Process s
		Read the next input into s
	}

An Example

	BufferedReader br = new BufferedReader (new InputStream (System.in));
	String s;
	s = br.readLine();
	while (!s.equals("quit")) {
		System.out.println (s.length());
		s = br.readLine();
	}

An Example

	BufferedReader br = new BufferedReader (new FileReader ("file.txt"));
	String s;
	s = br.readLine();
	while (s != null) {
		System.out.println (s.length());
		s = br.readLine();
	}

For loops

Schema

	// Process the n natural numbers, from 0..n-1
	for (int k=0; k != n; k++) {
		Process k
	}

An Example

	int x = 0;
	for (int k=0; k != s.length(); k++) {
		if (s.charAt(k) == 'w') {
			x++;
		}
	}

Infinite loops

Schema

	while (true) {

		if (condition) {
			break;
		}

	}

An Example

	BufferedReader in = new ...;
	int sum = 0;
	int count = 0;

	while (true) {  // an infinite loop
		// A new "i" is created at each loop cycle.
		int i = Integer.parseInt(in.readLine());

		if (i > 0) {
			sum += i;
			count++;
		}
		else if (i < 0) {
			break;	        // so it's not an infinite loop
			System.out.println("boo!");// NEVER print boo!
		}
		else
			System.out.println("zero ignored");

		// "i" is destroyed here every time through loop.
	}