Computer Science 1428 Test 2

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

Squarecap Unit 6

A function is: Answer:a named collection of statements. used to break programs into manageable units, or modules. A function __________ contains the statements that make up the function. Answer: definition A function is executed when it is: called What is output when the following program is executed? void function1 () { cout << "Function 1 "; } int main () { cout << "Main "; function1 (); } Answer: Main Function 1 A(n) ______ produces a value that is passed to a function, and a(n) ______ is a variable that receives the value passed to the function. Answer: argument, parameter Given the following function definition void f(int x) { cout << x*2 << endl; } which of the following statements are valid function calls to this function? Answer: f(1); and f(x); //where x is a variable of type int Given the following function prototype void myFunction(double,string); which of the following statements are valid function calls to this function? Answer: myFunction(3.14,"Hello"); What is this? void power(int,int); Answer: a function prototype What is the output of the following program? void sequence(int count, char ch) { for (int i=0; i < count; i++) cout << ch; } int main() { int x = 2; char y = '!' sequence(4,'+'); sequence(x,y); } Answer: ++++!! What is the output of the following program? void f(char ch) { cout << ch; } void pl(int count) { for (int i = 0; i < count; i++) f('+'); } int main() { int x = 2; pl(3); f('*'); pl(x); } Answer: +++*++ What is the output of the following program? void doSomething(int num) { num = num + 1; cout << num << " "; } int main () { int x = 3; cout << x << " "; doSomething(x); cout << x << endl; } Answer: 3 4 3 What is output by the following function when called with this function call: func1(10); ? void func1(int m) { cout << m << " "; if (m < 25) return; cout << m+1 << " "; } Answer: 10 Given the following program: int cube(int x) { return x * x * x; } int main() { int result; //here } Which statement below can replace the comment //here in main, to call the cube function, passing the value 4 to it, and assigning the function's return value to result? Answer: result=cube(4); iven the following function definition: double half (double a) { return a/2; } which of the following is not a valid statement in main? Assume main contains: double x; Answer: cout << half(x); double w = half(x+100); double t = (37 * half(x)) / 3000; double u = half(half(x)); Based on the code in main, what should go in the blank to make the prototype correct? _____ func (int); int main() { int x = 10; if (func(x)) cout << "You passed." << endl; } Answer: bool During the execution of a function, a reference parameter, such as int &t, Answer: is an alias to the argument What is output by the following code? void func1 (int x) { x=57; } int main { int m = 25; func1(m); cout << "m is " << m <<endl; } Answer: m is 25 What is output by the following code? void func1 (int &x) { // Note & x=57; } int main { int m = 25; func1(m); cout << "m is " << m <<endl; } Answer: m is 57 What is output by the following code? void calc (int a, int& b) { int c; c = b + 1; a = a * 3; b = c + a; } int main() { int x = 2, y = 5; calc(x, y); cout << x << " " << y << endl; } Answer: 2 12 A _______ is declared outside of all functions. Answer: global variable This type of variable is defined inside a function and is not accessible outside the function Answer: local variable Given the program below, which variables could have the same name (without causing a compiler error)? void f (int a, int& b) { int c; c = a + b; } int g (int d) { int e; e = d*2; return e; } int h (int i) { return 2*i; } int main() { ... } Answer: c and e

Top Down Design

A software development technique that imposes a hierarchical structure on the design of the program. It starts out by defining the solution at the highest level of functionality and breaking it down further and further into small routines that can be easily documented and coded (The Free Dictionary: top-down programming). Also known as: ~divide and conquer ~stepwise refinement ~structured programming Complex problems can be solved using top-down design, where ~We break the problem into a sequence of smaller tasks ~Then break the sub-tasks into tasks ~Soon, each of the tasks will be easy to do Advantages to top down design: ~Breaking the problem into parts helps us to clarify what needs to be done. ~At each step of refinement, the new parts become less complicated and, therefore, easier to figure out. ~Parts of the solution may turn out to be reusable. ~Breaking the problem into parts allows more than one person to work on the solution. Top Down Design usually results in a hierarchy chart that describes the tasks that must be accomplished. Each "leaf" task is a module (often implemented using a function). Once you have the tasks listed, you can start coding each one, and then adding code to sequence them correctly.

