Programming Fundamentals (MIDTERM)

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Are the following two declarations the same? char city[] = {'D', 'a', 'l', 'l', 'a', 's'}; char city[] = "Dallas";

no No. The first one is an array of characters. The second one is a C-String with a terminating character at the end.

Given an int variable k, an int array incompletes that has been declared and initialized, an int variable nIncompletes that contains the number of elements in the array, an int variable studentID that has been initialized, and an int variable numberOfIncompletes, write code that counts the number of times the value of studentID appears in incompletes and assigns this value to numberOfIncompletes. You may use only k, incompletes, nIncompletes, studentID, and numberOfIncompletes.

numberOfIncompletes=0; for (k=0; k<nIncompletes; k++){ if (incompletes[k] == studentID){ numberOfIncompletes++; } }

Arguments to functions always appear within __________.

parentheses

If a parameter is a reference variable, this parameter becomes an alias for the original variable. This is referred to as _________.

pass by reference

When you invoke a function with a parameter, the value of the argument is passed to the parameter. This is referred to as _________.

pass by value

If you wanted a function to return TWO variables, ____.

pass the arguments by reference

The ___ modifies the source code to create a larger, modified source code file. The ___ creates an executable file that you can run from the machine code.

preprocessor compiler

printArray is a function that has two parameters. The first parameter is an array of element type int and the second is an int, the number of elements in the array. The function prints the contents of the array parameter; it does not return a value. inventory is an array of ints that has been already declared and filled with values. n is an int variable that holds the number of elements in the array. Write a statement that prints the contents of the array inventory by calling the function printArray.

printArray(inventory,n);

printErrorDescription is a function that accepts one int parameter and returns no value. Write a statement that calls the function printErrorDescription, passing it the value 14.

printErrorDescription(14);

Assume that printStars is a function that takes one argument and returns no value. It prints a line of n stars (followed by a newline character ) where n is the value of the argument received. Write a statement that invokes printStars to make a line of 35 stars.

printStars(35);

CPU

Central Processing Unit; the brain of the computer.

>> << cin cout radius answer

Stream extraction operand Stream insertion operand console input console output radius answer

Actual parameter or argument

Values passed to the function

Formal parameters

Variables declared in the function header

What will be displayed by the call my_function('a', 3)? void my_function(char ch, int n) { while (n > 1) { cout << ch; n--; } }

aa

The benefits of a function are:

ability to reuse code reduce complexity easy to maintain the code

Assume int t[] = {1, 2, 3, 4}. What is t[4]?

accessing t[4] may result in a runtime error t[4] is out of bounds, which may cause an error.

Parameters can be passed by reference, which makes the formal parameter a(n) ___ of the actual argument. Thus, changes made to the parameters inside the function are also made to the arguments.

alias

The compiler checks____

syntax errors

When you pass an array to a function, __________ is passed to the array parameter in the function.

the starting address of the array

Which built-in function could you use to convert a letter to lowercase?

tolower()

Compiler

A computer program created to read an entire program and convert it into a lower-level language and ultimately to assembly language used by the processor.

Algorithm

A precise sequence of instructions for processes that can be executed by a computer

source code

A program in a high-level language before being compiled.

software

A program or instructions that give directions to the computer.

Which of the following are correct? -An array can hold multiple elements. -All the elements in an array have the same type. -An array element can be accessed using an index. -You can declare an array to store 100 integers. -All of the above.

All of the above

Example of high-level language

C++, Java, Python

ASCII

Encoding system to store text, where one byte is used for each character. Compare Unicode.

(T/F) A global variable is a variable that is defined inside a function.

False

(T/F) If an array is sorted, a linear search is more efficient than a binary search for finding an element in the array.

False

(T/F) Parameters are required.

False

(T/F) Since C++ is NOT case-sensitive, area, Area, and AREA all represent the same thing.

False

(T/F) You can always convert an if statement to a switch statement

False Switch statements only with integral values, so it would not work when evaluating doubles, floats, or strings.

(T/F) The (while) loop and (for) are called posttest loops because the continuation condition is checked after the loop body is executed. The (do-while) loop is called a pretest loop because the condition is checked before the loop body is executed.

False. (while) and (for) are pretest loops (do-while) is a posttest loop

(T/F) Software is the physical aspect of the computer that can be seen such as the CPU, memory, Storage devices, Input/Output devices, and Communication devices.

False. This is hardware.

What is wrong with the following: int num = 5; int myArray[num];

The size indicator cannot be a variable. It must be either a literal integer (5, 10, 11, etc...) or a constant (const int num = 5)

Function body

The statements enclosed in the function block that are executed when the function is called

__________ is to implement one function in the structure chart at a time from the top to the bottom.

Top-down approach

(T/F) A function may (or may not) return a value.

True

(T/F) A function prototype declares a function without having to implement it.

True

(T/F) A loop can be used to tell a program to execute statements repeatedly.

True

(T/F) A void function does not return a value.

True

(T/F) After a function completes its execution, all its local variables are destroyed.

True

(T/F) All four of the following statements are true. 1) A variable must be declared before it can be assigned a value. 2) A variable without a value assigned to it is an uninitialized variable. 3) A variable must initialized (assigned a value) in order to (1) print its value or (2) use it in an expression. 4) The scope of a variable is the part of the program where the variable can be referenced.

