EECS 183 Midterm

0.0(0)
studied byStudied by 0 people
GameKnowt Play
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/94

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

95 Terms

1
New cards

compiler

is a tool that converts a program into low-level machine instructions (0s and 1s) understood by a particular computer

2
New cards

Cout << or Cout >>

Cout <<

3
New cards

Cin << or Cin >>

Cin >> (extraction operator)

4
New cards

" " vs ' ' vs none

"string" 'char' variable

5
New cards

= vs ==

assigns whatever left side is to right side
equals

6
New cards

endl vs \n

for \n don't need << in between

7
New cards

Basic structure of function

(int/char/double etc.) function(){
stuff;
return;
}

8
New cards

Two types of comments

//one line comment

/*
multiple line comment
*/

9
New cards

syntax error

Known as: compile-time error (because detected by compiler)
Violate a programming language's rules on how symbols can be combined to create a program. An example is forgetting to end a statement with a semicolon.

10
New cards

logic error

An error that occurs while a program runs, also called a runtime error or bug. For example, a programmer might mean to type numBeans numJars but accidentally types numBeans + numJars (+ instead of ). The program would compile, but would not run as intended.

11
New cards

Warning

A compiler will sometimes report a warning, which doesn't stop the compiler from creating an executable program, but indicates a possible logic error. For example, some compilers will report a warning like "Warning, dividing by 0 is not defined" if encountering code like: totalItems = numItems / 0 (running that program does result in a runtime error). Even though the compiler may create an executable program, good practice is to write programs that compile without warnings. In fact, many programmers recommend the good practice of configuring compilers to print even more warnings

12
New cards

Variable (and address)

variable represents a memory location used to store data. Place where data is stored is the address

13
New cards

Variable definition/declaration

Same thing
Example: int food; or int food = 0;
Capitalization matter food != Food

14
New cards

Uninitialized variable value

A common error is to read a variable that has not yet been assigned a value. If a variable is defined but not initialized, the variable's memory location contains some unknown value, commonly but not always 0.

15
New cards

Expression

What you assign to a variable
Variable = expression;
Remember to always write expression on right side
Note that an expression can be just a literal, just a variable, or some combination of variables, literals, and operators.

16
New cards

Identifier (definition and what can use for one)

name of a variable
An identifier must be a sequence of letters (a-z, A-Z, _) and digits (0-9) and must start with a letter. Note that "_", called an underscore, is considered to be a letter.

17
New cards

Reserved word

A reserved word is a word that is part of the language, like int, short, or double. A reserved word is also known as a keyword. A programmer cannot use a reserved word as an identifier. Many language editors will automatically color a program's reserved words.

Know the following:
bool, break, case, char, class, const, default, do, double, else, false, float, for, if, int, namespace, operator, private, public, return, static_cast, struct, switch, true, unsigned, using, void, while

18
New cards

Function naming conventions

Camel case: Lower camel case abuts multiple words, capitalizing each word except the first, as in numApples or peopleOnBus.

Underscore separated: Words are lowercase and separated by an underscore, as in num_apples or people_on_bus.

This material uses lower camel case; neither convention is better. The key is to be consistent. Consistent style makes code easier to read and maintain, especially if multiple programmers will be maintaining the code. Make names meaningful, but not too long

19
New cards

Literal

A literal is a specific value in code like 2

20
New cards

x = 6,000 or x = 6000

x = 6000, no commas!

21
New cards

Operator

An operator is a symbol for a built-in language calculation like + for addition
Parentheses may be used, as in: ((userItems + 1) * 2) / totalItems. Brackets [ ] or braces { } may NOT be used.
5y is invalid, write 5*y

22
New cards

x + 5 or x+5 (and unary minus)

either works, but x + 5 is better practice
An exception is - used as negative, as in: xCoord = -yCoord. - used as negative is known as unary minus.

23
New cards

Division operator

5 / 2 = 2 (truncates: gets rid of any remainder)
1 / 2 = 0

