CSC 1240 Exam 2

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

How many iterations are performed by the following loop (i.e., how many times is the loop body executed)?num = 2; while( num < 10 ) num = 2 * num; end

3 The loop body is executed once for num = 2 to set num to 4. The second iteration sets num to 8, the third sets num to 16, upon which the loop terminates.

Loop iterates 2 times. (Use the smallest possible integer value) i = 1; while ( i < 11 ) i = i +________ ; end

5 The loop will terminate after the second iteration when i is incremented to 11.

Given the following while loop, what is the value assigned to variable z for the given values of variables a, b and c? mult = 0; while a < 10 mult = b * a if mult > c break; end a = a + 1 end z = a

5 z=5 In the first iteration, and a is 4, so mult is assigned 20 (4*5). 20 > 20 is false, so a is incremented by 1. In the second iteration, a is 5, so mult is assigned 25 (5*5). 25 > 20, so the if branch executes, causing a break from the loop. Thus, a's value of 5 is assigned to z.

Given the following code, how many times will the fprintf statement execute? i1 = 1; while (i1 < 19) i2 = 3; while (i2 <= 9) fprintf('%d%d ', i1, i2); i2 = i2 + 3; end i1 = i1 + 10; end

6 The outer loop will iterate 2 times for i1 = 1, 11. While the inner loop will iterate 3 times for i2 = 3, 6, 9. Therefore 2 * 3 = 6.

Assume user input for the GCD program results in numA = 18 and numB = 12. What is numA after the second and before the third iteration?

6 numB > numA, so the first branch is taken leaving numA unchanged.

Assume user input for the GCD program results in numA = 18 and numB = 12. What is numB after the second and before the third iteration?

6 numB > numA, so the first branch is taken setting numB = numB - numA.

Assume user input for the GCD program results in numA = 18 and numB = 12. What is numA after the first and before the second iteration?

6 numB is < numA, so the else branch is taken setting numA = numA - numB.

nested function

is a function defined within another function, known as the parent function can use variables defined in the parent function without explicitly passing those variables as arguments

functioon handle

is a special class of variable that is a pointer to another function is created by placing an @ symbol in front of a function name, and then using the assignment operator.

A special type of integer array used to extract values from a 2D array by using a single index for each indexed array element.

linear indexing array

loop body

list of statements within the loop

Any array consisting of logicals (i.e., true and false values).

logical array

A special type of logical array used for indexing.

logical indexing array

Indexing with a 2D logical array: can only be applied to 2D logical arrays. will always return a column array. generally returns a 2D array.

will always return a column array. The number of elements returned is equal to the number of true elements in the indexing array.

Linear indexing with a row array: will always return a row array. will always generate an error. can only index 2D integer arrays.

will always return a row array. The number of elements returned is equal to the number of elements in the indexing array.

Iterate while x is 99 or less. while (________) end

x <= 99

Iterate while x is positive (including 0). while (____________) end

x >= 0

Given x, y, and z coordinates of the corner of a cube with one corner at the origin, calculate the cube volume. CalcCubeVol = @( _______________) x * y * z;

x, y, z

Assume user input for the GCD program results in numA = 18 and numB = 12. What is numA before the first Euclid algorithm loop iteration?

18

x = 0; while (x > 0) fprintf('%d ',x); x = x - 1; end fprintf('Bye');

Bye x=0 so loop is never entered.

local function or subfunctions

Functions defined after the first function can appear in the program file in any order after the main function. While the main function can be called from other programs and from the command line, ________________ can only be called by other functions defined within the same program file. cannot be called from outside the program file.

Loop iterates 2 times. i = 1; while ( i <=_______ ) i = i + 1; end

2 When i is 1 or 2, the expression "i <= 2" will evaluate to true.

topMounts = [ 8848, 8611; % Asia (Everest, K2) 6962, 6893; % S. America (Aconcagua, Ojos del Salado) 6194, 5959 ] % N. America (McKinley, Logan) Write an expression using integer array row-column indexing that returns the same result as the following expression: topMounts([ false, false; false, false; true, true ]) topMounts