True

(T/F) An escape sequence consists of a backslash \ followed by a character or combination of digits. The backslash and character together represent another character that may be difficult to otherwise represent.

True

(T/F) Another common technique for controlling a loop is to designate a special value when reading and processing a set of values. This special input value, known as a sentinel value.

True

(T/F) C++11 supports a convenient for loop, known as a foreach loop, which enables you to traverse the array sequentially without using an index variable.

True

(T/F) Every statement in C++ must end with a semicolon (;) known as the statement terminator (though pre-processor statements are not C++ statements so they do not end in a semicolon.)

True

(T/F) If the variable is declared inside a loop control structure, it cannot be references outside the loop.

True

(T/F) If there is only one statement in a loop body, the braces can be omitted.

True

(T/F) If you pass an array to a function and you change the array in the function, you will see the change outside the function.

True

(T/F) In general, a (for) loop is commonly used when the number of repetitions is known in advance.

True

(T/F) Memory is volatile, because information is lost when the power is turned off. Programs and data are permanently stored on storage devices and are moved, when the computer actually uses them, to memory, which is much faster than storage devices.

True

(T/F) Suppose char city[8] = "Houston"; Then city is a C-string.

True

(T/F) The (char) type represents only one character.

True

(T/F) The code shown below is an example of a code using a while loop char c; cin >> c; while (c != 'Q' && c != 'q') cin >> c; The code listed below shows the same code rewritten using a do-while loop. char c; do { cin >> c; } while (c != 'Q' && c != 'q');

True

(T/F) The higher the resolution, the sharper and clearer the image is.

True

(T/F) The parameter list contains the type, order, and number of the parameters of a function.

True

(T/F) The software development life cycle is a multi-stage process that includes the following items (in the following order): -requirements specification -system analysis -system design -implementation -testing -deployment -maintenance

True

/*hello*/

a block comment

#include

a directive that instructs the computer to make available facilities from a file

byte

a group of 8 bits

//hello

a line comment

A variable defined inside a function is referred to as __________.

a local variable

Variable

a value stored in a computer

What is the indexed variable for the element at the first row and first column in array a?

a[0][0] The index starts from 0. So the first row and first column is [0][0]. Summary Previous item,

What is the representation of the third element in an array called a? a[2] a(2) a[3] a(3)

a[2]

We informally define the term "corresponding element" as follows: The first element in an array and the last element of the array are corresponding elements. Similarly, the second element and the second last element are corresponding elements. The third element and the third last element are corresponding elements -- and so on. Given an array a and a variable n that contains the number of elements in a, write an expression for the corresponding element of a[i].

a[n-i-1]

The following code displays ____. cout << "a" << setw(6) << "abc";

a___abc

Suppose void nPrint(char ch, int n) { while (n >0) { cout << ch; n--; } } What will be displayed by the call nPrint('a', 4)?

aaaa Invoking nPrint('a', 4) prints 'a' 4 times.

int

an example of a keyword

.cpp

an extension added to the end of a source file

Which of the following is correct to obtain a double value from a numeric string "1.55"?

atof("1.55")

bit

binary digit

Test whether a number is even, and returning true if it is

boolean isEven(int value)

A computer's components are interconnected by a subsystem called a

bus

Which of the following assignment statement(s) is correct? char c = 'd'; char c = 10; char c = "d"; char c = "1";

char c = 'd'; char c = 10;

Which of the following statements is correct? char charArray[][] = {'a', 'b'}; char charArray[2][2] = {{'a', 'b'}, {'c', 'd'}}; char charArray[2][] = {{'a', 'b'}, {'c', 'd'}}; char charArray[][] = {{'a', 'b'}, {'c', 'd'}};

char charArray[2][2] = {{'a', 'b'}, {'c', 'd'}};

Declare a char array named line of size 50, and write a statement that reads in the next line of console input into this array. (Assume the line may contain whitespace characters and the total number of the characters in the line is less than 50)

char line[50]; cin.get(line,50);

toThePowerOf is a function that accepts two int parameters and returns the value of the first parameter raised to the power of the second. An int variable cubeSide has already been declared and initialized. Another int variable, cubeVolume, has already been declared. Write a statement that calls toThePowerOf to compute the value of cubeSide raised to the power of 3 and stores this value in cubeVolume.

cubeVolume = toThePowerOf(cubeSide, 3);

using namespace std;

declares that the program will be accessing entities whose names are part of the namespace called std

Given a char variable c that has already been declared, write some code that repeatedly reads a value from console input into c until at last a 'Y' or 'y' or 'N' or 'n' has been entered.

do { cin >> c; }while (!(c == 'Y' || c == 'y' || c == 'N' || c == 'n'));

Given the following function definitions, which of the functions is invoked for double z = m(4, 4.4); double m(double x, double y) double m(int x, double y) double m(int x, int y)

double m(int x, double y)

The following code displays ______________. #include <iostream> using namespace std; void maxValue(int value1, int value2, int max) { if (value1 > value2) max = value1; else max = value2; } int main() { int max = 0; maxValue(1, 2, max); cout << "max is " << max << endl; return 0; }