24
New cards

Modulo operator

% gets remainder
5 % 2 = 1
1 % 2 = 1

25
New cards

Integer divide-by-zero

Floating-point divide-by-zero

error occurs at runtime if a divisor is 0, causing a program to terminate.

A floating-point divide-by-zero occurs at runtime if a divisor is 0.0. Dividing by zero results in inf or -inf depending on the signs of the operands.

26
New cards

Precedence rules for math

( ) first, - used as negative (unary minus) is second, * / % next but all three equal, + - next
left to right: If more than one operator of equal precedence could be evaluated, evaluation occurs left to right.
Even if works, use ( ) to make clear precedence

27
New cards

Compound operators

compound operators provide a shorthand way to update a variable, such as userAge += 1 being shorthand for userAge = userAge + 1. Other compound operators include -=, *=, /=, and %=.

28
New cards

Overflow (and type of error)

overflow occurs when the value being assigned to a variable is greater than the maximum value the variable can store.

A common error is to try to store a value greater than about 2 billion into an int variable. For example, the decimal number 4,294,967,297 requires 33 bits in binary, namely 100000000000000000000000000000001 (we chose the decimal number for easy binary viewing). Trying to assign that number into an int results in overflow. The 33rd bit is lost and only the lower 32 bits are stored, namely 00000000000000000000000000000001, which is decimal number 1.

Most compilers detect when a statement assigns to a variable a literal constant so large as to cause overflow. The compiler may not report a syntax error (the syntax is correct), but may output a compiler warning message that indicates a potential problem.

29
New cards

How much can int store

roughly + or - 2 billion

30
New cards

Double, floating point literal

A variable is sometimes needed to store a floating-point number like -1.05 or 0.001. A variable defined as type double stores a floating-point number.

A floating-point literal is a number with a fractional part, even if that fraction is 0, as in 1.0, 0.0, or 99.573. Good practice is to always have a digit before the decimal point, as in 0.5, since .5 might mistakenly be viewed as 5.

31
New cards

Scientific notation

Scientific notation is useful for representing floating-point numbers that are much greater than or much less than 0, such as 6.02x1023. A floating-point literal using scientific notation is written using an e preceding the power-of-10 exponent, as in 6.02e23 to represent 6.02x1023. The e stands for exponent. Likewise, 0.001 is 1x10-3 so 0.001 can be written as 1.0e-3. For a floating-point literal, good practice is to make the leading digit non-zero.

32
New cards

When to use floating point vs integer types

In general, a floating-point variable should be used to represent a quantity that is measured, such as a distance, temperature, volume, weight, etc., whereas an integer variable should be used to represent a quantity that is counted, such as a number of cars, students, cities, minutes, etc. Floating-point is also used when dealing with fractions of countable items, such as the average number of cars per household.

33
New cards

Char

A variable of char type can store a single character, like the letter m or the symbol %. A character literal is surrounded with single quotes, as in 'm' or '%'. Using " " yields a complier error.

34
New cards

ASCII

Under the hood, a char variable stores a number. For example, the letter m is stored as 109. A table showing the standard number used for common characters appears at this section's end. Though stored as a number, the compiler knows to output a char type as the corresponding character.

ASCII 0-9 (small 48-57) A-Z (medium 65-90) a-z ( big 97-122) THE LATER THE LETTER THE HIGHER THE VALUE, t>r

35
New cards

Escape sequence

