Start of Tutorial > Start of Trail > Start of Lesson | Search |
- Two questions about
WhileDemo
andDoWhileDemo
.Question: What would the output be from
WhileDemo
andDoWhileDemo
if you change the value of the stringcopyFromMe
to"golly gee. this is fun"
?
Answer:WhileDemo
displays nothing.DoWhileDemo
displaysgolly
.Question: Would the output be different? Defend your answer.
Answer: The output is different. The expressionc != 'g'
is evaluated at the top of the loop inWhileDemo
. Because the first character of the string is a 'g' the statements within the loop are never executed. InDoWhileDemo
the expression is evaluated at the bottom of the loop after the first 'g' is appended to the string buffer. Thus the expression tests the second character in the string, which is an 'o'. The loop continues until the second 'g' in the string.
- Question: Identify the control flow statements in the
Sort
program.
Answer:public class Sort { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; for (int i = arrayOfInts.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (arrayOfInts[j] > arrayOfInts[j+1]) { int temp = arrayOfInts[j]; arrayOfInts[j] = arrayOfInts[j+1]; arrayOfInts[j+1] = temp; } } } for (int i = 0; i < arrayOfInts.length; i++) { System.out.print(arrayOfInts[i] + " "); } System.out.println(); } }
Start of Tutorial > Start of Trail > Start of Lesson | Search |