max is 0 When invoking maxValue(1, 2, max), max is not changed.

A program and its data must be moved into the computer's _______ before they can be executed by the CPU.

memory

An array is declared as: double myList[1]; The above line assumes the array will contain ONE element. To initialize that one element to 10;

myList[0] = 10;

How would you represent the fourth element in an array called myList?

myList[3];

Which of the parameters is passed by reference? void increment(int& n, int x)

n

Write some code that repeatedly read a value into n until at last a number between 1 and 10 (inclusive) has been entered.

n = -1; while (n < 1 || n > 10) { cin >> n; }

Pseudocode

natural language mixed with some programming code

A loop inside of another loop is called a ___ loop.

nested

Displays whether a number is even (without returning a value)

void isEven(int value)

Prints the square root of a number (without returning a value)

void mysqrt(double value)

Write the definition of a function printArray, which has two parameters. The first parameter is an array of ints and the second is an int, the number of elements in the array. The function does not return a value. The function prints out each element of the array, on a line by itself, in the order the elements appear in the array, and does not print anything else.

void printArray (int s[], int n){ for (int k = 0; k < n; k++){ cout << s[k] << endl; } }

Write a statement that declares a prototype for a function printArray, which has two parameters. The first parameter is an array of element type int and the second is an int, the number of elements in the array. The function does not return a value.

void printArray(int[], int);

Display the calendar for a month, given the month and year (and no return value)

void printCalender(int month, int year)

Write the definition of a function printDottedLine, which has no parameters and doesn't return anything. The function prints a single line consisting of 5 periods (terminated by a new line character).

void printDottedLine() { cout << ".....\n"; }

Write the definition of a function printLarger, which has two int parameters and returns nothing. The function prints the larger value of the two parameters on a single line by itself. (For purposes of this exercise, the "larger" means "not the smaller".)

void printLarger(int a, int b) { if (a > b) cout << a << endl; else cout << b << endl; }

Write the definition of a function named swapints that is passed two int variables. The function returns nothing but exchanges the values of the two variables. So, if j and k have (respectively) the values 15 and 23, and the invocation swapints(j, k) is made, then upon return, the values of j and k will be 23 and 15 respectively.

void swapints(int& j, int& k){ int temp; temp = j; j = k; k = temp; }

What will be displayed by the following code? double x = 10.1; int y; y = (int) x; cout << "x is" << x << " and y is " << y;

x is 10.1 and y is 10. This is because x was declared a double and allowed decimals And y was declared an integer without decimals

What is the output of the following code? #include <iostream> using namespace std; void f(double& p) { p += 2; } int main() { double x = 1; double y = 1; f(x); f(y); cout << "x is " << x; cout << " y is " << y << endl; return 0; }

x is 3 y is 3 p is pass by reference. After invoking f(x), x is changed. After invoking f(y), y is changed.

What will be displayed by the following code? #include <iostream> using namespace std; void f(int& p1, int p2) { p1++; p2++; } int main() { int x1 = 1; int x2 = 1; f(x1, x2); cout << "x1 is " << x1 << " x2 is " << x2; return 0; }

x1 is 2 x2 is 1 p1 is pass by reference and p2 is pass by value. After invoking f(x1, x2), x1 is changed, but x2 is not.

Analyze the following code. #include <iostream> using namespace std; int main() { int x[3]; cout << "x[0] is " << x[0]; return 0; }

x[0] has an arbitrary value.

Are the following two declarations the same? char city[7] = "Dallas"; char city[] = "Dallas";

yes

Returns the square root of a number

double mysqrt(double value)

How many characters are stored in city using the following declaration? char city[7] = "Dallas";

7 The null terminator character '\0' is stored last.

What will be displayed to the console from the following C++ statement? cout << "\"Programming is fun\\awesome\"!!!\n" << endl;

"Programming is fun\awesome"!!! followed by a newline

Write a program that reads student scores, gets the best score, and then assigns grades based on the following scheme: Grade is A if score is >= best - 10; Grade is B if score is >= best - 20; Grade is C if score is >= best - 30; Grade is D if score is >= best - 40; Grade is F otherwise. The program prompts the user to enter the total number of students, then prompts the user to enter all of the scores, and concludes by displaying the grades. Sample Run Enter the number of students: 4 Enter 4 scores: 40 55 70 58 Student 0 score is 40 and grade is C Student 1 score is 55 and grade is B Student 2 score is 70 and grade is A Student 3 score is 58 and grade is B

#include <iostream> #include <cstring> using namespace std; int main() { int arr1[100],arr2[100]; int n,temp,max,temp1; cout<<"Number of students: "; cin>>n; cout<<"scores: "; for(int i = 0;i<n;i++) { cin>>temp; arr1[i] = temp; arr2[i] = temp;} for (int i = 0; i < n-1; i++) { max = i; for (int j = i+1; j < n; j++) if (arr1[j] > arr1[max]) max = j; temp1 = arr1[max]; arr1[max] = arr1[i]; arr1[i] = temp1; } int best = arr1[0]; for(int i = 0;i<n;i++) { if(arr2[i] >= best-10) cout<<"Score: "<<arr2[i]<<" grade: A "<<endl; else if(arr2[i] >= best-20) cout<<"Score: "<<arr2[i]<<" grade: B "<<endl; else if(arr2[i] >= best-30) cout<<"Score: "<<arr2[i]<<" grade: C "<<endl; else if(arr2[i] >= best-40) cout<<"Score: "<<arr2[i]<<" grade: D "<<endl; else cout<<"Score: "<<arr2[i]<<" grade: F"<<endl; } }