Keeping a running total (summing)

After each iteration of the loop, it stores the sum of the numbers added so far (running total) set an accumulator variable to 0 add the next number to it inside the loop int days; //Count for count-controlled loop float total = 0.0; //Accumulator float miles; //daily miles ridden cout << "How many days did you ride your bike? "; cin >> days; for (int i = 1; i <= days; i++) { cout << "Enter the miles for day " << i << ": "; cin >> miles; total = total + miles; } cout << "Total miles ridden: " << total << endl;

do-while

Always do at least once, good for: ~repeating on user request, simple menu processing , menus, repeating a process a 'post-test' loop executes at least once use when the code in the loop must be executed at least one time test a condition at the 'bottom' to determine whether or not to continue the loop general form: do statement while (expression);

Passing entire arrays to functions

An array element can be passed by reference. An entire array can(!) be passed to a function that has an array parameter In the function definition, the parameter type is a variable name with an empty set of brackets: [ ] ~Do NOT give a size for the parameter void showArray(int values[ ], int size) {...} In the prototype, empty brackets go after the element datatype. void showArray(int[ ], int); In the function call, use the variable name for the array (no brackets!). showArray(numbers, 5); An array is always passed by reference. The parameter name is an alias to the array being passed in, even though it has no &. Changes made to the array (elements) inside the function DO affect the array in the function call. Usually functions that have an array parameter also have an int parameter for the count of the number of elements in the array. ~so the function knows how many elements to process. The count parameter is just a regular int parameter and must be included in the parameter list and a corresponding argument value must appear in the function call.

Passing array elements to functions

An array element can be passed to any parameter of the same (or compatible) type: double square (double); int main() { double numbers[5] = {2.2, 3.3, 5.11, 7.0, 3.2}; for (int i=0; i<5; i++) cout << square(numbers[i]) << " "; cout << endl; return 0; } double square (double x) { return x * x; }

Array declaration/definition

Array: a variable that contains multiple values of the same type. Values are stored consecutively in memory. size declarator must be a constant (in the C++ standard) An array variable declaration statement in C++: int numbers[5]; This creates an array called numbers which contains 5 integer values (ints). numbers is the name of the array int is the data type of the array elements 5 is the size declarator: ~the number of elements (values) in the array The size declarator must be an integer and a constant. ~it must be greater than 0 ~IT CANNOT BE A VARIABLE!* It can be a literal or a named constant. const in SIZE = 40; double grades[SIZE]; Named constants ease program maintenance when the size of the array must be changed.

Lack of bounds checking

C++ does not check it to make sure an array subscript is valid (between 0 and size-1) If you use a subscript that is outside the bounds of the array you may not get a warning or error. You may unintentionally change memory allocated to other variables. const int SIZE = 3; int values[SIZE]; for (int i=0; i < 5; i++) { values[i] = 100; }

Reading data from a file of unknown length

