COP 4338 Midterm

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

When creating a vector ADT, the vector.c file would contain ____

Definitions of the vector functions

What is output? char level [ ] = "Minimum"; int amount = 13; printf("You have a %-.3s. of %d miles left to go \n", level, amount); return 0;

"You have a Min. of 13 miles left to go"

If the heap memory location starts at 9403, what is the value of the integer variable myAge at position 1? myAge = (int*)malloc(sizeof(int));

9403

Identify the symbol used to terminate a structure.

;

What is myChar assigned with? char myChar; myChar = '\'';

o A single-quote: '

What is the ending value of numItems if myChar = 'X'? switch(myChar) { case 'W': numItems = 1; case 'X': numItems = 2; case 'Y': numItems = 3; case 'Z': numItems = 4;

4

Dice have 6 sides, with values 1, 2, 3, 4, 5, and 6. Which expression randomly rolls one dice, directly yielding one of those values?

(rand() % 6) + 1

Which XXX and YYY best complete the code to return the minimum value in the array? int GetMinValue (int arrayVals [] XXX) { int i; int minVal; minVal = arrayVals[0]; for (i = 0; YYY; ++i) { if (arrayVals[i] < minVal) { minVal = arrayVals[i]; } } return minVal; }

, int numVals / i < numVals

Which operator is used when dereferencing a pointer to access a struct's member variable?

->

Which is true about abstract data types (ADTs)?

The implementation of an ADT is hidden from the user

Which is true regarding this preprocessor directive? #include <stdfile.h>

The preprocessor looks for stdfile in the system's standard library

Why is it best to develop a large program incrementally?

The program is easier to debug

Which expression best determines if double variable x is 74.7?

fabs (x - 74.7) < 0.0001

Given x = 1, y = 2, and z = 3, how is the expression evaluated? In the choices, items in parentheses are evaluated first. <code>(x == 5) || (y == 2) && (z == 5)</code>

false OR (true AND false) --> false OR false --> false

Assuming char* firstSymbol; is already declared, return a pointer to the first instance of an '!' in userInput.

firstSymbol = strchr(userInput, '!');

Which of the following code snippets result in a memory leak? void StudentClass() { int * ptr = (int*)malloc(sizeof(int)); } o int main() { StudentClass(); return 0; } o int main() { StudentClass(); free(StudentClass()); return 0; } o int main() { StudentClass* stu1 = new StudentClass; StudentClass* stu2 = new StudentClass; delete stu1; stu1 = stu2; return 0; }

int main() { StudentClass* stu1 = new StudentClass; StudentClass* stu2 = new StudentClass; delete stu1; stu1 = stu2; return 0; }

Which statement correctly assigns 12 into the fifth row and third column of array itemArray?

numVals[4][2] = 12;

What line of code assigns a char variable outputGames with the value the gamesPointer points to? char userGames = 'B'; char* gamesPointer;

outputGames = *gamesPointer;

What is the function? void Swap(int& x, int y){ int tmp; tmp = x; x = y; y = tmp; } int main(void) { int p = 4, q = 3; Swap(p, q); printf("p = %d, q = %d\n", p ,q); return 0; }

p = 3, q = 3

Which prints the value of the variable defined by the following statement: unsigned long destinationDistance;

printf("%lu", destinationDistance);

Which XXX tests the input value 4 using a print statement (without using assert)? int SquareNum(int origNum) { return origNum * origNum; } int main(void) { printf("Testing started\n"); XXX; printf("Testing completed\n"); return 0; }

printf("4, expecting 16, got: %d\n", SquareNum(4))

What are the possible values for ((rand()%9) + -4)?

-4...4

Which indicates the integer myAge will always be positive?

unsigned int myAge;

Which XXX and YYY will find the minimum value of all the elements in the array? Choices are in the form XXX / YYY. int userVal[NUM_ROWS][NUM_COLS]; int minVal = userVals[0][0]; for (i = 0; i < NUM_ROWS; ++i) { for (j = 0; j < NUM_COLS; ++j) { if (XXX) { YYY; } } }

userVals[i][j] < minVal / minVal = userVals[i][j]

A pointer is a ______ that contains a ______

variable, memory address

Which generates a random integer in the range 13..19?

(rand() % (19 - 13 + 1)) + 13

Which of the following statements allocates memory in the heap?

A = (int*)malloc(sizeof(int));

Which is true?

Format specifiers for scanf() and printf() are identical

What is the purpose of a variable?

To hold a value

Which header file is required to access the file pointer (FILE*)?

stdio.h

Which expression doubles x?

x *=2;

How many function parameters exist in the code? double FahrenheitToCelsius(double fahrenheit) { return (fahrenheit - 32.0) * 5.0 / 9.0; } int main(void) { double fahrenheit; scanf("%lf", &fahrenheit); int c1; int c2; int c3; int c4; c1 = FahrenheitToCelsius(fahrenheit); c2 = FahrenheitToCelsius(32); c3 = FahrenheitToCelsius(78); c4 = FahrenheitToCelsius(100); return 0; }

1

What is the output? int FindSqr(int a) { int t; t = a * a; return a; } int main(void) { int square; square = FindSqr(10); printf("%d" , square); return 0; }

10

How many x's will be output? Assume row and col are integers. for(row = 0; row < 2; ++row){ printf("x"); for (col = 0; col < 3; ++col){ //Do something } }

2

What is the ending value of z? int x = 5; int y = 12; double z; z = (double) (y / x);

2.0

How many function arguments exist in the code? double FahrenheitToCelsius(double fahrenheit) { return (fahrenheit - 32.0) * 5.0 / 9.0; } int main(void) { double fahrenheit; scanf("%lf", &fahrenheit); int c1; int c2; int c3; int c4; c1 = FahrenheitToCelsius(fahrenheit); c2 = FahrenheitToCelsius(32); c3 = FahrenheitToCelsius(78); c4 = FahrenheitToCelsius(100); return 0; }

3

Which is a correct scientific notation for the floating-point literal: 3478.904

3.478904e3

What is the ending value of cost? int numApples = 3; double cost; cost = 1.2 * numApples;

3.6

What is output, if the input is 3 2 1 0? scanf("%d" , &x); while (x > 0) { printf("%d ", 2 * x); }

6 6 6 6 6 ... (infinite loop)

Which is true regarding passing C strings to functions?

A C string is automatically passed by pointer

Which of the following statements is true about a memory leak?

A memory leak occur when a program allocates memory but loses the ability to access the allocated memory.

If realloc() cannot locate enough memory at the end of a memory block, what does realloc() return?

A pointer to a new memory block, where existing data has been copied

A linked list's head node stores ____ in the list

A pointer to the first item node

Which type of pointer is returned by the following function call? malloc(sizeof(int));

A void pointer

A linked list is slower than a vector when

Accessing the i'th element

Given struct ListEntry, which is defined in ListEntry.h and used in ListEntry.c, why does the following compilation not include ListEntry.h?

Because ListEntry.h is included in ListEntry.c

Two arrays, itemsNames and itemsPrices, are used to store a list of item names and their corresponding prices. What is true?

Both arrays should be declared to have the same number of elements

If the input sets int x with 5 and int y with 7, what is the ending value of z? Z is declared as a boolean. z = (x > y);

False

What is unit testing?

Individually testing a small part (or unit) of a program, typically a function, using a separate program called a test harness

A linked list supports faster ________ than a vector

Inserts of deletes

For an enumerated type like below, the compiler assigns what kind of value to RED, GREEN and BLACK. enum carColor {RED, GREEN, BLACK};

Integer

What variable naming convention is used for distanceFromSun?

Lower camel case

What is the error in this code? void MyFct(int& x) { x = (x * x) + 1; } int main(void) { printf("%d", MyFct(9)); return 0; }

MyFct() cannot be called with a literal

What does this code do? If x less than y Put x to output Else Put y to output

Outputs the lower of the two integers; if they are equal, outputs that integer

Which is true for the following code? char userText[10]; userText[0] = 'B'; userText[1] = 'o'; userText[2] = 'o'; userText[3] = 'k'; userText[4] = '\0'; ... userText[3] = 't';

Printing the array userText will work fine because the new string is 4 characters and the array size is 10

What is the purpose of the & symbol in the following code? int* myVar; int distance = 132; myVar = &distance;

Refers to the memory address of distance

An identifier can

Start with an underscore

Heap is a region in program memory where ____

The "malloc" function allocates memory

What is output? Typedef struct Sum_struct { int a; int b; } Sum; void Display(Sum obj) { Obj.a = obj.a + 5; Obj.b = obj.b + 10; printf("a = %d b = %d\n ", obj.a, obj.b); printf("Sum = %d\n", obj.a + obj.b); } int main(void) { Sum point; point.a = 10; point.b = 20; Display(point); return 0; }

a = 15 b = 30 Sum = 45

Assuming bodyWeights = (double*)malloc(3 * sizeof(double));, which declaration will reallocate an array of 10 double?

bodyWeights = (double*)realloc(bodyWeights, 10* sizeof(double));

Which allocated a new string carID, which is large enough to store the strings carModel, carMake, and an additional character?

carID = (char*)malloc((strlen(carMake) + strlen(carModel) + 2) * sizeof(char));

Given a function defined beginning with: void PrintMaxItem(int valsArray[], ... that prints the largest item in any array of integers. How would this function most likely iterate through the array?

for (i = 0; i < arraySize; ++i) where arraySize is a second function parameter

What function will deallocate memory after realloc() has been used?

free()

Which data type can be used instead of int to avoid overflow for an integer containing the value of 3,000,000,000,000?

long long

The fopen(str) function has a string parameter str that specifies the _____ of the file to open.

name

What is the output? int main(void) { double dividend = 0.0; double divisor = 0.0; printf("%lf\n", dividend / divisor); dividend = 3.0; printf("%lf\n", dividend / divisor); return 0; }

nan inf

Assuming int* newDimensions; is already declared, which declaration will dynamically allocate an array of 5 integers?

newDimensions = (int*)malloc(5 * sizeof(int));

A programmer compares x == y, where x and y are doubles. Many different values are expected for x and y. For values that a programmer expects to be equal, the comparison will _______.

sometimes evaluate to true, sometimes to false, depending on the values.

Which statement, executed once at the start of main(), enables a program to generate a different sequence of pseudo-random numbers from rand() each time the program is run?

srand((int)time(0));

Which statement XXX will correctly parse input string userInput[] into 3 values? char userInput[] = "Sports Tent 75.50"; float price; char storeDepartment[20]; char itemType[20]; int enteredValues = XXX; if(enteredValues >= 1){ printf("Store Department: %s\n", storeDepartment); printf("Items: %s\n", itemType); printf("Price: %.2f\n", price); }

sscanf(userInput, "%19s %19s %f", store Department, itemType, &price)

Which statement appends an exclamation point at the end of myStr? char myStr[10] = "Yay":

strcat(myStr, "!");

Identify the statement that checks whether myChar exists within myString, returning NULL if myChar does not exist, or returning the address of the first occurrence if myChar does exist?

strchr(myString, myChar)

Given string str is "Great", which choice has all matching expressions?

strcmp(str, "Great")

Which XXX prints the message only if str1 and str2 are equal?

strcmp(str1, str2) == 0

For the given pseudocode, which XXX and YYY will output the sum of the input integers (Stopping when -1 is input)? Choices are in the form XXX / YYY. val = Get next input XXX While val is not -1 YYY val = Get next input Put sum to output

sum = 0 / sum = sum + val

If a program compiles without errors, the program is free from _______.

syntax errors

What code for XXX, YYY correctly swaps a and b? Choices are written as XXX / YYY. XXX; a = b; YYY; b = tmp;

temp = a / (nothing)

How is the expression evaluated? ! x - 3 > 0

((!x) - 3) > 0

Which is a value preprocessor directive?

#include "filename.h"

Which includes a header file in the same directory as the file including the header?

#include "myheader.h"

Which XXX will result in the output "25"? #include <stdio.h> #include <stdlib.h>> void main() { typedef struct userdata_struct { int myInt; char initial; } userData; userData* newData = NULL; newData = (userData*)malloc(sizeof(userData)); XXX printf("%d", newData->myInt); free(newData); }

(*newData).myInt = 25;

Which expression for XXX outputs "Modern era" for any year 1980 and later? <code>if (year < 2000){ //Output "Past"} else if (XXX){ //Output "Modern era"}</code>

(No such expression exists)

For the given program, which XXX iterates through the array to find the state that is input (userState) until a match is found? string stateNames[NUM_STATES]; int statePop[NUM_STATES]; string userState; bool foundState = false; unsigned int i; scanf("%s", userState); foundState = false; for (i = 0; XXX; ++i) { if (stateNames[i] == userState) { foundState = true; printf("%s, %d \n", userState, statePop[i]); } }

(i < NUM_STATES) && (!foundState)

An exam with 10 questions requires all 10 answers to be correct in order to pass. Which expression represents this condition?

(numCorrect == 10)? "Pass" : "Fail"

What is the output? for (i = 0; i <= 10; ++i) { if (i == 6) continue; else printf("%d ", i); }

0 1 2 3 4 5 7 8 9 10

What possible values can x % 10 evaluate to? (x is an integer)

0..9

Which is the correct representation of 3.9e-5?

0.000039

What is the ending value of sum, if the input is 2 5 7 3? All variables are integers. scanf("%d" , &x); sum = 0; for (i = 0; i < x; ++i) { scanf("%d" , &currValue); sum += currValue; }

12

Which text most closely resembles the form in which one instruction is stored in a single location of a typical computer's memory?

Add 34, #9, 25

A sequence of instructions that solves a problem is called an _____

Algorithm

Which is true about arrays and functions?

An array is automatically passed to a function as a pointer

What is output? printf("Calculation: %+09.4lf \n", -13.785742835);

Calculation: -013.7857

A function defined beginning with void SetNegatives ToZeros(int userValue[], ... should modify userValues such that any negative integers are replaced by zeros. The function...

Can modify the array's elements directly because arrays are passed by pointer

Which is not a benefit of using enumerators over strings and constants?

Enumerators are less likely than strings or constants to cause errors

The difference threshold indicating that floating-point numbers are equal is often called what?

Epsilon

Given that integer array x has elements 5, 10, 15, 20, what is the output? int i; for (i = 0; i < 4; ++i) { printf("%d ", x[i] + x[i + 1]); }

Error: Invalid access

What is the ending value of y? pow(u, v) returns u raised to the power of v. x = 2.0; y = 3.0; y = pow(pow(x, y)) + 1.0;

Error: The compiler complains about calling a function within another function.

Information hiding allows the ADT user to ______

Focus on higher-level concepts

The automatic process of finding and freeing unreachable allocated memory locations is called a _____

Garbage collection

What will a compiler do for the following code? /* numItems = 2; /* Total Items to buy */ rate = 0.5; */

Generate an error.

Which is true regarding header files?

Header files serve as a brief summary of all functions available

What is output? #include <stdio.h> int main() { float newSize = 1.0; int i; for (i = 100; i < 120; ++i) { newSize *= i; } printf("%f", newSize); return 0; }

Infinity

Which best describes the meaning of a 1 (true) being output? Assume v is a large array of ints. int i; bool s; for (i = 0; i < N_SIZE; ++i) { if (v[i] < 0) { s = true; } else { s = false; } } printf("%d", s);

Last value is negative

In what component does a processor store the processor's required instructions and data?

Memory

The function's only behavior should be to return the sum of array userVals' elements. What common error does the function make? Assum userVals always has exactly 10 elements. int SumArrayElements(int userVals[]) { for (i = 1; i < 10; ++1) { userVals[i] = userVals[i] + userVals[i = 1]; } return userVals[i]; }

Modifies userVal's elements

Which input for char c causes "Done" to be output next? c = 'y'; while (c = 'y'){ //Do something printf("Enter y to continue, n to quit: \n"); scanf("%c", &c); } printf("Done\n");

No such value (infinite loop)

A common error when allocating a string is forgetting to account for the _____

Null character

Header file guards are preprocessor directives whose primary role is to cause the compiler to __________

Only include the contents of the header file once

What is a common error when using an ADT?

Passing an incorrect pointer to the ADT's functions

What is the output? void PrintWaterTemperatureForCoffee(int temp) { if (temp < 195) { printf("Too cold."); } else if ((temp >= 195) && (temp <= 205)) { printf("Perfect temperature."); } else if (temp > 205) { printf("Too hot."); } } int main(void) { PrintWaterTemperatureForCoffee(205); PrintWaterTemperatureForCoffee(190); return 0;

Perfect temperature.Too cold.

What is a benefit of using pointers over an array to store a list?

Pointers require fewer processor instructions to insert, delete and shift data.

What is an advantage of using separate files for structs?

Reduced compile time

Which XXX output the following? You have 3 pencils. Total Price: 60 #include <stdio.h> #include <string.h> typedef struct Data_struct { int itemCount; double price; char name[20]; } Data; Data my data; void updateItemCount(int x) { myData.itemCount = x; } void updateItemPrice(double p) { myDate.price = p; } void updateItemName(char n[20]) { strcpy(myData.name, n); } double totalPrice() { XXX } int main(void) { int number = 3; double price = 20.0; char name[] = "Pencil"; double total; updateItemCount(number); updateItemPrice(price); updateItemName(name); total = totalPrice(); printf("You have %d %ss. ", number, name); printf("Total Price: %.0f ", total); return 0; }

Return myData.item * myData.price;

Which statement defines the character search function strrchr()?

Returns a pointer to the last occurrence of the character.

What is output? #include <stdio.h> int main() { int myInt; int* myRestaurant; int myVar; int* myBill = NULL; myInt = 10; myRestaurant = &myInt; myVar = *myBill; myVar = *myRestaurant + 10.5; printf("%f\n", myVar); return 0; }

Runtime errors

Which is an essential feature of a while loop having the following form? while (LoopExpression) { LoopBody }

The LoopExpression should be affected by the LoopBody

The following program generates an error. Why? const int NUM_ELEMENTS = 5; int userVals[NUM_ELEMENTS]; unsigned int i; userVals[0] = 1; userVals[1] = 7; userVals[2] = 4; for(i = 0; i <= NUM_ELEMENTS; ++i){ cout << userVals[i] << endl; }

The for loop tries to access an index that is out of the array's valid range

Which corrects the logic error in the following program? void FindPrevNext (int x, int prev, int next) { prev = x - 1; next = x + 1; } int main(void) { int x = 10; int y; int z; FindPrevNext (x, y, z); printf("Previous = %d, Next = %d", y, z); return 0; }

The variables prev and next should be passed by reference

Which is true about testing a function with three integer parameters and one integer return value?

Using various alls involving assert() is a good way to test the function

Given input "Samantha Jones", what does the following code do? char myString[10]; fgets(myString, 10, stdin);

Writes "Samantha" to string myString

Which XXX would generate "the USA has 50 states" as the output for "the usa has 50 states" as the input? #include <stdio.h> #include <string.h> int main(void) { char userInput[100]; char* stringPosition = NULL; printf("Enter a line of text: "); fgets(userInput, 100, stdin); stringPosition = strstr(userInput, "usa"); if (stringPosition != NULL) { XXX } printf("%s\n", userInput); return 0; } a.strncpy(*stringPosition, "USA", 3); b.strncpy(stringPosition, "USA", 3); c.strncpy(stringPosition, "USA"); d.strncpy(stringPosition, 'USA', 3);

b. strncpy(stringPosition, "USA", 3);

Identify the correct declaration of an array of strings.

char stringArr[10][50];

Which XXX will delete a node from a list? DeleteNode(IntNode* priorNode) { IntNode* delNode = NULL; XXX }

delNode = priorNode->nextNodePtr; priorNode->nextNodePtr = delNode->nextNodePtr;

Which XXX completes the program to calculate the volume of a cone? XXX int main(void) { double coneVol; coneVol = ConeVolume(2, 4); printf("%1f" , coneVol); return 0; } double ConeVolume (double r, double h) { return (0.33) * 3.14 * ComputeSquare(r) * h; } double ComputeSquare (double r) { return r * r; }

double ConeVolume (double r, double h); double ComputeSquare (double r);

Which statement XXX outputs each element of array customerName to a file called CustomerList.txt using a file pointer? char* customerName[5] = {"Bob", "Sally", "Jim", "Joe", "Denise"}; FILE *inputFile = NULL; int numberplayers; inputFile = fopen("Customer.txt", "w"); for(int i = 0; i < 5; ++i){ XXX }

fprintf(inputFile, "%s\n", customerName[i]);

Which XXX is used to read and store the data into the variable numberPlayers from the file that is opened by the stream inputFile?

fscanf(inputFile, "%d", &numberPlayers);

Which XXX causes every character in string inputWord to be output? for (XXX) { printf("%c\n" &inputWord[i]); }

i = 0; i < strlen(inputWord); ++i

Which XXX will generate the following output? "importantNum = 10"

importantNum = (int*)malloc(sizeof(int));

Which XXX converts the string userStr to uppercase? for (i = 0; userStr[i] != '\0'; ++i) { XXX; }

userStr[i] = toupper(userStr[i]);


Ensembles d'études connexes

Emergency Nursing Practice Questions

View Set

PrepU Ch 9 Teaching and Counseling

View Set

CTI-120 Cybersecurity chapters 1-6 quizzes

View Set

Nursing Considerations for the Child and Family with a Chronic condition

View Set

Chapter 8 Review Quiz- UAFS US History I FULL ONLINE Julie Oliver

View Set