Write the following function that returns true if the list is already sorted in increasing order: bool isSorted(const int list[], int size) Write a test program that prompts the user to enter a list and displays whether the list is sorted or not. Assume that the maximum number of integers in the list is 100. So declare array of size 100. Sample Run 1 Enter the size of the list: 8 Enter list: 10 1 5 16 61 9 11 1 The list is not sorted Sample Run 2 Enter the size of the list: 10 Enter list: 1 1 3 4 4 5 7 9 11 21 The list is already sorted

#include <iostream> using namespace std; int main() { int n; cout << "enter the size of the list : "; cin >> n; //input the list size int arr[n]; cout << "enter list :"; for(int i=0;i<n;i++){ cin >> arr[i]; //input the values of list } int j,flag=0;; for(int i=0;i<n;i++){ for(j=i+1;j<n;j++){ if(arr[i]>arr[j]){ //if the list not sorted make the flag value 1 flag=1; } } } if(flag==0) //if flag value remains same ,the list is already sorted cout << "The list is already sorted"; else //if flag value changed ,the list is not sorted cout << "The list is not sorted"; return 0; }

What will correctly display Star Wars to the console?

#include <iostream> using namespace std; int main() { string movie; cout << "Enter a string: " getline(cin, movie); cout << movie << endl; }

Which of the following expressions does NOT successfully test to see if the value stored in the variable x is a capital letter? ('A' <= x && x <= 'Z') (65 <= x && x <= 90) (x == CAPITAL_LETTER)

(x == CAPITAL_LETTER)

What is the output of the following code: int x[4] = {2}; cout << x[1] << endl;

0

What will be displayed by the following code? char s2[7] = "Dallas"; char s1[14] = "Dallas"; cout << strcmp(s1, s2);

0

What is the output of the following code? int count = 0; while (count < 5) { cout << count << " "; count++; }

0 1 2 3 4

If an array contains 10 elements, the index numbers start at ___ and end at ___.

0, 9

What is the output of the following code? inline void print(int i) { cout << i << endl; } int main() { print(1); return 0; }

1

What is the output of the following code? int values[] = {3, 1, 2, 3, 4}; int min = values[0]; for (int e : values) if (min >= e) min = e; cout << min << endl;

1 The code finds the minimal element in array values.

What is the output of the following code? int f() { return 1; } int main() { cout << f() << endl; return 0; }

1 The function f() returns 1.

What is the output of the following code? double myList[] = {1, 5, 5, 5, 5, 1}; double max = myList[0]; int indexOfMax = 0; for (int i = 1; i < 6; i++) { if (myList[i] > max) { max = myList[i]; indexOfMax = i; } } cout << indexOfMax << endl;

1 The list has four 5s. indexOfMax is the index of the first largest element 5 in the list, which is 1.

What is the output of the following code: int values[] = {1, 2, 3, 4}; for (int e: values) cout << e << endl; return 0;

1 2 3 4

What is the output of the following code? int list[] = {1, 2, 3, 4, 5, 6}; for (int i = 1; i < 6; i++) list[i] = list[i - 1]; for (int i = 0; i < 6; i++) cout << list[i] << " ";

1 1 1 1 1 1 list[0] is assigned to list[1], then list[1] is assigned to list[2], and so on.

What is the output of the following code? int myList[] = {1, 2, 3, 4, 5, 6}; for (int i = 4; i >= 0; i--) { myList[i + 1] = myList[i]; } for (int i = 0; i < 6; i++) cout << myList[i] << " ";

1 1 2 3 4 5 The elements in myList is shifted right one position. But the first element is not changed.

gigabyte

1 billion bytes

What is the number of iterations in the following loop (i.e how many times is the body of the loop executed?): 1) for (int = 1; i < n; i++) { //iteration } 2) for (int = 1; i <= n; i++) { //iteration }

1) n-1 times due to it not being (<=) 2) n times

Assume the myList array has been declared. Based on the following loop, what is the value stored in myList[5]: for (int i =0; i < 10; i++) { myList[i] = i*2; }

10

What is the output of the following code? int f() { return 10; } int main() { cout << f() << endl; return 0; }

10

kilobyte

1000 bytes

What is the output from the following code? double number = 12.34567; cout << setprecision(3) << number << endl;

12.3

What is the output of the following code: #include <iostream> using namespace std; int main() { int x[] = {120, 200, 16}; for (int i = 0; i < 3; i++) cout << x[i] << " "; return 0; }

120 200 16 The array elements are displayed. Summary Previous item,

Which of the following is an INVALID identifier? firstPlace place1 1stplace _firstplace

1stplace an identifier cannot start with a number

Show the output of the following code: char city[7] = "Dallas"; cout << strlen(city);

6 Returns the length of the string, i.e., the number of the characters before the null terminator.