(3,[1, 2])'or(3,1:2)'or(3,:)' The logical indexing array example given in the question retrieves the third row of the table. Using integer indexing to retrieve the third row returns a row array, which must then be transposed to create a column array.

How many iterations are performed by the following loop?num = 2; while( num > 10 ) num = 2 * num; end

0 The loop body is never executed since num is initialized to a value less than 10.

What is x after evaluating the following code? RaisedCos = @(angle) ( cosd(angle) )^2; x = RaisedCos(45);

0.5

Given the following while loop, what is the value assigned to variable z for the given values of variables a, b and c? mult = 0; while a < 10 mult = b * a if mult > c break; end a = a + 1 end z = a a = 1, b = 1, c = 0

1 z=1. In the first iteration, a and b will be 1. mult is assigned 1. Because 1 > 0, the if branch executes, so the

The loop iterates 10 times. i = 1; while ( i <= _____) i = i + 1; end

10 i is incremented to 11 at the end of the tenth iteration, and the expression "i <= 10" will evaluate to false.

Given the following code, how many times will the fprintf statement execute? i1 = 0; while (i1 < 3) i2 = 1; while (i2 <= 7) fprintf('%d%d ', i1, i2); i2 = i2 + 2; end i1 = i1 + 1; end

12 The outer loop will iterate 3 times for i1 = 0, 1, 2. While the inner loop will iterate 4 times, for i2 = 1, 3, 5, 7. Therefore 3 * 4 = 12. Be sure to pay careful attention to the conditional operators (in this case < versus the <=).

Assume user input for the GCD program results in numA = 18 and numB = 12. What is numB after the first and before the second iteration?

12 numB is < numA, so the else branch is taken leaving numB unchanged.

What is the output of the following code? i1 = 1; while (i1 < 19) i2 = 3; while (i2 <= 9) fprintf('%d%d ', i1, i2); i2 = i2 + 3; end i1 = i1 + 10; end

13 16 19 113 116 119 outer loop: i1 = 1, 11inner loop: i2 = 3, 6, 9i1 cannot exceed 19 so the outer loop only runs twice.i2 cannot exceed 9 so the inner loop will run 3 times.

What is the value of num after the following loop terminates? num = 1; while( num < 10 ) num = 2 * num; end

16 num starts with the value 1. After the first iteration, it is assigned the value 2, then 4, etc. until it reaches the first value greater than 10, which is 16.

x=5; y=18; while (y >= x) fprintf('%d ',y); y = y - x; end

18 13 8 Note that there is a space after each number, including after the last number.

Assume user input for the GCD program results in numA = 18 and numB = 12. How many loop iterations will the algorithm execute?

2 The loop does not enter a third iteration because numA == numB (6 == 6), so execution proceeds below the while loop and thus 6 is output as the GCD.

anonymous function

is a custom function defined directly in the workspace or in a program file

Loop iterates 95 times. i = 1; while ( i <______ ) i = i + 1; end

96 i is incremented to 96 at the end of the last iteration, and the expression "i < 96" will evaluate to false.

Loop iterates from -100 to 31 (inclusive). i = -100; while ( i _____ 32 ) i = i + 1; end

< The while loop could also be "while ( i <= 31 )"

Complete the indexing statement such that only the entries in the second column of AnnuityTable are extracted, as indicated by the logical index array midIntrstIdx paymentSatCriteria =

AnnuityTable(midIntrstIdx, 2) The row indexing array is midIntrstIdx and the 2 indicates only the second column entries are of interest.

break statement

in a loop (either while loop or for loop) causes an immediate exit of the loop. Statements in the loop after the break statement do not execute. It can sometimes yield a loop that is easier to understand.

