goal 6 and 7

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

BEST PRACTICE- use ______ ____ ________ when they simplify your loop logic. Its recommended not to use break and continue in loops because it causes execution flow to jump around and can make flow of logic harder to follow (break in middle of complicated logic could be missed or may not be obvious under what conditions it should be triggered). Break and continue can help make loops more readable by keeping number of nested blocks down and reducing need for complicated looping logic.

break and continue

causes while loop, do-while loop, for loop, or switch statement to end, with execution continuing with the next statement after loop or switch. break; is used to end a case and prevents fall through into the subsequent case.

break statement

break statement terminates the switch or loop, and execution continues at the first statement beyond the switch or loop. Return statement terminates the entire function that the loop is within, and execution continues at point where function was called.

break vs return

can be used to get out of intentional infinite loop: if (num == 0) break;

breaking a loop

function being called return-type identifier() //function header { //function body }

called (callee) function

function initiating the function call

caller

is called implicitly when main() ends. Can be called explicitly to halt program before it would normally terminate with #include <cstdlib> WARNING- std::exit() does NOT clean up local variables in current function or up the call stack. Its best to AVOID calling std::exit()

calling std::exit() explicitly

BEST PRACTICE- define local variables as _____ to their first use as reasonably possible. std::cout << "Enter an integer: "; int x{}; std::cin >> x;

close

Loops are control flow __________ that allow code to execute repeatedly until some ________ is met and add flexibility to the programming toolkit.

constructs, condition

provides convenient way to end current iteration of a loop without terminating entire loop. Causes current point of execution to jump to bottom of current loop. A for loops end-statement still executes after a continue. With thile or do-while loops the value of the variable changes when used in the condition inside the loop body. If continue statement causes lines to be skipped then the loop may be infinite.

continue statement

______: statement that tells the compiler about existence of an identifier and its type information. Need to satisfy compiler. Definitions serve as declarations. int add(int x, int y); - Tells compiler about function named "_____" that takes two int parameters and returns an int int x; - Tells compiler about integer variable x

declaration, add

implements (for function or types) or instantiates (for variables) the identifier. Needed for the linker.

definition

looping construct similar to while loop, except the statement executes always at least once. Once executed, the do-while loop checks the condition. If true, execution jumps to the top of the do-while loop and executes again. Can be useful to avoid magic numbers and additional variables. Aren't commonly used, having the condition at the bottom of the loop obscures the loop condition, leading to errors. Utilized for faulty input from user in a loop. do statement; while (condition);

do while statement

return statement that is not the last statement in a function (many believe this should be AVOIDED).

early return

return statement that is not the last statement in a function, causes function to return to caller when return statement is executed (can be used in value-returning functions)

early return