Suppose void nPrint(char ch, int n) { while (n >0) { cout << ch; n--; } } What is k after invoking nPrint('a', k)? int k = 2; nPrint('a', k) ;

2 k is not changed after invoking nPrint('a', k). When invoking nPrint('a', k), k's value 2 is passed to n.

Show the output of the following code: #include <iostream> using namespace std; void increase(int x[], int size) { for (int i = 0; i < size; i++) x[i]++; } void increase(int y) { y++; } int main() { int x[] = { 1, 2, 3, 4, 5 }; increase(x, 5); int y[] = { 1, 2, 3, 4, 5 }; increase(y[0]); cout << x[0] << " " << y[0]; return 0; }

2 1 Invoking increase(x, 5) passes the array x to the function. Invoking increase(y[0]) passes the value 1 to the function. The value y[0] outside the function is not changed.

If you declare an array double list[] = {3.4, 2.0, 3.5, 5.5}, list[1] is ________.

2.0

Use the selectionSort function presented in this section to answer this question. Assume list is {3.1, 3.1, 2.5, 6.4, 2.1}, what is the content of list after the first iteration of the outer loop in the function?

2.1, 3.1, 2.5, 6.4, 3.1

What is the value of the following expression? static_cast<double> (5) / 2

2.5

How many elements are in array matrix[5][5]?

25

If you declare an array double list[] = {3.4, 2.0, 3.5, 5.5}, the highest index in array list is __________.

3

What will be displayed when the following code is executed? int number = 6; while (number > 0) { number -= 3; cout << number << " "; }

3 0

What is the output of the following program? #include <iostream> using namespace std; int main() { int values[2][4] = {{3, 4, 5, 1}, {33, 6, 1, 2}}; int v = values[0][0]; for (int row = 0; row < 2; row++) for (int column = 0; column < 4; column++) if (v < values[row][column]) v = values[row][column]; cout << v << endl; return 0; }

33 The code finds the largest element in the array and assigns it to v.

Suppose int[] list = {4, 5, 6, 2, 1, 0}, what is list[0]?

4

What is the output of the following code? #include <iostream> using namespace std; int main() { int matrix[4][4] = {{1, 2, 3, 4}, {4, 5, 6, 7}, {8, 9, 10, 11}, {12, 13, 14, 15}}; for (int i = 0; i < 4; i++) cout << matrix[1][i] << " "; return 0; }

4 5 6 7 matrix[1][0], matrix[1][1], matrix[1][2], and matrix[1][3] are displayed.

Assume the myList array has been declared. Based on the following loop, what is the value stored in myList[5]: for (int i = 0; i < 10; i++) { myList[i] = i; }

5

What will be displayed by the following code? #include <iostream> using namespace std; int main() { int data[][2][2] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}; cout << data[1][0][0] << endl; return 0; }

5

How many elements are in array double list[5]?

5 There are five elements in double list[5].

What is the output of the following program? #include <iostream> using namespace std; int m(int list[], int numberOfElements) { int v = list[0]; for (int i = 1; i < numberOfElements; i++) if (v < list[i]) v = list[i]; return v; } int main() { int values[2][4] = {{3, 4, 5, 1}, {33, 6, 1, 2}}; for (int row = 0; row < 2; row++) { cout << m(values[row], 4) << " "; } return 0; }

5 33 The m(list, numberOfElements) function returns the largest element in list. m(values[0], 4) returns 5 and m(values[1], 4) returns 33.

To create a C-string named city, which holds the value of "Austin" then XXX should be ___. Suppose char city [XXX] = "Austin";

7

What is wrong with the following code: void p(double x, double y) { cout << x << " " << y << endl; return x + y; }

A void function does not need a return statement, but if you include one, it cannot return a value. Use: return;

interpreter

Converts a program written in a higher level language into a lower level language and executes it, beginning execution before converting the entire program.

Suppose char city[7] = "Dallas"; what is the output of the following statement? cout << city;

Dallas city is a C-String.

What will be displayed by the following code? char s2[7] = "Dallas"; char s1[14] = "Dallas"; strcat(s1, s2); cout << s1;

DallasDallas

What is the output of following code? char city[] = "Dallas"; char s1[] = "Houston"; strncpy(s1, city, 3); cout << s1;

Dalston

The following is an example of a ____. int min(int num1, int num2) { int result; if (num1 < num2) result = num1; else result = num2; return result; }

Function definition

What is the output from the following code? #include <iostream> #include <string> using namespace std; int main() { string myExample = "HCC"; cout << myExample.at(0); }

H

If the following code is executed, what is the output if the user enters HAPPY HOLIDAYS? cout << Enter a string: "; char s[30]; cin >> s; cout << s << endl;

HAPPY

How many times is the following loop body repeated (i.e., how many iterations)? #include <iostream> #include <string> #include <iomanip> using namespace std; int main() { int i = 1; while (i < 10) if (i % 2 == 0) cout << i << endl; }

Infinite, because i never changes (no ++i)

Assume int myList[] = {10, 20, 30, 40}. What is myList[4]?

It is out of range and thus may result in a runtime error.

What is wrong with the following code: for (int i = 0; i < 10; i++) // Line 1 { // Line 2 cout << i << endl; // Line 3 } // Line 4 cout << i << endl; // Line 5