Given the rectangular coordinates a, b, and c of a point on the surface of a sphere centered at the origin given by x^2+y^2+z^2 =R^2, where R is the sphere radius, calculate the volume of the sphere. CalcRadius = @( a, b, c ) sqrt( a^2 + b^2 + c^2 ); CalcSphereVol = @( a, b, c ) (4/3) * pi * __________________________^3;

CalcRadius(a, b, c) An anonymous function can be called from within another anonymous function as long as it has been previously defined.

Write a statement that defines an anonymous function with the same name and input list, and which returns the same result as the following function definition: function f = CelToFah(c) f = (9 / 5) * c + 32; end

CelToFah = @(c) (9 / 5) * c + 32 The result of the @ operator is assigned to a variable with the desired name of the anonymous function. The input list is the same as the function definition. The result of the statement in the body of the anonymous function does not need to be assigned to an output variable.

continue statement

in a loop causes an immediate jump to the loop condition check. It can sometimes improve the readability of a loop.

Provide the required function call to the local function to complete the SineDegrees function. function x = SineDegrees( y ) x = sin (___________________); end function rad = DegsToRads( angle ) rad = ( pi/180 ) * angle; end

DegsToRads( y ) SineDegrees calls the local function DegsToRads to convert its input (assumed in degrees) to radians before calling the sin function. The functionality of SineDegrees is equivalent to the MATLAB function sind.

function dist = CalcDistLatLong( ) minsPerDeg = 60; secsPerMin = 60; secsPerDeg = minsPerDeg * secsPerMin; earthRadius = 6371; % Earth's radius in km function degOut = ConvertToDegrees( degIn, minIn, secIn ) end end ConvertToDegrees is a local function. True False

False ConvertToDegrees is a nested function, not a local function.

for index = 1:5 if index< 10 continue else disp(index) end end The loop will print at least some output. True False

False In each iteration, i is less than 10, so the continue statement executes.

Logical indexing must index all elements of an array. True False

False The last true logical indexing array element must specify an indexed array element within the indexed array size, but the logical indexing array may be bigger or smaller than the indexed array.

for index = 1:5 if index< 10 continue else disp(index) end end The loop will iterate only once. True False

False The loop will iterate 5 times. Continue jumps to the next iteration, thus preventing each iteration from printing anything. The continue statement doesn't break out of the loop though.

Integer indexing must index all elements of an array. True False

False Integer indexing specifies only the elements of the indexed array that are accessed.

How many iterations are performed by the following loop? num = -2; while( num < 10 ) num = 2 * num; end

IL (infinite loop) The loop is never terminated since num is initialized to a negative value (by definition less than positive 10) and becomes increasingly negative as each iteration is completed.

x = 10; while (x ~= 3) fprintf('%d ',x); x = x / 2; end

IL (infinite loop) because no matter how many times 10 is divided by 2, the result will never equal 3. The programmer perhaps should have used ">= 3".

An array that is being accessed by an indexing array.

indexed array

tempDistribution = [ [73,75,81] ; [85,75,69] ; [75,81,84] ]; aptNumbers = 1:9; extractAprNumbers = aptNumbers > 5 & ... aptNumbers < 8 The variable extractAprNumbers is equal to? [false, false, true, false, false, false, false, true, false] [false, false, false, false, false, true, true, false, false] [[false, false, true]; [false, false, false]; [false, true, false]] [false; false; true; false; false; false; false; true; false]

[false, false, false, false, false, true, true, false, false] A logical row array is defined with the true values in positions 6 and 7

An array used to index another array.

indexing array

Any array of integers.

integer array

