Discussion Assignment: while loops,
sentinel loops, and fencepost problems
1. Consider the following code:
int sum = 0;
for(int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("Sum: " + sum);
Write an equivalent code segment that uses a while loop.
2. Consider the following code:
int x = 10;
System.out.print(x);
while(x < 100) {
x *= 2;
System.out.print(", " + x);
}
A. How many times is the body of the loop executed?
B. What is the output?
3.
public static void mysteryMethod(int n) {
int x = 5;
int y = 10;
while(y <= n) {
x++;
y += x;
}
System.out.println(x + " " + y);
}
What is the output from each of the falling method calls?
mysteryMethod(3); Ouput? _________________
mysteryMethod(15); Output? ________________
mysteryMethod(30); Output? ________________
4. Write a do-while loop that prints the odd integers 15 to
75.
5. Write a Java program that prompts the user to create a password,
and continues to prompt until the user enters a string of length
greater than 5 that contains at least one digit. Then the program
prints the message, "Account created". First write a method gotDigit()
which takes a String and returns true if it contains a digit and
false otherwise.
Sample Run: (user input is underlined)
Now create a password for your account. The password must contain
more than 5 characters, including at least one digit.
Password? abc1x
That is not a valid password. Try again:137
That is not a valid password. Try again: 1abcde
Account created.