Line 5: You cannot print the value of i outside of the block it was defined

The speed of the CPU may be measured in ____

Megahertz and gigahertz

Does the return statement in the following function cause compile errors? void f() { int max = 0; if (max != 0) cout << max; else return; }

No It is rare, but sometimes useful to have a return statement for circumventing the normal flow of control in a void function.

Does the function call in the following function cause compile errors? #include <iostream> #include <cmath> using namespace std; int main() { pow(2.0,4); return 0; }

No. A function with a nonvoid return value type can also be invoked as a statement in C++. In this case, the caller simply ignores the return value. This is rare, but permissible if the caller is not interested in the return value.

Can you copy an array as follows: int x[] = {120, 200, 16}; int y[3]; y = x;

No. You have to copy each element from array x to array y.

If you read a string input: PROGRAMMING IS FUN using the following code, what will be the output? cout << "Enter a string: "; char s[30]; cin >> s; cout << s << endl;

PROGRAMMING

If you read a string input: PROGRAMMING IS FUN using the following code, what will be the output? cout << "Enter a string: "; char s[30]; cin.getline(s, 30, '\n'); cout << s << endl;

PROGRAMMING IS FUN

If the following code is executed, what is the output if the user enters SURPRISE? char s[30]; cout << "Enter a string: "; cin >> s; cout << s[2] << endl;

R

What will be displayed by the following code? char s2[7] = "Dallas"; char s1[14] = "Savannah"; strncat(s1, s2, 3); cout << s1;

SavannahDal

___ local variables are permanently allocated in the memory for the lifetime of the program.

Static

Which of the loop statements always has their body executed at least once?

The do-while loop

Function header

The function's return value type, function name, and parameters

hardware

The machines, wiring, and other physical components of a computer or other electronic system

Analyze the following code: #include <iostream> using namespace std; int xfunction(int n, long t) { cout << "int"; return n; } long xfunction(long n) { cout << "long"; return n; } int main() { cout << xfunction(5); return 0; }

The program displays long followed by 5.

Analyze the following code. #include <iostream> using namespace std; int m(int num) { return num; } void m(int num) { cout << num; } int main() { cout << m(2); return 0; }

The program has a compile error because the two functions m have the same signature. You cannot overload the functions based on the return type.

Analyze the following code: #include <iostream> using namespace std; int main() { int x[5]; int i; for (i = 0; i < 5; i++) x[i] = i; cout << x[i] << " "; return 0; }

The program may have a runtime error because the statement cout << x[i] << " " has the out of bound index on x[i]. After the for loop i is 5. x[5] is out of bounds. Note that the statement cout << x[i] << " " is not inside the loop.

Analyze the following: #include <iostream> using namespace std; int main() { int x[3]; cout << "x[0] is " << x[0]; return 0; }

The program runs, but since x[0] has not been initialized, an arbitrary value is printed.

(T/F) The switch-expression (in the parenthesis) must evaluate to an integral value (char, boolean, integer, etc.). The default case is optional, but can be used when none of the other cases match the switch-expression. The keyword break is optional. It immediately ends the switch. When the value in a case statement matches the value of the switch-expression, the statements starting from this case are executed until the end of the switch is reached or a break statement is reached.

True

(T/F) When declaring an array: elementType arrayName[SIZE]; SIZE must be a constant or an integer literal. For example: int myArray[10]; const int num = 5; int myArray[num];

True

C++ was developed by Bjarne Stroustrup during 1983-1985.

True

What is wrong with the following code: double myList[4]; myList = {1.9, 2.9, 3.4, 3.5};

When initializing arrays at the time of declaration, you must declare and initialize the array in one statement. Splitting it, as shown above, would cause a syntax error.

Example of Operating System

Windows XP

Write the definitions for three functions named max. Each receives two parameters of the same type and returns the larger of the two values. Define one of these functions to apply to type double, another to type int, and a third to type char.

double max(double a, double b) { if (a >= b) return a; else return b; } double max(int a, int b) { if (a >= b) return a; else return b; } double max(char a, char b) { if (a >= b) return a; else return b; }

What is the output from the following code?

double number = 12.34567; cout << fixed << setprecision(3) << number << endl;

Write the definition of a function named timeOnHighway that receives three parameters, all of type double: mileEndingPoint, mileStartingPoint, and speed . The first parameter indicates the mile marker on an interstate at which a vehicle goes to. The second parameter indicates the mile marker on an interstate at which a vehicle starts at. The third parameter indicates the speed of the vehicle in miles per hour. The function returns the number of hours it takes a vehicle to go from the starting mile marker to the ending one. The function has a default value for the speed: 55 miles per hour, and a default value for mileStartingPoint: 0.0.

double timeOnHighway (double mileEndingPoint, double mileStartingPoint = 0.0, double speed = 55.0) { return (mileEndingPoint - mileStartingPoint) / speed; }

{}

encloses a block of statements

storage device

external hardware used to store and retrieve data, such as a disk drive, CD/DVD drive, flash drive, or tape drive

Which of the following loops prints "Welcome to C++" 10 times?

for (int count = 1; count <= 10; count++) { cout << "Welcome to C++" << endl; }

