CS

¡Supera tus tareas y exámenes ahora con Quizwiz!

"To find the number of elements in an array, you add .length to its name. Do parentheses go after the word length?"

"No, they are not allowed"

To visit every character in a string, a for loop should iterate over indices _____.

0 to length-1

Given the following code, how many times will the inner loop body execute? char letter1; char letter2; letter1 = 'a'; while (letter1 <= 'f') { letter2 = 'c'; while (letter2 <= 'f') { // Inner loop body ++letter2; } ++letter1; }

24

int row; int col; for(row = 0; row < 2; row = row + 1) { for(col = 0; col < 3; col = col + 1) { // Inner loop body } } how many times will the inner loop body execute?

6

How many times wil this loop iterate: for ( k = 0; k < 8; ++k ) { }

8

When can a class' private methods be called?

A class' private methods can only be called from the class' other methods.

what does a double variable store?

A double variable stores a floating-point number. Ex: double milesTravel -declares a double variable.

what is a nested loop?

A nested loop is a loop that appears in the body of another loop.

What is a primitive type variable?

A primitive type variable directly stores the data for that variable type, such as int, double, or char. Ex: int numStudents = 20; declares an int that directly stores the data 20.

what can a programmer use method stubs for?

A programmer can use method stubs to capture the high-level behavior of main() and the required method (or modules) before diving into details of each method, like planning a route for a road trip before starting to drive. A programmer can then incrementally develop and test each method independently.

Array initialization

A programmer may initialize an array's elements with non-default values by specifying the initial values in braces {} separated by commas. Ex: int[] myArray = {5, 7, 11}; creates an array of three integer elements with values 5, 7, and 11.

What is a reference variable?

A reference variable stores the memory address of an object. We say that the variable "refers" to the object. A reference type variable can refer to an instance of a class, also known as an object.

What is a sentinel?

A sentinel value is a special value indicating the end of a list, such as a list of positive integers ending with 0, as in 10 1 6 3 0. The example below computes the average of an input list of positive integers, ending with 0. The 0 is not included in the average.

"When used as part of a loop, what is a sentinel?"

A special data value that tells the loop when to stop

break statement

A statement that causes a loop to terminate early/causes an immediate exit of the loop

How can a switch statement be written?

A switch statement can be written using a multi-branch if-else statement, but the switch statement may make the programmer's intent clearer.

Can a user call private methods?

A user of the class can call public member methods, but a user can not call private member methods (which would yield a compiler error).

Definition of while loop (zybooks official)

A while loop is a program construct that repeatedly executes a list of sub-statements (known as the loop body) while the loop's expression evaluates to true. Each execution of the loop body is called an iteration. Once entering the loop body, execution continues to the body's end, even if the expression would become false midway through.

How many times can a while loop run?

A while loop will always run at least once but can also run an infinite amount of times.

element

Each item in an array

"If you create an int array of a given size but don't initialize its values, all of its elements will be automatically initialized to -1"

False

A key benefit of method stubs is faster running programs.

False

4 elements of a loop (in order)

Initialization-1st Test-2nd Update-3rd Body-4th

internal data members/methods are

Internal Data members=private

Is there a restriction when it comes to calling private helpers?

No such restriction exists. A private helper can be called from any other method of the class, whether public or private.

Do uppercase and lowercase letters have the same value in an identifier?

No. Identifiers are case sensitive, meaning upper and lower case letters differ. So numCats and NumCats are different.

Do processors store data?

No. a computer is basically a processor interacting with a memory, as depicted in the following example. In the example, a computer's processor executes program instructions stored in memory, also using the memory to store temporary results. The example program converts an hourly wage ($20/hr) into an annual salary by multiplying by 40 (hours/week) and then by 50 (weeks/year), outputting the final result to the screen. The processor computes data, while the memory stores data (and instructions).

how can you tell the number of iterations (repetitions of something) in a for loop?

Number of iterations is computable before the loop, like iterating N times.

how can you tell the number of iterations in a (repetitions of something) while loop?

Number of iterations is not (easily) computable before the loop, like iterating until the input is 'q'.

what is one use of a nested loop?

One use is to generate all combinations of some items

void shuffle(int[] deck)

Reorders deck's contents to have a random order.

double average(int[] values)

Returns the average of the elements in the array values.

int kthLargest(int[] values, int k)

Returns the kth largest element of array values.

int maximum(int[] values)

Returns the largest element in values.

void rotateRight(int[] values, int numPositions)

Shifts elements of the array numPositions to the right, wrapping the last element around to the beginning of the array.

Arrays and Loops

Such array initialization does not require the use of the new operator, because the array's size is automatically set to the number of elements within the braces. For larger arrays, initialization may be done by first defining the array, and then using a loop to assign array elements.

Write three statements to print the first three elements of array runTimes. Follow each statement with a newline. Ex: If runTime = {800, 775, 790, 805, 808}, print: 800 775 790

System.out.println(runTimes[0]); System.out.println(runTimes[1]); System.out.println(runTimes[2]);

what is an enhanced for loop?

The enhanced for loop is a for loop that iterates through each element in an array. An enhanced for loop is also known as a for each loop. The enhanced for loop declares a new loop variable, whose scope is limited to the for loop, that will be assigned with each successive element of an array. The enhanced for loop only allows elements to be accessed forward from the first element to the last element.

Any for loop structure can be rewritten as a while loop

True

Any while loop structure can be rewritten as a for loop

True

Incremental development may involve more frequent compilation, but ultimately lead to faster development of a program.

True

It is possible for a for loop to execute zero times

True

It is possible for a while loop to execute zero times

True

Modular development means to divide a program into separate modules that can be developed and tested independently and then integrated into a single program.

True

You can declare an array and give its size in two separate program statements

True

You can make an array that holds boolean values

True

You can use an arithmetic expression to give the size of an array

True

Do memories store data?

Yes. A memory is a circuit that can store 0s and 1s in each of a series of thousands of addressed locations, like a series of addressed mailboxes that each can store an envelope (the 0s and 1s). Instructions operate on data, which is also stored in memory locations as 0s and 1s.

Do operators perform calculations?

Yes. An operator is a symbol that performs a built-in calculation, like +, which performs addition.

incremental development

a process in which a programmer writes, compiles, and tests a small amount of code, then writes, compiles, and tests a small amount more (an incremental amount), and so on.

An error that unintentionally modifies data is known as

a side effect. A common side effect is a method that calculates values based on an array, but unintentionally modifies the array. Methods should perform exactly one task. A method can calculate something or change the array contents, but should not do both.

array

an ordered list of items of a given data type.

continue statement

causes an immediate jump to the loop condition check; improves readability of a loop;

most data methods are

data methods=public

"Write a statement that will define a two-dimensional array of doubles named klinemobile, with CCC columns and RRR rows. Assume CCC and RRR are already-defined integer constants."

double [] [] klinemobile = new double [RRR] [CCC];

Write a for loop to print all elements in courseGrades, following each element with a space (including the last). Print forwards, then backwards. End each loop with a newline. Ex: If courseGrades = {7, 9, 11, 10}, print:

for (i = 0; i < NUM_VALS; i++) { System.out.print(courseGrades[i] + " "); } System.out.println(""); for (i = NUM_VALS - 1; i >= 0; --i) { System.out.print(courseGrades[i] + " "); } System.out.println("");

Write a for loop to populate array userGuesses with NUM_GUESSES integers. Read integers using Scanner. Ex: If NUM_GUESSES is 3 and user enters 9 5 2, then userGuesses is {9, 5, 2}.

for (i = 0; i < userGuesses.length; ++i) { userGuesses[i] = scnr.nextInt(); }

different parts of a for loop

for (initialization; condition; increment/decrement)

what are the three parts of a for loop? What does each part of the for loop do?

for (initialization; condition; increment/decrement)

Which of these loop types puts three of these four elements all on the same line?

for loop

If a for loop iterates through a string s using variable i, the loop body can access the current character as:s.charAt( _____ )

i

What do we a call a loop whose test is always true, preventing the loop from ever ending?

infinite loop

example of variable declaration

int userAge; declares a new variable named userAge that can hold an integer value.

7.19.3: Errors in method signatures and handling array parameters.

int[] hoursWorked = {0, 7, 9, 5}; copyOfRange(hoursWorked, 1, 3); .. . public static void copyOfRange(int[] arrayReference, int start, int end) { int[] tempArray = new int[end - start]; int index; for (index = start; index < end; ++index) { tempArray[index - start] = arrayReference[index]; } arrayReference = tempArray; }

method stub

is a method definition whose statements have not yet been written.

A while loop

is a program construct that repeatedly executes a list of sub-statements (known as the loop body) while the loop's expression evaluates to true. Each execution of the loop body is called an iteration. Once entering the loop body, execution continues to the body's end, even if the expression would become false midway through.

Modular development

is the process of dividing a program into separate modules that can be developed and tested separately and then integrated into a single program.

Which test expression will make this loop iterate 10 times: for ( j = 1; ______ ; ++j ) { }

j < 11

Which test expression will make this loop iterate 6 times: for ( j = 10; ______ ; --j ) { }

j > 4

nextLine

makes a new line after the string

Assign numMatches with the number of elements in userValues that equal matchValue. userValues has NUM_VALS elements. Ex: If userValues is {2, 1, 2, 2} and matchValue is 2 , then numMatches should be 3.

numMatches = 0; for (i = 0; i < userValues.length; ++i) { if(userValues[i] == matchValue) { numMatches++; } }

Array testGrades contains NUM_VALS test scores. Write a for loop that sets sumExtra to the total extra credit received. Full credit is 100, so anything over 100 is extra credit. Ex: If testGrades = {101, 83, 107, 90}, then sumExtra = 8, because 1 + 0 + 7 + 0 is 8.

sumExtra = 0; for (i = 0; i < NUM_VALS; ++i) { if (testGrades[i] > 100) { sumExtra = sumExtra + (testGrades[i] - 100); } }

How many times can a for loop run?

the for loop will run as many times as it takes, until a certain condition is met. This means that a for loop could run zero times, 1 or more, or even infinite... all depending upon the condition

If a method returns something other than an array reference or void,

the method likely does not modify the array contents.

If a method returns an array reference,

the method likely should construct a new array

If a method returns void,

the method likely should modify the array's contents.

while loop code example a program that has a "conversation" with the user, asking the user to type something and then (randomly) printing one of four possible responses until the user enters "Goodbye".

while (!userText.equals("Goodbye")) { randNum = userText.length() % 4; // "Random" num. %4 ensures 0-3 System.out.println();

example of a while loop

while( userNum >1){ userNum=userNum/2; System.out.print(userNum+" "); }


Conjuntos de estudio relacionados

Cartilage & Bone - Human Anatomy & Physiology - Chapter 6 - Tortora

View Set

Life Insurance - Chapter 10: Taxation of Life Insurance and Annuities - Premiums and Proceeds

View Set

Fundamentals Nursing Prep U Chapter 22 Nurse Leader, Manager, and Care Coordinator

View Set

Chapter 3 All, Chapter 2 All, Chapter 1 All

View Set

PEDS unit 4 ch 27,28,18; ATI ch 21,21,22,5

View Set