Can test a file stream variable as if it were a boolean variable to check for various errors. After opening a file, if the open operation failed, the value of file stream variable is false. ifstream infile; infile.open("test.txt"); if (!infile) { cout << "File open failure!"; return 1; //abort program! } Note: after ANY input operation, if it fails, the value of file stream variable will then be false. Use fin>>x; in a loop Problem: when to stop the loop? First entry in file could be count of number of items ~problems: maintenance (must update it whenever data is modified), large files (might be hard to count) Could use sentinel value ~problem: may not be one (every value is valid), maintenance (someone might delete it) Want to automatically detect end of file stream extraction operation (>>) returns true when a value was successfully read, false otherwise int num; ifstream inputFile; inputFile.open("numbers.txt"); bool foundValue = (inputFile >> num); inputFile >> num: ~tries to read a value into num ~if it was successful, result is true (foundValue is true) ~if it failed (non-number char or no more input), result is false (foundValue is false, but the value in num does not change!)

Function prototype

Compiler must know the following about a function before it can process a function call: ~name, return type and ~data type (and order) of each parameter Not necessary to have the body of the function before the call. Sufficient to put just the function header before all functions containing calls to that function ~The complete function definition must occur later in the program. ~The header alone is called a function prototype Place prototypes near the top of the program (before any other function definitions)--good style. Using prototypes, you can place function definitions in any order in the source file Common style: all function prototypes at beginning, followed by definition of main, followed by other function definitions.

Counters/count controlled loop

Counter: a variable that is incremented (or decremented) each time a loop repeats. Used to keep track of the number of iterations (how many times the loop has repeated). Must be initialized before entering loop!!!! int number; int count = 0; cout << "Enter a number between 1 and 10: "; cin >> number; while (number < 1 || number > 10) { count = count + 1; cout << "Please enter a number between 1 and 10: "; cin >> number; } cout << count << " invalid numbers were entered." << endl; // Do something with number here Conditional loop: body executes as long as a certain condition is true ~input validation: loops as long as input is invalid Count-controlled loop: body executes a specific number of times using a counter ~actual count may be a literal, or stored in a variable. Count-controlled loop follows a pattern: ~initialize counter to zero (or other start value). ~test counter to make sure it is less than count. a 'pre-test' loop used when the number of repetitions is known in advance ~update counter during each iteration

Array elements

Each element of the array has a unique subscript (or index) that indicates its position in the array. The subscripts are 0-based ~the first element has subscript 0 ~the second element has subscript 1 ~ . . . ~the last element has subscript (size -1) Given this array declaration: int numbers[5]; ~The syntax to access one element is: numbers[2] //the third element of numbers array ~Pronounced "numbers at 2" or "numbers sub 2" The subscript is ALWAYS an integer ~regardless of the type of the array elements. ~the subscript can be ANY integer expression literal: 2 numbers[2] variable: i numbers[i] expression: (i+2)/2 numbers[(i+2)/2] We can use a for loop to input into the array The subscript/index can be the loop variable: const int NUM_SCORES = 7; int scores[NUM_SCORES]; cout << "Enter the " << NUM_SCORES << " programming assignment scores: " << endl; for (int i=0; i < NUM_SCORES; i++) { cin >> scores[i]; } i starts at 0, the first valid subscript loop ends when i is 7, the first invalid subscript We can also use a for loop to output the elements of the array: const int NUM_SCORES = 7; int scores[NUM_SCORES]; cout << "Enter the " << NUM_SCORES << " programming assignment scores: " << endl; for (int i=0; i < NUM_SCORES; i++) { cin >> scores[i]; } cout << "You entered these values: "; for (int i=0; i < NUM_SCORES; i++) { cout << scores[i] << " "; } cout << endl;

Infinite loops

Examples: int x=1; while (x<=5){ cout << "repeat " ; } cout << "Done!" << endl; int x=1; while (x<=5) cout << "Repeat " ; x=x+1; cout << "Done!" << endl;

Function call

Function call: statement (or expression) that causes a function to execute function-name (arguments) To execute the statements in a function, you must "call" it from within another function (like main). To call a function, use the function name followed by a list of expressions (arguments) in parens: printHeading(); Whenever called, the program executes the body of the called function (it runs the statements). After the function terminates, execution resumes in the calling function after the function call A program is a collection of functions, one of which must be called "main". Function definitions can contain calls to other functions. A function must be defined before it can be called ~In the program text, the function definition must occur before all calls to the function ~Unless you use a "prototype"

Function definition

Function definition: statements that make up a function, along with its name, parameters and return type. return-type function-name (parameters) { statements } ~return type: data type of the value that the function returns to the part of the program that called it. ~function-name: name of the function. Function names follow same rules as variables. ~parameters: optional list of variable definitions. These will be assigned values each time the function is called. ~body: statements that perform the function's task, enclosed in { }.

Processing arrays

Given the following array definition: double tests[10]; the expression test[i] may be used exactly like any variable of type double. tests[i] tests[0] = 79; cout << tests[0]; cin >> tests[1]; tests[4] = tests[0] + tests[1]; Generally there are NO operations that you can perform over an entire array. Some operations may appear to work (no errors) but you don't get the desired results. We can use a for loop to sum the elements of the array (the running total) const int NUM_SCORES = 7; int scores[NUM_SCORES]; cout << "Enter the " << NUM_SCORES << " programming assignment scores: " << endl; for (int i=0; i < NUM_SCORES; i++) { cin >> scores[i]; } int total = 0; //initialize accumulator for (int i=0; i < NUM_SCORES; i++) { total = total + scores[i]; } We can use a for loop to find the max value: • Note: keep track of the maximum value encountered so far (the running maximum) const int NUM_SCORES = 7; int scores[NUM_SCORES]; cout << "Enter the " << NUM_SCORES << " programming assignment scores: " << endl; for (int i=0; i < NUM_SCORES; i++) { cin >> scores[i]; } int maximum = scores[0]; //init max to first elem for (int i=1; i < NUM_SCORES; i++) { //start i at 1 if (scores[i] > maximum) maximum = scores[i]; //save the new maximum } // no else needed To copy/assign one array to another, you must assign element by element. const int SIZE = 4; int values1[SIZE] = {100, 200, 300, 400}; int values2[SIZE]; // values2 = values1; WRONG, won't work correctly for (int i = 0; i < SIZE; i++) { values2[i] = values1[i]; } Note: this also does not work: values2 = {3,6,9,27}; //only works for initialization

for loop

Initialize/test/update, good for: ~count-controlled loops, init; test; update ‣ all are optional general form: for (expr1; expr2; expr3) statement

while loop for input validation

Inspect user input values to make sure they are valid. If not valid, ask user to re-enter value: int number; cout << "Enter a number between 1 and 10: "; cin >> number; while (number < 1 || number > 10) { cout << "Please enter a number between 1 and 10: "; cin >> number; } // Do something with number here

Modular Programming

Modular programming: breaking a program up into smaller, manageable components (modules) Function: a collection of statements that perform a task, grouped into a single named unit. Why is modular programming important? ~Improves maintainability/readability of programs by giving structure and organization to the code ~Simplifies the process of writing programs: programmer can write one small function at a time

Pass by reference

Pass by reference: when an argument is passed to a function, the function has direct access to the original argument. Pass by reference in C++ is implemented using a reference parameter, which has an ampersand (&) in front of it: void changeMe (int &myValue); A reference parameter acts as an alias to its argument. Changes to the parameter in the function DO affect the value of the argument void Changes made to a reference parameter are actually made to its argument The & must be in the function header AND the function prototype. The argument passed to a reference parameter must be a variable - it cannot be a constant or contain an operator (like +) Use when appropriate - don't use when: ~the argument should not be changed by function (!) ~the function returns only 1 value: use return stmt!

Pass by value

Pass by value: when an argument is passed to a function, its value is copied into the parameter. Parameter passing is implemented using variable initialization (behind the scenes): int param = argument; Changes to the parameter in the function definition cannot affect the value of the argument in the call When the argument is a variable (as in f(x)): The parameter is initialized to a copy of the argument's value. Even if the body of the function changes the parameter, the argument in the function call is unchanged. The parameter and the argument are stored in separate variables, separate locations in memory

Sentinel controlled loop

Sentinel: special value in a list of values that indicates the end of the data sentinel value must not be a valid value! -99 for a test score, -1 for miles ridden User does not need to count how many values will be entered Requires a "priming read" before the loop starts ~so the sentinel is NOT included in the sum ~the loop can be skipped (if first value is the sentinel) float total = 0.0; //Accumulator float miles; //daily miles ridden cout << "Enter the miles you rode on your bike each day, "; cout << "then enter -1 when finished. " << endl; cin >> miles; //priming read while (miles != -1) { total = total + miles; //skipped when miles==-1 cin >> miles; //get the next one } cout << "Total miles ridden: " << total << endl;

Breaking and Continuing

Sometimes we want to abort (exit) a loop before it has completed. The break statement can be used to terminate the loop from within: cout << "Guess a number between 1 and 10" << endl; int number; while (true) { cin >> number; if (number == 8) break; } cout << "You got it." << endl; Don't do this. It makes your code hard to read and debug Sometimes we want to abort an iteration (skip to the end of loop body) before it is done. The continue statement can be used to terminate the current iteration: for (int i=1; i <= 6; i++) { if (i == 4) continue; cout << i << " "; } Output: 1 2 3 5 6 Don't do this either. It makes your code hard to read and debug.

while loop

Test at start of loop, good for: ~validating input, sentinel controlled loops, etc a 'pre-test' loop executes zero or more times use when the number of repetitions is not known in advance test a condition at the 'top' to determine whether or not to continue the loop general form: while (argument) statement

Debugging

Test failure: actual output from running a test case does not match the expected output. Debugging: figure out why it failed, find the coding mistake and fix it. Add output statements in strategic places: ~cout the values of variables (label them!) ~trace execution path, see which statements are being reached. Add cout<<"here1"<<endl; statements periodically in your program.

Testing

Testing: running the program with simulated data, checking the actual output against expected output, in order to find bugs Bug: coding mistake causing an error in output Test Case: a set of specific input data and the corresponding expected program output Choose input data wisely: ~Values used in if/while conditions ~Smallest and largest valid values of a dataset ~Put data in multiple positions: for maximum, put max value in first position, then last position, then middle position

Scope and Lifetime

Variables defined inside a function are local to that function. ~They are hidden from the statements in other functions, which cannot access them. Because the variables defined in a function are hidden, other functions may have separate, distinct variables with the same name. ~This is not bad style. These are easy to keep straight Parameters are also local to the function in which they are defined. A function's local variables and parameters exist only while the function is executing. When the function begins, its parameters and local variables (as their definitions are encountered) are created in memory, and when the function ends, the parameters and local variables are destroyed. This means that any value stored in a local variable is lost between calls to the function in which the variable is declared. A global variable is any variable defined outside all the functions in a program. The scope of a global variable is the portion of the program starting from the variable definition to the end of the file This means that a global variable can be accessed by all functions that are defined after the global variable is defined A local variable may have the same name as a global variable. The global variable is hidden in that variable's block. Do not use global variables!!! Because: They make programs difficult to debug. ~If the wrong value is stored in a global var, you must scan the entire program to see where the variable is changed Functions that access globals are not selfcontained ~cannot easily reuse the function in another program. ~cannot understand the function without understanding how the global is used everywhere It is ok (and good) to use global constants because their values do not change.

Squarecap Unit 5

What does the following C++ statement do, when executed? float x[10]; Answer: Creates a variable named x that can store 10 different float values. What will the following code display when executed? int numbers[5] = {99, 87, 66, 55, 101}; cout << numbers[2] << endl; Answer: 66 What is the subscript of the last element in the following array? int values[10]; Answer: 9 What will be output by the following code? int numbers[ ] = {99, 87, 66, 55, 101}; for (int i=1; i < 4; i++) cout << numbers[i] << " "; Answer: 87 66 55 What will fix the error in the following code, which copies the elements from arrayB to arrayA? int arrayA[3]; int arrayB[3] = {3,6,9}; arrayA = arrayB; Answer: arrayA=arrayB should be arrayA[0]=arrayB[0]; arrayA[1]=arrayB[1]; arrayA[2]=arrayB[2]; What is output by the following statements? int z[ ] = {11, 12, 13, 15, 14, 10}; int m = z[0]; for (int i=1; i<5; i++) { if (z[i] < m) m = z[i]; } cout << "It's " << m << endl; Answer: It's 11

Squarecap Unit 4

What is output when the following code is executed? int x = 0; while (x <= 5) { cout << x << "!"; x = x + 2; } Answer: 0!2!4! What is output when the following code is executed? int x = 7; while (x <= 5) { cout << "Repeat " ; x = x + 1; } cout << "Done!" << endl; Answer: Done! What is output when the following code is executed? int x = 7; do { cout << "Repeat " ; x = x + 1; } while (x <= 5); cout << "Done!" << endl; Answer: Repeat Done! What will be output when the following code is executed? for (int x=1; x <= 5; x++) { cout << "One "; } cout << "Done!" << endl; Answer: One One One One One Done! How many times will the following loop display "Hello"? for (int i=0; i<=20; i++) cout << "Hello!" << endl; Answer: 21 What goes in the blanks to make this for loop sum the values 1..n? int n, x = 0; cout << "Enter a positive number: "; cin >> n; for (int count = 1; __________; count++) _______________ cout << x << endl; Answer: count <= n and x = x+count; A special value that marks the end of a list of values is a---sentinel What two elements are needed to calculate the total of a series of numbers? Answer: A loop and a variable that accumulates the total The valid range of values for integer variable x is described by this relational expression: -10<=x && x<=10. Which of the following integer values could be used as a sentinel value when inputting a value for x in a loop? Answer: 50 What is wrong with the following loop that attempts to sum the numbers from 1 to n? int total; for (int i=1; i<=n; i++) total = total + i; cout << "The sum is " << total << e Answer: int total; should be int total = 0; What does the following code do when executed? for (int i=1; i<=10; i++) for (int j=1; j<=4; j++) cout << "*"; Answer: Outputs 40 stars all on one line What code should go in the blank in order to store a count of the numbers in the file in the count variable? int number, count=0; ifstream fin; fin.open("numbers.txt"); while (__________________) { count++; } Answer: fin>>number

Nested loops

When one loop appears in the body of another For every iteration of the outer loop, we do all the iterations of the inner loop Example from "real life": ~Print a bar graph ~Calculate grades for a class

Array initialization

You can initialize arrays when they are defined. const int NUM_SCORES = 3; float scores[NUM_SCORES] = {86.5, 92.1, 77.5}; • Values are assigned in order: scores[0] = 86.5 scores[1] = 92.1 scores[2] = 77.5 NOTE: uninitialized arrays have GARBAGE values stored in them (not necessarily 0). When you initialize, you don't need to specify a value for every position. float scores[7] = {86.5, 92.1, 77.5}; In this case, the first 3 elements are initialized to the specified values. The uninitialized values WILL be set to 0!!!! 86.5 92.1 77.5 0 0 0 0 When you initialize, you don't need to specify the size declarator. float scores[] = {86.5, 92.1, 77.5}; In this case, the compiler determines the size of the array from the number of elements listed. 86.5 92.1 77.5

Function parameters and arguments

You can pass (or send) values to a function in the function call statement. This allows the function to work over different values each time it is called. Arguments: Expressions (or values) passed to a function in the function call. Parameters: Variables defined in the function definition header that are assigned the values passed as arguments. void displayValue(int num) { cout << "The value is " << num << endl; } num is the parameter. Calls to this function must provide an argument (expression) that has an integer value: displayValue(5); 5 is the argument.

The return statement

return; Used to stop the execution of a void function Can be placed anywhere in the function body ~the function immediately transfers control back to the statement that called it. Statements that follow the return statement will not be executed In a void function with no return statement, the compiler adds a return statement before the last } You can use the return statement in a non-void function to send a value back to the function call: return expr; The value of the expr will be sent back. The data type of expr must be placed in the function header: (return type) int doubleIt(int x) { (value being return) return x*2; } If the function returns void, the function call is a statement: pluses(4); If the function returns a value, the function call is an expression: int y = doubleIt(4); When a function call calls a function that returns a value, it is an expression. The function call can occur in any context where an expression is allowed: ~assign to variable (or array element) total = sum(x,y); ~output via cout cout << sum(x,y); ~use in a more complicated expression cout << sum(x,y)*.1; ~pass as an argument to another function z = pow(sum(x,y),2); The value of the function call is determined by the value of the expression returned from the function.


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

MSK/Rheumatology Practice Q's (Exam 2)

View Set

Prejudice vocab, practice, and quiz

View Set

Amino Acids, Peptides, and Protein Structures

View Set

Bases socioculturales de la conducta humana

View Set