Reversing the elements of an array involves swapping the corresponding elements of the array: the first with the last, the second with the next to the last, and so on, all the way to the middle of the array. Given an array a, an int variable n containing the number of elements in a, and two other int variables, k and temp, write a loop that reverses the elements of the array. Do not use any other variables besides a, n, k, and temp.

for (int k=0; k<n/2; k++){ temp=a[k]; a[k]=a[n-k-1]; a[n-k-1]=temp; }

#include <ctime> #include <cstdlib>

for time function for rand and srand function

Given two 2x3 (2 rows, 3 columns) arrays of int, x1 and x2, both already initialized, two int variables, i and j, and a bool variable x1Rules. Write the code that is necessary for x1Rules to be true if and only if every element in x1 is bigger than its corresponding element in x2 and is false otherwise.

for(int i = 0; i < 2; i++){ for(int j = 0; j < 3; j++){ if (x1[i][j] > x2[i][j]) x1Rules = true; else x1Rules = false; } }

Given two 3x3 arrays of integers, x1 and x2, write the code needed to copy every value from x1 to its corresponding element in x2.

for(int i = 0; i<3; i++){ for(int j = 0; j < 3; j++){ x2[i][j] = x1[i][j]; } }

The following is an example of a ____. answer = min(10, y);

function definition

The function header species the function's:

function name parameters return value type

The signature of a function consists of ____________.

function name and parameter list

C++ allows you to declare functions with the same name. This is called ________.

function overloading

What will be the output of the following code? #include <iostream> using namespace std; int j = 1; int main() { int i = 2; cout << "i is " << i << " j is " << j << endl; return 0; }

i is 2 j is 1

What will be the output of the following code? #include <iostream> using namespace std; int j = 1; int main() { int i = 2; int j = 2; cout << "i is " << i << " j is " << j << endl; return 0; }

i is 2 j is 2 The local variable j hides the global variable j.

A computer's native language, which differs among different types of computers is its ___ --- a set of built-in primitive instructions, such as 01010111.

machine language

The following program invokes p() three times. What is the output from the last call of p()? #include <iostream> using namespace std; int j = 40; void p() { int i = 5; static int j = 5; i++; j++; cout << "i is " << i << " j is " << j << endl; } int main() { p(); p(); p(); return 0; }

i is 6 j is 8

Data types

i.e. numbers and booleans

To create an object for reading data from file test.txt, use ___.

ifstream output("test.txt");

Which of the following is correct? int a[2]; int a[]; int a(2); int a();

int a[2];

Which of the following is correct? int a[]; int a[2]; int a(); int a(2);

int a[2];

Declare a two-dimensional array of int values named arr with 3 rows and 10 columns.

int arr[3][10];

Which of the following function declaration is correct? int f(int[][] a, int rowSize, int columnSize); int f(int a[][], int rowSize, int columnSize); int f(int a[][3], int rowSize); int f(int a[3][], int rowSize);

int f(int a[][3], int rowSize);

The header of the main function in C++ is __________.

int main()

Write the definition of a function oneLess , which receives an int parameter and returns an int that is one less than the value of the parameter. So if the parameter's value is 7 , the function returns the value 6 . If the parameter's value happens to be 44 , the functions returns the value 43 .

int oneLess(int amount) { return amount - 1; }

Display the calendar for a month, given the month and year (returning the year)

int printCalender(int month, int year)

Write the definition of a function signOf that receives an int parameter and returns -1 if the parameter is negative, returns 0 if the parameter is 0 and returns 1 if the parameter is positive. So, if the parameter's value is 7 or 803 or 141 the function returns 1 . But if the parameter's value is -22 or -57 , the function returns -1 . And if the parameter's value is 0 , the function returns 0 .

int signOf(int x) { if (x<0){return -1;} else if (x==0){return 0;} else {return 1;} }

Rewrite the following loop into a while loop. int sum = 0; for (int i = 0; i <= 4; i++) sum = sum + i;

int sum = 0, i = 0; while (i <= 4) { sum = sum + i; i++; }

Write a loop that reads positive integers from console input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out the sum of all the even integers read.

int sum = 0; int num = 1; while (num > 0){ cin >> num; if ((num % 2) == 0 && (num > 0)){ sum += num; } } cout << sum;

Declare a 3x3 two-dimensional array of int values named tictactoe.

int tictactoe[3][3];

Write the definition of a function twice , that receives an int parameter and returns an int that is twice the value of that parameter.

int twice(int n) { return 2*n; }

Declare an array of int values westboundHollandTunnelTraffic that can store the number of vehicles going westbound through the Holland Tunnel on a particular hour (numbered 0 through 23) on a particular day (numbered 0 through 6) on a particular week (numbered 0 through 51) over the last ten years (numbered 0 through 9). The innermost dimension should be years, with the next being weeks, and so on.

int westboundHollandTunnelTraffic [10][52][7][24];

Write a loop that reads positive integers from console input, printing out those values that are greater than 100, and terminates when it reads an integer that is not positive. The printed values should be separated by a single blank space.

int x; cin >> x; while (x > 0) { if (x > 100) cout << x << " "; cin >> x; }