init-statement is executed once the loop is initiated (used for variable definition and initialization). The variables have "loop scope", form of block scope where these variables exist from point of definition through end of the loop statement. Then for each loop iteration, the condition is evaluated (if true statement executes or if its false the loop terminates and execution continues with next statement after the loop. Finally, statement is executed and end-expression is evaluated (used to increment/decrement loop variables defined in init-statmeent) which returns to the second step.

evaluation of for statements

BEST PRACTICE- when addressing compile errors in your program, resolve the _____ error produced then compile again. To fix these errors you can ______ the function definitions or use a forward declaration.

first, reorder

BEST PRACTICE- avoid this form of for loops ( ______ and use while(true) instead

for ( ; ; )

defining multiple variables in the init-statement with a comma operator to change the value of multiple variables in end-expression: for (int x{ 0 }; y{ 9 }; x < 10; ++x, -y) std::cout << x << ' ' << y << '\n';

for loops with multiple counters

most commonly used loop statement and allows us to define, initialize, test, and change the value of loop variables. There are two types: for statements and range-based for statements. For statement: for (init-statement; condition; end-expression) statement; For statement converted to while statement: { init-statement; while (condition) { statement; end-expression; } }

for statement (for loop)

__________ are best used with counter variable or a while statement

for statements

for each cases where we want to iterate through every element in an array (or other list-type structure). When the statement is encountered the loop will iterate through each element in an array assigning the value of the current array element tot he variable declared in element_declaration (has same type as the array elements for type conversion) for (element_declaration : array) statement;

for-each loop (range-based for-loop)

works with fixed arrays and many kinds of list-like structure (vectors, linked lists, trees, and maps). For each loops provide flexible and generic way to iterate through more than just arrays

for-each loop and non-arrays

BEST PRACTICE- in _________ element declarations, if your elements are non-fundamental type, use _________ or const references for performance reasons.

for-each loops, references

tells compiler about existence of identifier before defining the identifier. Allows us to tell compiler this before defining the function body. When compiler encounters a call to the function it understands were making a function call and can check to ensure were calling the function correctly.

forward declaration

If a _______ _______ is made but the function is never called, the program will compile and run fine but if it is called the program never defines the function, the program will compile but ______ cant resolve function call. Forward declarations can be used with other identifiers in C++ (variables and user-defined types)

forward declaration, linker

curly braces and statements in-between, where statements that determine what function does. WARNING- include parentheses() after the function's name when making a function call.

funciton body

Functions calling functions calling functions- any ______ can call any other _______

function

reusable sequence of statements designed to do a specific job. Executable programs must have a function named main. As code gets longer, putting all code here becomes hard to manage. Functions provide a way to split our programs into small, modular chunks for organization, testing, and use.

function

expression that tells CPU to interrupt current function and execute another function. CPU "puts bookmark" at current point of execution, then calls (executes) the function named in the function call. When the function ends, the CPU returns back to the point it bookmarked, and resumes execution.

function call

(function prototype)- statement used to write forward declaration for a function (consists of function header- function return type, name, and parameter type), terminated with semicolon. Function body is not included in declaration int add(int x, int y);

function declaration

tells compiler about existence of function, what function is called, and other information

function header

variable used in function. Works similarly to variables defined inside function, but they are always initialized with value provided by caller of function.Defined in function header by placing them in between parentheses after function name, with multiple parameters being separated by commas.

function parameter

KEY INSIGHT- names used for ________ or variables declared in function body are only visible within function that _____ them. Local variables within a function can be named without regard for names of variables in other functions (keeps functions independent).

function parameters, declares

BEST PRACTICE- _______ function should return the value 0 if the program ran normally. Non-zero status code indicates ______

main(), failure

__________ the number of variables used and keeping number of nested blocks down improves code comprehension more than break or continue harms it.

minimizing

In ________ programs, calling std::exit() can cause your program to crash (because the thread calling std::exit() will cleanup static objects that may still be accessed by other threads). For this reason, C++ has introduced another pair of functions that work similarly to std::exit() and std::atexit() called std::quick_exit() and std::at_quick_exit(). std::quick_exit() terminates the program normally, but does not clean up static objects, and may or may not do other types of cleanup. std::at_quick_exit() performs the same role as std::atexit() for programs terminated with ___________

multi-threaded, std::quick_exit().

for ( ) { //text for ( ) //text } }

nested for loops

for each iteration of the outer loop, the body of the outer loop executes once. Outer loop body contains inner loop (executed for each iteration of outer loop).

nested loops

BEST PRACTICE- make sure function with _______ return value in all cases. Failure to return a value from value-returning will cause undefined behavior.

non-void

program has exited in an expected way, doesnt imply success. std::exit is a function that causes the program to terminate normally and performs cleanup functions (objects with static storage are destroyed then file cleanup is done and control is returned back to the OS, with the argument passed to std::exit() used as the status code.

normal termination

occur when the loop iterates too many/ few times, caused by incorrect relational operators or using pre-decrement instead of post-decrement and vice-versa

off-by-one errors

for loops that omit any or all statements or expressions EXAMPLES: for ( ; count < 10; ) //no init-statement of end-expression Does a manual initialization and incrementing for (; ;) statement; Creates an infinite loop while (true) statement; Creates an infinite loop as well

omitted expressions

___ ____ _____- 1. Within a given _____, a function, variable, type, or template can only have one definition. 2. Within a given program, a variable or normal function can only have one definition. This distinction is made because programs can have more than one file (we'll cover this in the next lesson). 3. Types, templates, _____ functions, and inline variables are allowed to have identical definitions in different files. int add(int x, int y) //implements function add() { int z{ x + y }; // instantiates variable z return z; }

one definition rule, file, inline

New programmers often combine calculating a value and printing the calculated value into a single function. However, this violates the "_____" rule of thumb for functions. A function that calculates a value should return the value to the caller and let the caller decide what to do with the calculated value (such as call another ______ to print the value).

one task, function

______: determines where the identifier can be accessed within source code. Compile-time property, trying to use an _______ when it is out of scope results in compile error. Local variables scope begins at point of variable definition and stops at end of set curly braces where it is defined (for function parameters, at end of function). Ensures variables can not be used before point of definition, local variables defined in one function are not in scope in other functions that are called.

scope, identifier

Loop Variables should be ______- unsigned integers can lead to unexpected issues BEST PRACTICE- loop variables should be of type (signed) int.

signed

Functions can only return _____ value- returned to caller each time it's called, value in return statement does NOT need to be ______, can be result of any valid expression, including variable or even call to another function that returns value.

single, literal

History lesson- before C++ had support for namespaces, all names that are now is std namespace were in global namespace. This caused naming collisions between program identifiers and standard library identifiers. Programs working under one version of C++ might have a naming conflict with new version of C++. In 1995 namespaces were ________ and all functionality from standard library was moved out of global namespace to _______ ______ (this broke older code that was using names without std::

standardized, namespace std

Function main implicitly returns 0 if no _______ is provided- exception to this rule: value-returning function must return a value via return statement is for main(). _______ return value from main to show intent and for consistency with other functions

statement, explicitly

______ (exit code or return code)- indicated whether program executed successfully.

status code

_________ specifies function that will automatically be called on program termination through std::exit(). Allows you to specify cleanup function in one place (usually ______). A few notes here about std::atexit() and the cleanup function: First, because std::exit() is called implicitly when main() terminates, this will invoke any functions registered by std::atexit() if the program exits that way. Second, the function being registered must take no parameters and have no return value. Finally, you can register multiple _________ functions using std::atexit() if you want, and they will be called in reverse order of registration (the last one registered will be called first).

std::atexit, main, cleanup

Typically, when learning C++, you will write a lot of programs that involve 3 ______: Reading inputs from the user Calculating a value from the inputs Printing the ________ value (For trivial programs (e.g. less than 20 lines of code), some or all of these can be done in function ____. However, for longer programs (or just for practice) each of these is a good candidate for an individual function.)

subtasks, calculated, main

name that does NOT include scoping qualifier ( cout and x are examples with no associated scope)

unqualified name

functions you write yourself, similar to a bookmark

user-defined functions

return-type identifier() { //code here } Functions are not required to return ______ back to caller, to tell compiler that a function does NOT return a value the ____ return type is used. Main calls the void then control returns to main and program proceeds. Void function automatically returns to caller at end of function (NO return statement is required).

value, void

function that returns value, function is value-returning if return type is anything other than void and must return a value of that type.

value-returning function

BEST PRACTICE- - Prefer for loops over while loops when there is an obvious loop _________. - Prefer _________ over for loops when there is no obvious loop variable.

variable, while loops

BEST PRACTICE- defining multiple _________ (in the init-statement) and using the comma operator (in the ____________) is acceptable inside for statement

variables, end-expression

_________ can NOT be used in expression that requires a value- Some statements require values to be provided and others dont. When calling a function by itself we call a function for its behavior not its return value. We can call a non-value returning function or call a value-returning function and ignore return value. When calling a function in context that requires a _______, a value must be provided (can only call value-returning functions).

void functions, value

Returning a value from a _____ function is a compile error- trying to return a value from a non-value returning function results in error void printHi() //function is non-value returning { std::cout << "In printHi()" << '\n'; return 5; } OUTPUT: ______

void, error

while loops, simple loop type in C++. Declared using while keyword, when executed the condition is evaluated, if true the statement executes. Unlike if statements, once the statement is executed control returns to the top of the while statement and the process repeats as long as the statement is true. while (condition) statement;

whiile statement

BEST PRACTICE- favor _____ loops over do-while

while

BEST PRACTICE- favor ______(_____) for intentional infinite loops

while(true)

BEST PRACTICE- avoid operator ___ when doing numeric comparisons in the for-loop condition

!=

used for including fixed-width integers

#include<cstdint>

used for element_declartion with same type as array elements, C++ deduced type of the array elements constexpr int fibonacci[]{ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 }; // type is auto, so number has its type deduced from the fibonacci array for (auto number : fibonacci)

auto keyword

every time you use operator __ or operator>> to do input or output, you're using a function provided by the ______ library

<<, standard

C++ standard defines 3 status codes: 0, EXIT________, and EXIT_________. C++ disallows calling the ______ function explicitly, define main function at bottom of code file.

SUCCESS, FAILURE, main

program had some kind of unusual runtime error and the program couldn't continue to run. std::abort() function causes program to terminate abnormally. std::terminate() function used in conjunction with "exceptions" and can be called explicitly (mostly called implicitly when an exception isnt handled). By default std::terminate() calls std::abort()

abnormal termination

value passed from caller to function when function call is made

argument

One of the biggest challenges new programmers encounter (besides learning the language) is understanding when and how to use functions effectively. Here are a few basic guidelines for writing functions: - Groups of statements that appear more than once in a program should generally be made into a ________. For example, if we're reading input from the user multiple times in the same way, that's a great candidate for a function. If we output something in the same way in multiple places, that's also a great candidate for a function. - Code that has a well-defined set of inputs and outputs is a good candidate for a function, (particularly if it is complicated). For example, if we have a list of items that we want to ______, the code to do the sorting would make a great function, even if it's only done once. The input is the unsorted list, and the output is the sorted list. Another good prospective function would be code that simulates the roll of a 6-sided dice. Your current program might only use that in one place, but if you turn it into a function, it's ready to be reused if you later extend your program or in a future program. - A function should generally perform one (and only one) task. - When a function becomes too long, too complicated, or hard to understand, it can be split into multiple sub-functions. This is called ________.

function, sort, refactoring

BEST PRACTICE- use early return when they simplify __________ logic.

functions

Nested Functions are not supported- functions can NOT be defined inside other ________. (foo, goo, moo, and boo are used as placeholders and have NO syntactical meaning)- void foo()

functions

objects at end of scope (end of curly brace) in which object was instantiated. Local variables life end at point where is "goes out of scope".

going out of scope

flow control statement that terminates the program, implemented as function (rather than keywords), halt statements will be function calls.

halt

BEST PRACTICE- only use a _____ if there is not safe way to return normally from the main function. If you havent disabled exceptions, prefer using exceptions for handling errors safely. _________ are safer mechanism for handling error cases.

halt, exceptions

User-defined functions have names, the _____ is the name of the user-defined function. ______ after the identifier tell the compiler that we are defining a function.

identifier, Parentheses

when an identifier can be accessed

in scope

For-each loops do NOT provide direct way to get array ____ of current element because many structures that for-each loops can be used with (linked lists) are NOT directly indexable.

index

can be used with range-based for-loops and to create a manual index counter without polluting function the for-loop is placed for (init-statement; element_declaration : array) statement;

init-statement

each time a loop executes, when using while statement we want to do something every 2nd, 3rd, or 5th time (printing new line), done with the modulus operator on our counter.

iterations

runtime property, time between creation and destruction when program is running, NOT at compile time. Objects must be created and initialized no later than the point of definition, and destroyed no earlier than end of set of curly braces in which they are defined. void doSomething() { //code here } int main() { int x; //x's lifetime begins doSomething(); return 0; } //x's lifetime ends

lifetime

function parameters and variables defined inside function body int add(int x) //local function parameters and variables (x) { //local variables } // local variables destroyed here ________ are __________ in ________ order of creation at end of set of curly braces in which it is defined.

local variables, destroyed, opposite

integer used to count how many times a loop has executed (infinite loops have a loop variable). Loop variables have simple names (i, j, k, iii, jjj). Can also be "real" variable names (count, userCount).

loop variable (counter)

infinite loops

loops that execute forever

why functions are useful, and how to use them effectively: ________ -- As programs grow in complexity, having all the code live inside the main() function becomes increasingly complicated. A function is almost like a mini-program that we can write separately from the main program, without having to think about the rest of the program while we write it. This allows us to reduce a complicated program into smaller, more manageable chunks, which reduces the overall complexity of our program. Reusability -- Once a function is written, it can be called multiple times from within the program. This avoids duplicated code ("Don't Repeat Yourself") and minimizes the probability of copy/paste errors. Functions can also be shared with other programs, reducing the amount of code that has to be written from scratch (and retested) each time. ________ -- Because functions reduce code redundancy, there's less code to test in the first place. Also because functions are self-contained, once we've tested a function to ensure it works, we don't need to test it again unless we change it. This reduces the amount of code we have to test at one time, making it much easier to find bugs (or avoid them in the first place). Extensibility -- When we need to _____ our program to handle a case it didn't handle before, functions allow us to make the change in one place and have that change take effect every time the function is called. _______ -- In order to use a function, you only need to know its name, inputs, outputs, and where it lives. You don't need to know how it works, or what other code it's dependent upon to use it. This lowers the amount of knowledge required to use other people's code (including everything in the standard library).

organization, testing, extend, abstraction

when an identifier can NOT be accessed. The identifier when it can not be accessed within the code

out of scope

BEST PRACTICE- keep _____ ______ in your function declarations. Can easily create function declarations by copy/pasting function's header and adding a _______.

parameter names, semicolon

Functions that share an identifier but have different _______ are considered to be distinct functions

parameters

when a function is called, all parameters of function are created as variables, and the value of each of the arguments is copied into matching parameter through this process. Number of arguments must match number of function parameters or compiler will throw an error.

pass by value

For-each does NOT work with _______ to an array- need to know how big the array size is, arrays that have decayed into a pointer do not know their _____ so for-each loops will NOT work

pointers, size

_______: not all declarations are definitions such as function declaration (satisfies compiler but not the linker). Other types include forward declarations for variables and type declarations - ODR (_______) does NOT apply to pure declarations, can have as many declarations for an identifier as you want (having more than one is redundant)

pure declaration, one definition rule

____ _______: name that includes associated scope (names are qualified with namespace using scope resolution operator (____) std::cout //qualified by namespace std ::foo //identifier foo qualified by global namespace Name can also be qualified by class name using scope resolution operator (: :), or by class object using member selection operator ( (___) dot or ->) class C; C::s_member; obj.x; ptr->y;

qualified name, : :, .

BEST PRACTICE- Follow the DRY best practice: "don't repeat yourself". If you need to do something more than once, consider how to modify your code to remove as much _________ as possible. Variables can be used to store the results of calculations that need to be used more than once (so we don't have to repeat the calculation). Functions can be used to define a sequence of ________ we want to execute more than once. And loops (which we'll cover in a later chapter) can be used to execute a statement more than once.

redundancy, statements

element declarations are declared by value so each array element iterated over will be copied into variable element. Copying array elements can be expensive, and we mostly want to refer to the original element using references (recommended to be const) std::string array[]{ "peter", "likes", "frozen", "yogurt" }; // element is a const reference to the currently iterated array element for (const auto& element: array) { std::cout << element << ' '; }

references

BEST PRACTICE- do NOT put _______ statement at end of non-value returning function

return

user-defined functions allow you to determine whether your function will return a value back to the caller or not by indicating type of value to be returned by setting the function's _______ (type defined before function's name) then inside the function that will return a value, use a ______ to indicate specific value being returned to the caller (return value). When return statement is executed, function exits immediately and return value is copied from function back to called (process called return by _____).

return type, return statement, value

Function author can decide what the _______ means- meaning of value returned by function is determined by function's author. Some functions use return values as static codes to indicate whether they succeeded or failed. Other functions return calculated or _______ value or nothing.

return value, selected

A function with one _______ statement at the bottom of the function is simple for the function to take its argument, do whatever logic it has implemented, and return a result without deviation. Having extra returns complicates logic. ______ _______ allow function to exit as soon as it is done, reducing reading through unnecessary logic and minimizing need for conditional nested blocks to make code readable. Some programmers only use early returns at top of function to do parameter validation (catch bad arguments passed in), and then a ______ return.

return, early returns, single


Kaugnay na mga set ng pag-aaral

Research in Public Elementary and Secondary Schools - SBE

View Set

Praxis 5089 Middle School Social Studies, Social Studies Praxis Practice Test, Middle School Social Studies Praxis Study Guide 2

View Set

NCSU ST370 Chapters 1-8 Important Content

View Set

intro to criminal justice exam 1 review

View Set