topMounts = [ 8848, 8611; % Asia (Everest, K2) 6962, 6893; % S. America (Aconcagua, Ojos del Salado) 6194, 5959 ] % N. America (McKinley, Logan) Write an expression that uses logical indexing to return the height of the second-tallest mountain per continent as a column array. topMounts(

[false, true; false, true; false, true] In the indexing array, all entries in the first column are false and all entries in the second column are true. A column array is returned.

logical indexing array

a special type of indexing array that consists of logical (i.e., true or false) values

A special type of integer array used for indexing.

integer indexing array

Write a statement that defines an anonymous function named absSin, which takes a single argument x in radians and returns the absolute value of the sine of x using MATLAB functions.

absSin = @(x) abs(sin(x)) The input list contains the single variable x. sin takes an argument in radians, and the result is then passed to abs to compute the absolute value of the sine of x.

Complete the logical expression to extract all the entries in the rows with interest rates less than 12% midIntrstIdx = (

interestRates < 12 ( interestRates < 12 ) creates a logical column array.

Row-column integer indexing uses two integer indexing arrays. True False

True The first integer indexing array specifies the row(s) of the accessed elements, while the second specifies the column(s).

Good practice is to ensure number of elements in the logical indexing array and the indexed array are equal. True False

True While the logical indexing array may be bigger or smaller than the indexed array, good practice is to ensure the logical indexing array and the indexed array are the same size.

function dist = CalcDistLatLong( ) minsPerDeg = 60; secsPerMin = 60; secsPerDeg = minsPerDeg * secsPerMin; earthRadius = 6371; % Earth's radius in km function degOut = ConvertToDegrees( degIn, minIn, secIn ) end end ConvertToDegrees can access the variable earthRadius without passing the variable as an argument. True False

True earthRadius is defined within the parent function of ConvertToDegrees and can be accessed by the nested function.

function dist = CalcDistLatLong( ) minsPerDeg = 60; secsPerMin = 60; secsPerDeg = minsPerDeg * secsPerMin; earthRadius = 6371; % Earth's radius in km function degOut = ConvertToDegrees( degIn, minIn, secIn ) end end At the command line, typing the statement angDeg = ConvertToDegrees(54,40,37) will result in an error. True False

True A nested function cannot be called directly from the command line.

function dist = CalcDistLatLong( ) minsPerDeg = 60; secsPerMin = 60; secsPerDeg = minsPerDeg * secsPerMin; earthRadius = 6371; % Earth's radius in km function degOut = ConvertToDegrees( degIn, minIn, secIn ) end end The statement angularDist = ConvertToDegrees(degIn1,minIn1,secIn1) - ConvertToDegrees(degIn2,minIn2,secIn2) can appear before the final end statement. True False

True Calls to nested functions can appear anywhere within the parent function.

Iterate with i from 1 to 100 (inclusive). for ____________________ end

i = 1:1:100

randInts = [ 20, 36, 3; 33, 2, 5; 9, 14, 42 ]. What value of primeIdx causes randInts(primeIdx) to return a column array of all the prime numbers in randInts using linear logical indexing? [false, false, false, false, true, false, true, true, false ] [ false; false; false; false; true; false; true; true; false ] [ false, false, true; false, true, true; false, false, false ] [ false; false; false; false; false; false; true; true; true ]

[ false; false; false; false; true; false; true; true; false ] The logical indexing column array references the fifth, seventh, and eighth elements of randInts, corresponding to numbers 2, 3, and 5, which are all the prime numbers in the original array.

empDistribution = [ [73,75,81] ; [85,75,69] ; [75,81,84] ]; aptNumbers = 1:9; extractTemps=tempDistribution(extractAprNumbers') The variable extractTemps is equal to? [81; 81] [81, 81] [75; 81] [75, 81]

[81; 81] A column is returned, with entries at all the true positions in extractAprNumbers

Iterate with i from 212 to 32 (inclusive). for ______________ end

i = 212:-1:32

If aMat = [1, -1, 3; 2, 4, 5; 7, 11, 0] and aMat([ false, false, false, true, true, true, false, false, false]) aMat = [ 7 , 11 , 10 ] aMat = [ 2 ; 4 ; 5 ] aMat = [ -1 , 4 , 11 ] aMat = [ -1 ; 4 ; 11 ]

aMat= [-1,4,11] The logical indexing row array references the fourth through sixth elements of aMat, i.e. the entire second column, and returns a row array.

If aMat = [1, -1, 3; 2, 4, 5; 7, 11, 0] , bMat=aMat([ false,true, false; false, true, false; false, true, false]) bMat= [ 2 ; 4 ; 5 ] bMat= [ 2 , 4 , 5 ] bMat = [ -1 , 4 , 11 ] bMat = [ -1 ; 4 ; 11 ]

bMat=[-1;4;11] The row-column indexing extracts the second column and a column array is returned.

If aMat = [1, -1, 3; 2, 4, 5; 7, 11, 0] , bMat=aMat([ false, false, false; true, true, true; false, false, false]) bMat= [ 2 ; 4 ; 5 ] bMat= [ 2 , 4 , 5 ] bMat = [ -1 , 4 , 11 ] bMat = [ -1 ; 4 ; 11 ]

bMat=[2;4;5] The row-column indexing extracts the second row and a column array is returned.

Given a height argument, calculate the area of a triangle assuming the base is 7.98. ______________________; CalcTriArea = @( height ) 0.5 * base * height ;

base = 7.98 The variable base is assigned the value 7.98 before being used in the function definition.

Iterate until c is equal to the variable n. while (_________) end

c ~= n "c == n" would be incorrect. Note the word "until" rather than "while" in the question, meaning to loop while c is not n. "~(c == n)" would also be correct using two operators.

With linear indexing, what is the integer index array to display the cMat(1,1) and the cMat(2,2) as a column? % Result should be a column array resultingColumn =

cMat([1; 4]) The format is cMat([ integerColArray ]) with two elements in integerColArray.

With row-column indexing, what is the logical index array to display both the cMat(1,1) and the cMat(2,2) as a row? % Result should be a row array resultingRow =

cMat([[true, false]; [false, true]])' The format is cMat([ logical2DArray ])' where the transpose is needed to convert the output column to row.

With linear indexing, what is the logical index array to display both the cMat(1,1) and the cMat(2,2) as a row? % Result should be a row array resultingRow =

cMat([true, false, false, true]) The format is cMat([ logical1DRowArray ]) with four elements. Array elements corresponding to cMat(1,1) and cMat(2,2) are marked as true.

Row-column integer indexing: cannot be used to access elements in 2D arrays. can return a 2D array. returns only logical values.

can return a 2D array. Multiple rows and columns can be accessed in a 2D array using row-column integer indexing.

typing __________ from the command line will interrupt the program execution (exiting the infinite loop), and allow the programmer to enter a new command

ctrl-c

Iterate with i over the even integers from 4 to 20 (inclusive). for_______________ end

i = 4:2:20

iteration

each execution of the loop body

loops

execute a set of statements between the keywords that delimit the beginning and end

while loop

executes this list of statements (called the loop body) as long as the loop expression evaluates to true. The loop expression is a logical expression following the while keyword that evaluates to true or false. Logical expressions can include both relational operators (such as < or ==) and logical operators (such as &, |,or ~):

Logical indexing arrays typically result from

expressions that use relational or logical operators.

main function

first function

Iterate 100 times.

for The iterations are known before the loop, so use "for i = 1:100"

GCD

greatest common divisor, the largest positive integer that divides into the numbers without producing a remainder

Which statement will display a column of labels? hiCostDataLabels = dataLabels( hiCostIdx',:) hiCostDataLabels = dataLabels( hiCostIdx );

hiCostDataLabels = dataLabels( hiCostIdx',:) Row-column indexing is used, and MATLAB expects a 1D array. It can be either a row array or a column array. Also, hiCostDataLabels = dataLabels( hiCostIdx,:) is correct.

Loop iterates over the odd integers from 0 to 9 (inclusive). i = 1; while ( i <= 9 ) i = ______; end

i + 2 "i = i + 2" iterates over 1, 3, 5, 7, and 9.

Loop iterates over multiples of 5 from 0 to 1000 (inclusive). i = 0; while ( i <= 1000 ) i = ______ ; end

i + 5 The while loop could also be "while ( i <= 1001 )". A common error is to use "i = i * 5", which will yield 0, 0, 0, ... rather than 0, 5, 10, 15, ... (and even if start with i=1 would yield 1, 5, 25, 125, ...)

Loop iterates from 212 to 32 (inclusive). i = 212; while ( i >= 32 ) i = ______; end

i - 1 The while loop could also be "while ( i > 31 )"

With row-column indexing for 2D arrays, using a row integer indexing array and a column integer indexing array, what is the command to display both the cMat(1,1) and the cMat(2,2) as a column? % Result should be a column array resultingColumn =

no answer Row-column indexing for 2D arrays with a row integer indexing array and a column integer indexing array cannot access multiple elements in a 2D array that are on array element positions that do NOT share common rows and columns.

topMounts = [ 8848, 8611; % Asia (Everest, K2) 6962, 6893; % S. America (Aconcagua, Ojos del Salado) 6194, 5959 ] % N. America (McKinley, Logan) What result is returned by evaluating the following: outlierIdx = (topMounts > 8700) | (topMounts < 6900); outlierHts = topMounts(outlierIdx) outlierHts =8848;6194;5959;6893 outlierHts =8848;6194;6893;5959 outlierHts = 8848 6194 6893 5959 outlierHts = 8848 6194 5959 6893

outlierHts =8848;6194;6893;5959 The order is correct. Result is returned in linear indexing order.

Each element in the logical indexing array indicates whether an array element in the indexed array should be

returned (true) or not returned (false)

Provide the required statement to complete the SqrRootUserInterface function. function sqrRoot = SqrRootUserInterface( ) usrNum = input('Enter a positive number: '); ; ________________________________________________________ fprintf('The square root of %f is %f\n', usrNum, sqrRoot); end function root = NewtonSquareRoot( x ) end

sqrRoot = NewtonSquareRoot( usrNum ) The variable sqrRoot must be assigned the value of calling NewtonSquareRoot with the argument userNum.

logistical indexing array: an error is generated if

the last true element in the logical indexing array specifies an array element that exceeds the number of elements in the indexed array

Given that dataTable is a 2 × 3 array, then dataTable([ false; true; false; true; false; true ]) returns a 6 × 1 column array. the transpose of the second row of dataTable. a 1 × 3 row array consisting of elements at indices (2,1), (2,2), and (2,3). a 1 × 3 column array consisting of elements at indices (2,1), (2,2), and (3,2).

the transpose of the second row of dataTable The logical indexing row array references the second, fourth, and sixth elements of dataTable, i.e. the entire second row, and returns it as a column array. This is equivalent to taking the transpose of the second row of dataTable.

topMounts = [ 8848, 8611; % Asia (Everest, K2) 6962, 6893; % S. America (Aconcagua, Ojos del Salado) 6194, 5959 ] % N. America (McKinley, Logan) Write a relational expression that assigns the logical indexing array lowHeightsIdx the logical indices for all mountains with heights lower than 6900 m. lowHeightsIdx = (

topMounts < 6900 The indexing array is assigned logical values as a result of the relational operator. It will have true values at indices (2,2), (3,1), and (3,2) and false values everywhere else.

loop variable

variable is used to count the number of iterations

Iterate as long as the user-entered number userNum is not -1.

while The iterations are not known before the loop, so use "while (userNum ~= -1)".

Iterate until the values of x and y are equal, where x and y are changed in the loop body.

while The iterations are not known before the loop, so use "while (x ~= y)".

Linear integer indexing: is the only way to access 2D array elements. will only return a scalar. will always return a 1D array.

will always return a 1D array. Each element accessed in the indexed array is returned in a row or column array by linear integer indexing.


संबंधित स्टडी सेट्स

1.3 Physical and Chemical Properties

View Set

Effective Leading Citizens: Qualities of an Effective Leader

View Set

Exam 5 Family - Quiz, Book, and PowerPoint questions (Ch 7, 8, 23, 24, 4, 5, 6)

View Set

The Outliers Study Guide Questions

View Set