Write a loop that reads positive integers from console input, printing out those values that are even, separating them with spaces, and that terminates when it reads an integer that is not positive. Declare any variables that are needed.

int x; cin >> x; while (x > 0) { if (x% 2 == 0) cout << x << " "; cin >> x; }

Given an int variable i, declare a reference variable r that is a reference to i.

int& r = i;

The following code displays ____. double temperature = 50; if (temperature >= 100) cout << "too hot" << endl; else if (temperature <= 40) cout << "too cold" << endl; else cout << "just right" << endl;

just right

Use a while loop to print a single line of 97 asterisks.

k = 0; while (k < 97) { cout << '*'; k++; }

What is k after the following block executes? { int k = 2; }

k is not defined outside the block.

Use the selectionSort function presented in this section to answer this question. What is list1 after executing the following statements? double list1[] = {3.1, 3.1, 2.5, 6.4}; selectionSort(list1, 4);

list1 is 2.5, 3.1, 3.1, 6.4

For the binarySearch function in this section, what is low and high after the first iteration of the while loop for the list {1, 4, 6, 8, 10, 15, 20} and key 11?

low is 4 and high is 6

machine code

machine-level instructions that are uniquely read by computer processors using patterns of 1s and 0s.

The missing function body in the following incomplete code should be ________. #include <iostream> using namespace std; int f(int number) { // Missing function body } int main() { cout << f(5) << endl; return 0; }

return number; This function has a return type int. It must return a value using the return statement.

A return statement is not needed for a void function, but it can be used for terminating the function and returning control to the function's caller. Which is an example of using the return statement in a void function:

return;

The ___ of a variable is the part of the program where the variable can be references.

scope

Rewrite the following if-else statement using a conditional (aka ternary operator): if (x > 10) score = 3 * scale; else score = 4 * scale;

score = (x > 10) ? 3 * scale : 4 * scale;

The ___ specifies the number of pixels in horizontal and vertical dimensions of the display device.

screen resolution

Which of these data types requires the least amount of memory? -float -double -short -int

short

What is the missing line if you want to generate a number between 0 and 9 and save it in the variable myRandomNum? ____________________________; int myRandomNum = rand() % 10?;

srand(time(0));

Write an expression that evaluates to true if the value of C-string lastName is greater than the C-string "Dexter".

strcmp(lastName, "Dexter") > 0

Write an expression that evaluates to true if and only if the C-string s equals the C-string " end".

strcmp(s, "end") == 0

Write an expression that evaluates to true if the value of the C-string s1 is greater than the value of C-string s2.

strcmp(s1, s2) > 0

<<

stream insertion operator

Declare an 8x8 two-dimensional array of strings named chessboard.

string chessboard[8][8];

Write a loop that reads strings from console input where the string is either "duck" or "goose". The loop terminates when "goose" is read in. After the loop, your code should print out the number of "duck "strings that were read.

string duck; string goose; string x; int count = 0; do { cin >> x; if (x < "goose") { count++; } } while (x < "goose"); cout << count;

To concatenate a number 1.5 with a string "Good" and assign the result to s, you write _________.

string s = to_string(1.5) + "Good";

Analyze the following code. void setChar(int i, char& ch, const string& s) { s[i] = ch; }

string s is a constant parameter and its content cannot be changed inside the function.

The ? mark in the following code should be replaced by ___________. #include <iostream> #include <cstring> using namespace std; int countLetters(const char s[]) { int count = 0; for (int i = 0; i < ?; i++) { if (isalpha(s[i])) count++; } return count; } int main() { // Prompt the user to enter a string cout << "Enter a string: "; char s[80]; cin.getline(s, 80); cout << "The number of letters in " << s << " is " << countLetters(s) << endl; return 0; }

strlen(s) See the strlen function in this section. strlen(s) returns the actual number of characters in string s.

return 0;

terminates the main() function

Function signature

the function name and parameter list

Declaring a variable

the part of the code that identifies the variable and the data type

An array is a data structure for storing a FIXED-size sequential collection of elements of ____.

the same type (all ints or all strings, etc...)

operating system

the software that supports a computer's basic functions, such as scheduling tasks, executing applications, and controlling peripherals.

Given int variables k and total that have already been declared, use a while loop to compute the sum of the squares of the first 50 counting numbers, and store this value in total. Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into total.

total = 0; k = 1; while (k <= 50) { total += k * k; k++; }

Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a while loop to compute the sum of the cubes of the first n counting numbers, and store this value in total. Thus if n equals 4 your code should put 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 into total.

total = 0; k = 1; while (k <= n){ total += k*k*k; k++; }

Suppose your function does not return any value, which of the following keywords can be used as a return type?

void

Write a function addOne that adds 1 to its int reference parameter. The function returns nothing.

void addOne(int& num){ num = num + 1; }

Write the header for a function addOne that accepts a single int reference parameter and returns nothing. Name the parameter x.

void addOne(int& x)


Kaugnay na mga set ng pag-aaral

Care and Prevention of Injuries Final

View Set

Chapter 17: Gene Expression: From Gene to Protein

View Set

Lesson 6: Life in Medieval Towns

View Set

AFPAAS Cor Quiz and Certification 2020

View Set

Methods Of Administering Medication

View Set