escape sequence is a two-character sequence starting with \ that represents a special character. Ex: '\n' represents a newline character. Escape sequences also enable representing characters like ', ", or \. Ex: myChar = '\'' assigns myChar with a single-quote character. myChar = '\\' assigns myChar with \ (just '\' would yield a compiler error, since \' is the escape sequence for ', and then a closing ' is missing).
\n newline
\t tab
\' single quote
\" double quote
\\ backslash

36
New cards

String

Some variables should store a sequence of characters like the name Julia. A sequence of characters is called a string. A string literal uses double quotes as in "Julia". Various characters may be included, such as letters, numbers, spaces, symbols like $, etc., as in "Hello ... Julia!!".
A string data type isn't built into C++ as are char, int, or double. But a string data type is available in the standard library and can be used after adding: #include <string>. A programmer can then define a string variable as: string firstName;.
A programmer can initialize a string variable during definition: string firstMonth = "January";. Otherwise, a string variable is automatically initialized to an empty string "".

37
New cards

Input "Betty Sue"
Cin >> stringVar;


Getline(cin, stringVar);

stores only Betty since there is a space, second part will be stored in next cin if another string, otherwise error

gets all input until enter is pressed so Betty Sue (notice no space in between getline and first parenthesis

38
New cards

Constant variables

If the programmer precedes the variable definition with the keyword const, then the compiler will report an error if a later statement tries to change that variable's value. An initialized variable whose value cannot change is called a constant variable. A common convention, or good practice, is to name constant variables using upper case letters with words separated by underscores, to make constant variables clearly visible in code. AMOUNT_FOOD
Don't just use a number (magic number), use a constant

39
New cards

Type conversion

A type conversion is a conversion of one data type to another, such as an int to a double. The compiler automatically performs several common conversions between int and double types, such automatic conversion known as implicit conversion.
For an arithmetic operator like + or *, if either operand is a double, the other is automatically converted to double, and then a floating-point operation is performed.
For assignment =, the right side type is converted to the left side type.

int-to-double conversion is straightforward: 25 becomes 25.0.

double-to-int conversion just drops the fraction: 4.9 becomes 4.

40
New cards

double someDoubleVar = 0;
someDoubleVar = 5;

are allowed, but discouraged. Using 0.0 or 5.0 is preferable.

41
New cards

type casting

convert the expression's value to the indicated type. For example, if myIntVar is 7 (an int type), then static_cast<double>(myIntVar) converts int 7 to double 7.0

A common error is to cast the entire result of integer division, rather than the operands, thus not obtaining the desired floating-point division. For example, static_cast<double>((5 + 10) / 2) yields 7.0 (integer division yields 7, then converted to 7.0) rather than 7.5.

42
New cards

Integer Numeric Types

Char (8 bits), short (16 bits), long (32 bits), long long (64 bits), int (natural size based on compiler, usually 32 bits), float (32 bits), double (64 bits)

Overflow with floating-point results in infinity.

On some processors, especially low-cost processors intended for "embedded" computing, like systems in an automobile or medical device, floating-point calculations may run slower than integer calculations, such as 100 times slower. Floating-point types are typically only used when really necessary.

43
New cards

Step over, Step into, Step out, Continue

Step Over executes the procedure as a unit, and then steps to the next statement in the current procedure. Therefore, the next statement displayed is the next statement in the current procedure regardless of whether the current statement is a call to another procedure. Available in break mode only.

When not in design mode, Step Into enters break mode at the current line of execution. If the statement is a call to a procedure, the next statement displayed is the first statement in the procedure.

Executes the remaining lines of a function in which the current execution point lies. The next statement displayed is the statement following the procedure call. All of the code is executed between the current and the final execution points. Available in break mode only.

Continues to next break point.

44
New cards

Function, argument, function call

A function is a list of statements that can be executed by referring to the function's name. An input value to a function appears between parentheses and is known as an argument, such as areaSquare above. The function executes and returns a new value. In the example above, sqrt(areaSquare) returns 7.0, which is assigned to sideSquare. Invoking a function is a function call.

45
New cards

Math library

function followed by ( )
pow Raise to power cos Cosine
sqrt Square root sin Sine
tan Tangent
exp Exponential function acos Arc cosine
log Natural logarithm asin Arc sine
log10 Common logarithm atan Arc tangent
atan2 Arc tangent with two parameters
ceil Round up value cosh Hyperbolic cosine
fabs Compute absolute value sinh Hyperbolic sine
floor Round down value tanh Hyperbolic tangent
fmod Remainder of division
abs Compute absolute value frexp Get significand and exponent
ldexp Generate number from significand and exponent
modf Break into fractional and integral parts

46
New cards

Function definition

A function definition consists of the new function's name and a block of statements, as appeared above: void PrintFace() { ... }. The name can be any valid identifier. A block is a list of statements surrounded by braces.

47
New cards

Parameter, argument

Programmers can influence a function's behavior via an input to the function known as a parameter.
Function (parameter);

The value passed to a parameter is known as an argument. An argument is an expression, such as 99, numCars, or numCars + 99.

In contrast to an argument being an expression, a parameter is like a variable definition. Upon a call, the parameter's memory location is allocated, and the argument's value is assigned to the parameter. Upon a return, the parameter is deleted from memory,

48
New cards

0 - no parameter function call

Argument values are assigned to parameters by position: First argument to the first parameter, second to the second, etc.

A function definition with no parameters must still have the parentheses, as in: void PrintSomething() { ... }. The call to such a function there must be parentheses, and they must be empty, as in: PrintSomething().

49
New cards

Return statement

A function may return a value using a return statement, as follows. Return statement must match return type!
A return statement may appear as any statement in a function, not just as the last statement. Also, multiple return statements may exist in a function.

50
New cards

Void

A return type of void indicates that a function does not return any value, in which case the return statement should simply be: return;

51
New cards

Reasons for functions

1. improve readability
2. modular (incremental) program development
3. avoid writing redundant code

52
New cards

Unit testing, testbench, test vector, border cases

Unit testing is the process of individually testing a small part or unit of a program, typically a function. A unit test is typically conducted by creating a testbench, a.k.a. test harness, which is a separate program whose sole purpose is to check that a function returns correct output values for a variety of input values. Each unique set of input values is known as a test vector. Border cases are cases you think could "break" the function

53
New cards

Scope

The name of a defined variable or function item is only visible to part of a program, known as the item's scope. A variable defined in a function has scope limited to inside that function. In fact, because a compiler scans a program line-by-line from top-to-bottom, the scope starts after the definition until the function's end. The following highlights the scope of local variable cmVal.

Starts at declaration point
Ends at the closing bracket of the enclosing
block (e.g., end of function, if statement, etc.)
Once the execution leaves the scope of a
variable - by returnstatement or reaching the end of the scope (i.e., curly braces{}), the variable gets de-allocated (destroyed)

54
New cards

Global variable

A variable defined outside any function is called a global variable, in contrast to a local variable defined inside a function. A global variable's scope extends after the definition to the file's end, and reaches into functions. For example, HeightFtInToCm() above accesses global variables CM_PER_IN and IN_PER_FT.

55
New cards

Function declaration

A function declaration specifies the function's return type, name, and parameters, ending with a semicolon where the opening brace would have gone. A function declaration is also known as a function prototype The function declaration gives the compiler enough information to recognize valid calls to the function. So by placing function declarations at the top of a file, the main function can then appear next, with actual function definitions appearing later in the file.

Return type, function name, parameter list

int isLeapYear (int year);

56
New cards

Missing return statement

Sometimes a function with a missing return statement (or just return;) still returns the correct value. The reason is that the compiler uses a memory location to return a value to the calling expression.

57
New cards

Preprocessor

The preprocessor is a tool that scans the file from top to bottom looking for any lines that begin with #, known as a hash symbol. Each such line is not a program statement, but rather directs the preprocessor to modify the file in some way before compilation continues, each such line being known as a preprocessor directive. The directive ends at the end of the line, no semicolon is used at the end of the line.
#include "filename"
#include <filename>

58
New cards

#include

#include "myfile.h" -- A filename in quotes causes the preprocessor to look for the file in the same folder/directory as the including file.
#include <stdfile> -- A filename in angle brackets causes the preprocessor to look in the system's standard library folder/directory. Programmers typically use angle brackets only for standard library files, using quotes for all other include files. Note that nearly every previous example has included at least one standard library file, using angle brackets.
Header files that are part of the standard C++ library do not have a .h extension.
Items that were originally part of the C standard library have a "c" prepended, as in cmath.

59
New cards

Multiple files

If you have main.cpp, blah.cpp, and blah.h (which has the declarations for blah.cpp), write #include "blah.h" because without then the definitions aren't in the scope of main.cpp (could also define functions in blah.h)

60
New cards

Header guard files

When lots of files, headers could be called twice which causes a problem as thinks items being defined multiple times

#ifndef FILENAME_H
#define FILENAME_H
// Header file contents
#endif

Header file guards are preprocessor directives cause the compiler to only include the contents of the header file once. #define FILENAME_H defines the symbol FILENAME_H to the preprocessor. The #ifndef FILENAME_H and #endif form a pair that instructs the preprocessor to process the code between the pair only if FILENAME_H is not defined ("ifndef" is short for "if not defined"). Thus, if the preprocessor includes encounter the header more than once, the code in the file during the second and any subsequent encounters will be skipped because FILENAME_H was already defined. Good practice is to guard every header file.

61
New cards

Pass by value

Assigning a normal parameter fails to update the argument's variable, because normal parameters are pass by value, meaning the argument's value is copied into a local variable for the parameter.

Although a pass by value parameter creates a local copy, good practice is to avoid assigning such a parameter. Don't assign this value to x and return x.

62
New cards

Pass by reference

A pass by reference parameter does not create a local copy of the argument, but rather the parameter refers directly to the argument variable's memory location. Appending & to a parameter's data type makes the parameter pass by reference type.

void ConvHrMin (int& timeVal, int& hrVal,
int& minVal) {
hrVal = timeVal / 60;
minVal = timeVal % 60;
return;
}

Before did blah=function( ) but this doesn't work for multiple variables, and & will actually change stored location

ONLY USE WHEN OUTPUT VALUES ARE INTERTWINED

if returning those values then just write return not return 0

CAN'T HAVE AN EXPRESSION IN PASS BY REFERENCE

63
New cards

#include <iostream>

Adds in standard input and output (cin, cout)

64
New cards

Function overloading

Sometimes a program has two functions with the same name but differing in the number or types of parameters, known as function name overloading or just function overloading. The following two functions print a date given the day, month, and year. The first function has parameters of type int, int, and int, while the second has parameters of type int, string, and int.

A function's return type does not influence overloading. Thus, having two same-named function definitions with the same parameter types but different return types still yield a compiler error.
The use of overloading and of default parameter values may be combined as long as no ambiguity is introduced. Adding the function void DatePrint(int month, int day, int year, int style = 0) above would generate a compiler error because the compiler cannot determine if the function call DatePrint(7, 30, 2012) should go to the "int, int, int" function or to that new "int, int, int, int" function with a default value for the last parameter.

65
New cards

Branching

if else, switch statements

66
New cards

If else statement

// Statements that execute before the branches

if (expression) {
// Statements to execute when the expression is true (first branch)
}
else {
// Statements to execute when the expression is false (second branch)
}

// Statements that execute after the branches

When a branch has a single statement, the braces are optional, but good practice always uses the braces. Always using braces even when a branch only has one statement prevents the common error of mistakenly thinking a statement is part of a branch.

67
New cards

relational operator or equality operator

a < b a is less-than b
a > b a is greater-than b
a <= b a is less-than-or-equal-to b
a >= b a is greater-than-or-equal-to b
a == b a is equal to b
a != b a is not equal to b

can only compare two things at once, evaluate left to right!

68
New cards

Equal for strings and float

The operators can also be used for the string type. Strings are equal if they have the same number of characters and corresponding characters are identical. If string myStr = "Tuesday", then (myStr == "Tuesday") is true, while (myStr == "tuesday") is false because T differs from t. If one is longer and all equal up to that, longer is greater. Can also use greater than, smaller than, !=, etc.

Don't use == for float

69
New cards

Logical operator

treats operands as being true or false, and evaluates to true or false.

Logical operator Description
a && b Logical AND: true when both operands are true
a || b Logical OR: true when at least one of its two operands are true
!a Logical NOT (opposite): true when its single operand is false (and false when operand is true)
can only compare two things at once, evaluate left to right!

70
New cards

Bool

bool (short for Boolean) data type is for variables that should store only values true or false.

71
New cards

Precedence rules for logical and relational operators

1. ( )
2. !
3. used as negative (unary minus) is second
4. * / % next but all three equal
5. + -
6. < <= > >=
7. == !=
8. &&
9. ||

left to right: If more than one operator of equal precedence could be evaluated, evaluation occurs left to right.

72
New cards

Else if

Bad code:
if (grade >= 90) {cout << "A";}
if (grade < 90 && grade >= 80) {cout << "B";}
if (grade < 80 && grade >= 70) {cout << "C";}
if (grade < 70 && grade >= 60) {cout << "D";}
if (grade < 60) {cout << "F";}

Better code:
if (grade >= 90) {cout << "A";}
else {if (grade >= 80) {cout << "B";}
else {if (grade >= 70) {cout << "C";}
else {if (grade >= 60) {cout << "D";}
else {cout << "F";}}}}

Best code:
If (grade >= 90) {cout << "A";}
else if(grade >= 80) {cout << "B";}
else if(grade >= 70) {cout << "C";}
else if(grade >= 60) {cout << "D";}
else {cout << "F";}

73
New cards

Floating point comparison

Don't use == because not exact value is stored. The difference threshold indicating that floating-point numbers are equal is often called the epsilon. Epsilon's value depends on the program's expected values, but 0.0001 is common. Use fabs(x - y) < 0.0001 (use fabs because could be negative)

74
New cards

Switch

Only compares integers or chars!
A switch statement can more clearly represent multi-branch behavior involving a variable being compared to constant values. The program executes the first case whose constant expression matches the value of the switch expression, executes that case's statements, and then jumps to the end. If no case matches, then the default case statements are executed.

switch (variable) {
case 0:
stuff;
break;
case 1:
stuff;
break;
default:
stuff;
break;
}

If no break and something is true falls through to all others until next break

75
New cards

Loop

for, while
Some behaviors should be repeated over and over, like a race-car driving around a track. A loop is a construct that repeatedly executes specific code as long as some condition is true.

infinite loop is a loop that will always execute (i.e., execute infinitely) because the loop's expression always evaluates to true. (common is to use = instead of ==)

76
New cards

While loop

A while loop is a program construct that executes a list of sub-statements repeatedly as long as the loop's expression evaluates to true.

When execution reaches the while loop statement, the expression is evaluated. If true, execution proceeds into the sub-statements inside the braces, known as the loop body. At the loop body's end, execution goes back to the while loop statement start. The expression is again evaluated, and if true, execution again proceeds into the loop body. But if false, execution instead proceeds past the closing brace. Each execution of the loop body is called an iteration, and looping is also called iterating.

while (expression) {
stuff;
}
// Statements that execute after the expression evaluates to false

77
New cards

Increment operator

i = i + 1 same as ++i
i = i - 1 same as --i

Important: The increment/decrement operators can appear in prefix form (++i or--i) or postfix form (i++ or i--). The distinction is relevant when used in a larger expression, as in x < i++. The prefix form first increments the variable, then uses the incremented value in the expression. The postfix form first uses the current variable value in the expression, and then increments the variable. We do not recommend use of the increment/decrement operators in larger expressions, and thus only use the prefix form, which some say is safer for beginner programmers in case they accidentally type i = ++i, which works as expected, whereas i = i++ does not.

78
New cards

For loop

Use for counting, note third expression doesn't end with ;
Don't add in another increment, already handled in top

for (initialExpression; conditionExpression; updateExpression) {
// Loop body
}
// Statements to execute after the expression evaluates to false

Example (runs 100 times):
for (i = 0; i <= 99; ++i) {
// Loop body statements
}

Same as

Example (runs 100 times):
for (i = 0; i <= 99; i = i + 1) {
// Loop body statements
}

79
New cards

For vs While

For Use when the number of iterations is computable before entering the loop, as when counting down from X to 0, printing a character N times, etc.
While Use when the number of iterations is not computable before entering the loop, as when iterating until a user enters a particular character.

80
New cards

Increment programming

Experienced programmers develop programs incrementally, meaning they create a simple program version, and then growing the program little-by-little into successively more-complete versions.

81
New cards

RME

RME: use for every function, Requires (constraints? The constraint doesn't have to be written in code, assumes user respects the R), Modifies (change?), Effects (what does it do?) Use before declaration not definition.

82
New cards

Convert !( (18 > age) || (age > 22))

!( (18 > age) || (age > 22)) same as (18<= age) && (age <=22)

83
New cards

Short circuit evaluation

Short Circuit Evaluation
Promotes efficiency
-Put conditions that are less expensive first
Useful in error prevention
In case of AND &&:
- Put the expression that is most likely false first
In case of OR ||:
- Put the expression that is most likely true first

84
New cards

Pseudocode, Algorithim

Code before actually write in source code (c++)

An algorithm is a specific approach to solve a
problem.
Counting people in the room Finding a certain page in a book
Different algorithms vary in efficiency and
speed
By halving the problem each time, we vastly improved the search through the book

85
New cards

What is everything

#include <iostream>
Using namespace std;

Int main (void) {
Cout << "Hello world!" << endl;
Return 0;
}

Main: where it all starts, the main function
Void: Don't need anything, nothing, not 0
(): whatever inside is passed to the program
Return: go back to where the function was called from (main)
0: is return value, 0 means everything is good, nothing here, have to return something for a function, in this case 0
Int: return type, must match to return value
{}: denote the scope of the function
Cout: says to print the standard output stream
<<: insertion operator, used to put thing into output stream
"Hello world": string literal
Endl: denotes the end of line
#include: tells preprocessor to include code someone else made called iostream
Using namespace std: tells system what library to use
Cin >> : way to get information from user

86
New cards

When does cin enter fail state

When
datatype of value read doesn't match datatype of variable

87
New cards

double numFood = (7/2) + (8/2); is equal to

7

88
New cards

Function call:
food(int x)
or
food(x)

food(x) NO INT or any variable type in function calls

89
New cards

DeMorgan's Theorem

• To complement a compound logical expression:
- First write complement of each sub-expression - Change each AND to OR and
each OR to AND

90
New cards

Strings location and how to change

first char at 0, then 1, then 2

string str = "hello";
str[0] = 'j';
cout << str << endl;
Output: Jello

string str = "hello";
str[0] = 'y';
str[5] = 'w';
cout << str << endl;
Runtime error, no 5th place

string str = "hello";
str[0] = 'y';
str = str + 'w'; (concatenates w to the string)
cout << str << endl;
Yellow

91
New cards

What happens if a function local variable has same name as global variable?

Refer to local variable in the function

92
New cards

If you include the string library do you need to write using namespace std;?

YES

93
New cards

for array [ ] what is first number stored in to

0, so the 6th term put in would be accessed using [5]

94
New cards

Which of the following is a valid array declaration?
I. int arr[5];
II. int arr[] = {1, 2, 3, 4, 5};
III. int arr[5] = {0};
A. I only B. I and II C. I and III D. II and III E. I, II, and III

E

95
New cards

Which of the following are possible reasons to pass a variable by reference?
A. To change the value of the variable.
B. To save memory.
C. To shorten run time.
D. A and C.
E. A, B, and C.

E