/** Demo loops, CS1110, 29 March 2012 */ public class Demo { /** = the largest power of 2 that is at most n. Precondition: 1 <= n. Example: n = 1. 2**0 = 1 but 2**1 = 2. So set s to 1. Example: n = 31. 2**4 = 16 but 2**5 = 32. So set s to 16. */ public static int pwr(int n) { int s= 1; // inv: s is a power of 2 and s <= n while ( 2*s <= n) { s= 2*s; } // { R: s is a power of 2 and s <= n and 2*s > n } return s; } /** = number of times the first char of s appears at beginning of s. Precondition: s has at least one character. Example: s answer "bbbcgbb" 3 "$b$$$" 1 "hh" 2 */ public static int beginningLength(String s) { int t= 1; // Loop invariant: R1 while (t != s.length() && s.charAt(t) == s.charAt(t-1)) { t= t+1; } /* { R1: 0 t s.length() |----------------|----------| |all the same | | |---------------------------| R2: either t = s.length() or s[t] != s[t-1] } */ return t; } /** = position of first occurrence of c in s. Precondition: c is in s. */ public static int linearSearch(char c, String s) { int k= 0; // Store in k to truthify R // invariant: c is not in s[0..k-1] while (s.charAt(k) != c) { k= k+1; } /* { R: 0 k s.length |----------------|-|--------| |c is not here |c| | |----------------|-|--------| } */ return k; } }