next up previous
Next: Characteristic elements in the Up: Unit 06 Previous: Example of while loop:

Example of while loop: counting the occurrences of a character in a string

public static int countChar (String s, char c) {
  int numchars = 0;
  int pos = 0;
  while (pos < s.length()) {
    if (s.charAt(pos) == c)
      numchars++;
    pos++;
  }
  return numchars;
}

Note that in all four previous examples the loops are in fact definite loops, since the number of iterations depends only on the values of variables that have been fixed before starting the execution of the loop.


next up previous
Next: Characteristic elements in the Up: Unit 06 Previous: Example of while loop: