Unit 4 Flashcards
difference between selection and repetitions?
if vs. loops (while or for loops)
ALWAYS USE CURLIES?
real
3 parts of a for loop header
- initialized loop variable
- test loop variable in loop header
- change loop variable
how do you create an infinite while loop?
while(true)
{
}
name of the stopping value of a loop
sentinel value
true/false
all 3 parts of a for statement should all refer to the same variable
technically possible to not, but def SHOULD (true)
if it exists within the method, does a return statement HAVE to be the end of a method?
yes
can you put return constant statements in an if-else in a loop, such as with
“
while (a>=0)
if (word.substring(a, a+1).equals(c))
{
return a;
}
else
return -1;
a–
“? why?
no, as that return statement returns that number outside of the loop and ends it prematurely
is there an empty string after EVERY string?
yes, this is why youre able to traverse strings until the very end (at indexOf = -1, whatever variable = “”)
can you declare a variable in a loop?
yes, but it only remains in the scope of that loop
4-1-5: Consider the following code segment. What is count’s value after running this code segment? (To trace through the code, keep track of the variable count and its value through each iteration of the loop.)
int count = 1;
while (count <= 10)
{
count *= 2;
}
count = count - 10;
A. 0
B. 1
C. 16
D. 6
D
4-1-6: What does the following code print? (To trace through the code, keep track of the variable x and its value, the iteration of the loop, and the output every time through the loop.)
int x = -5;
while (x < 0)
{
x++;
System.out.print(x + “ “);
}
A. 5 4 3 2 1
B. -5 -4 -3 -2 -1
C. -4 -3 -2 -1 0
C
generally, in loops, when you want to count to a number and you start at 0, you use ______ (<, <=) and when you want to count to a number and you start at 1, you use _____ (<, <=)
<
<=