Shared Flashcard Set

Details

CSCE 121 C++ Tamu Ch 4-5
MOAR
130
Computer Science
Undergraduate 1
02/07/2014

Additional Computer Science Flashcards

 


 

Cards

Term
Where can output go to?
Definition

Output can be to a screen, to files, to other output

devices, to other programs, and to other parts of a program. Examples of output

devices include network interfaces, music synthesizers, electric motors, light generators,

heaters, etc.

Term
Argument and result
Definition

Inputs to a part of a program. 

outputs from a program part. 

Term
Computation
Definition
The act of producing the output  based on input arguments.
Term
Abstraction
Definition

Hide details that we don't need to usc a facility ("implementation details") behind a convenient and general interface. we access it through typed and named

variables

Term
Divide and conquer
Definition

taking a large problem and dividing it into several

little ones.

Term
Expression
Definition

The most basic building block of programs is an expression. An expression computes

a value from a number of operands. The simplest expression is simply a literal value, such as 10, 'a', 3.14, or "Norah". Names and variables are also expressions.

Term

Are the following expressions?

 

int length = 20;

int width = 40;

int area = length*width

Definition
Yes
Term

What does this mean?

 

length = 99;

Definition

99 is the value found in the variable length. 99 has initialized the variable. Here, length means "the object

named length," so that the assignment expression is read "Put 99 into the object named by length." We distinguish between length used on the left-hand side of an assignment or an initialization (" the lvalue of length" or "the object named by length") and length used on the right-hand side of an assignment or initialization

(" the rvalue of length," "the value of the object named by length," or just "the value of length")

Term
What do ivalue and rvalue mean?
Definition
ival"value that can appear all the left-hand side of an assignment. refers to the object ("value that can appear all the left-hand side of an assignment), rvalue refers to the value in the object. oh god what happened to my format 
Term

Which code is correct in determining perimeter?

 

1. int perimeter = length*2+width*2

 

2. int perimeter = length+width*2

 

3. int perimeter = (length+width)*2

Definition
1 and 3 are both correct, however 1 is generally considered a clumsy and ugly.
Term
What rules apply to mathematical precedence in C++?
Definition

The usual mathematical rules of operator precedence apply, so length+ width*2 means le ngth+(width*2). Similarly a* b+c/d means (a* b)+(cld) and not

a*( b+c)/d.

Term
Why do we want to avoid ugly code?
Definition

ugly code slows down reading and comprehension.

Ugly code is not often just hard to read, it is also much harder to get correct. Ugly code often hides logical errors.

Term
Define a constant
Definition

a symbolic constant, that is, a named object to which you can't give a new value after it has been initialized. For example:

 

const double pi = 3.14159

 

You cannot reassign pi. for instance, saying pi=7 would just cause the compiler to read const pi. 

Term
What is a magic constant?
Definition
Nonobvious literals in code (outside const definitions)
Term

Define a constant expression

Definition

expression with an integer value composed exclusively of constants. For example:

 

 

const int max=17; //a literal is a constant expression

int val=9

 

max+2 //a constant expression (const plus a literal)

val+2 //not a const expression.

Term

Name these operators:

 

f(a)

++ival

--ival

!a

-a

a*b

a/b

a%b

Definition

Function call

pre increment

pre decrement

not

unary minus

multiply

divide

modulo

Term

Name these operators:

 

a+b

a-b

out<<b

in>>b

a<b

a<=b

a>b

a>=b

Definition

add 

subtract

white b to out

read in into b

less than

less than or equal

greater than

greater than or equal

 

Term

Name these operators:

 

a==b

a!=b

a && b

a || b

ival = a

ival *=a

Definition

equal

not equal

logical and

logical or

assignment

compound assignment 

Term
Why is a<b<c a useless expression?
Definition

a<b<c means (a<b)<c and that a<b evaluates to a Boolean value: True or false. So, a<b<c will be equivalent to either True<c or false<c. In particular,

a<b<c docs not mean "Is b between a and c?".

Term

What are the three ways an increment can be expressed?

What is the most preferred method for expression incrementation? Why?

 

Definition

++a

a+=1

a=a+1

 

Method one is the most preferred because it expresses what we want to do most logically, and leaves no room for guessing whether we meant to increment by 1 or just made an error. 

Term
Can you mix expressions? If so, give an example. What happens if we divide an int by an int? A double by a double? a double by an int?
Definition
Yes; if necessary, a compiler will promote an int to a double, or a char to an int. An int divided by an int will always provide an int, whether or not the it should actually give a decimal number.  Doubles will provide doubles. A double divided by an int will provide a double.
Term
What would 5/2 yield?
Definition
2
Term
What would 5.0/2 yield?
Definition
2.5
Term
what would 'a'+1 yield?
Definition
int('a')+1
Term

What is wrong with this code?

 

double dc;

cin>>dc;

double df=9/5*dc+32;

Definition
9/5 would produce a value of 1 rather that 1.8, because it is an integer divided by an integer.
Term
What is an expression statement?
Definition
An express ion statement is simply an expression followed by a semicolon. For example: a = b; or ++a;
Term

What does the compiler do to statements that follow one another? 

 

example:

 int a =7;

cout << a << '\n';

Definition
The execute them in the order in which they are written. Here, the declaration, with its initialization, is executed before the output expression statement.
Term
What is an empty statement?
Definition

generally looks like  

 

if {x == 5};

{ y = 3;}

 

These statements do nothing, even though they're legal constructs in C++. The compiler will not alert you to these errors. 

 

 

Term

What happens in this empty statement? 

 

if {x == 5};

{ y = 3;}

 
Definition

The compiler will test x to see if it has

the value 5. If this condition is true, the following  statement (the empty statement) will be executed, with no effect. Then the program continues to the next

line, assigning the value J to y (which is what you wanted to have happen if x equals 5). If, on the other hand, x does not have the value 5, the compiler will not execute the empty statement (still no effect) and will continue as before to assign the value 3 to y (which is not what you wanted to have happen unless x equals 5). In other words, the if statement doesn't matter; y is going to get the value 3 regardless.

Term
What is an if statement?
Definition

The simplest form of selection which selects between two alternatives. If its condition is true, the first

statement is executed; otherwise, the second statement is.

Term
Give an example of an if statement embedded into some code.
Definition

int main()

{

   int a=0;

   int b=0

 

   cout<< "Please enter two integers\n";

   cin>>a>>b;

  

   if (a<b)

      cout<<"max("<<a<<","<<b<<") is "<<b<<"\n";

   else 

      cout<<"max("<<a<<","<<b<<") is "<<a<<"\n";

}

Term

What is wrong with this code?

 

int main()

{

   const double cm_per_inch = 2.54;

   int length = 1;

   char unit = 0;

   cout<<"please enter a lenth followed by a unit (c or i):\n";

   cin<<length<<unit;

 

   if (unit == 'i')

      cout <<length<<"in ==" <<cm_per_inch*length<<"cm\n";

   else

      cout <<length<< "cm ==" <<length/cm_per_inch<<"in\n";

}

Definition
we didn't test for bad input. The program assumes that the user enters proper input. The condition unit=='i' distinguishes between The case where the unit is 'i' and all other cases . It never looks for a 'c'.
Term
What is the general format for an if statement?
Definition

if (expression) statement

else statement

Term
What is the general format for an if, else if, statement?
Definition

if (expression) statement

else if (expression) statement

else statement

Term
What is a switch statement?
Definition
They are clearer than nested if statements, they are used to make a selection based on comparison of a value against several constants. The value presented in parentheses after the switch is compared to a set of constants. Each constant is presented as part of a case label. If the value equals the constant in a case label, the statement for that case is chosen. Each case is terminated by a break. If the value doesn't match any of the case labels, the statement idenified by the default label is chosen.
Term
What are the technical details of a switch statement?
Definition

1. The value on which we switch must be of an integer, char, or enumeration type. In panicular, you cannot switch on a string.

 

2. The values in the case labels must be constant expressions. In particular, you cannot use a variable in a case label.

 

3. You cannot usc the same value for two case labels.

 

4. You can use several case labels for a single case.

 

5. Each case ends with a break.

Term

What is wrong with this switch statement based code?

 

int main()

{

   cout<<"Do you like fish?\n";

   string s;

   cin>>s;

   switch (s) {

   case "no";

   //...code here

   case "yes";

      break;

   //...code here 

      break;

   }

}

Definition
The value of the switch statement must be an integer, char, or enum type.
Term

What's wrong with this code?

 

int main()

{

   int y='y';

   const char n='n';

   const char m='?'

   cout<<"Do you like fish?\n";

   char a;

   cin>>a;

   switch (a) {

   case "n";

      //...code here

       break;

   case "y";

      //...code here 

      break;

   case "m";

      //...code here 

      break;

   case "n";

      //...code here 

      break;

   default:

      //

      break;

   }

 

}

Definition

There is a duplicate case label (n's value is 'n')

There is a variable in the case label, int y instead of char y. 

Term
How would you make a code if you wanted the same action for a set of values in a switch?
Definition

int main()

{

   cout<< "Please enter a digit\n";

   char a;

   cin>>a;

 

   switch(a){

   case '0': case '2': case '4': case '6': case '8':

      cout<< "is even\n";

      break;

   case '1': case'3': case '5': case '7': case '9':

      cout<< "is odd\n";

      break;

   default:

      cout<<"is not a digit\n"

      break;

   }

}

Term
What is the most common error when it comes to switch statements?
Definition
Forgetting to terminate a case with a break.
Term

Whats wrong with this code?

 

int main()

{

   const double cm_per_inch=2.54;

   int length=1;

   char unit='a';

   cout<<"please enter a length followed by a unit (c or i):\n";

   cin>>length>>unit;

 

   switch (unit) {

   case 'i':

      cout<<length<<"in=="<<cm_per_inch*length<<"cm\n";

   case 'c':

      cout<<length<<"cm=="<<length/cm_per_inch<<"in\n";

   }

Definition

A compiler will accept this, and when you have finished case 'i' you'll just "drop through" into case 'c', so that if you enter 2i the program will output

 

2in == 5.08cm

2cm == 0.787402 in

Term
Iteration
Definition
repetition to a series of elements of a data structure.
Term

Identify this code:

 

int main()

{

   int i=0
   while (i<100){

      cout<<i<<'\t' << square(i)<<'\n';

      ++i;

    }

Definition
This is the C++ version of the first program written and stored on a computer, by David Wheeler in 1949. it calculates and prints a table of squares 0-99.
Term
What is the language construct known as the while-statement?
Definition
a keyword that has a condition on top, following with a body. it is a loop with a variable that is defined outside (before) the while statement.
Term
What are the parts of a while loop?
Definition

and initializer for the loop variable

 

A way to repeat the statement (while)

 

 

A termination criterion

 

a variable to keep track of how many times we have been through the loop (a loop variable/control variable)

 

The loop body, delimited by curly braces, that writes out something to do each time around the loop.

 

 

 

Term
What is a sequence of statements delimited by curly braces?
Definition
A block or a compound statement.
Term
What is a for statement?
Definition
A for statement is like a while statement, except that the management of the control variable is concentrated at the top where it is easy to see and understand.
Term
Give an example of a for statement
Definition

int main()

{

   for (int i=0; i<100; ++i)

      cout<<i<<'\t'<<square(i)<<'\n';

}

Term
Why is it more advantageous to use a for statement instead of a while statement
Definition
for statement yields more easily understood and more maintainable code whenever a loop can be defined as a for statement with a simple initializer, condition, and increment operation.
Term

What is wrong with this code?

 

int main()

{

   for (int i=0; i<100; ++i){

      cout<<i<<'\t'<<square(i0<<'\n';

      ++i;

   }

}

Definition

the ++i at the end of the body ensures that i is incremented twice, so instead of giving the squares of 100 values, it will give the squares of the 50 even values of i.

 

Term
Function
Definition
A named sequence of statements. A function can return a result (also called a return value). The standard library provides a lot of useful fucntions, such as the square root function sqrt().
Term
Write a function for a definition of square.
Definition

int square(int x)

{

   return x*x

}

Term

What does this function do?

 

int square(int x)

{

   return x*x

}

Definition
The first line of this definition tells us that this is a function that is called square, that takes an int argument, here called x. It returns an int.
Term

How could this function be used in another function?

 

int square(int x)

{

   return x*x

}

Definition

int main()

{

   cout<<square(2)<<'\n';       //prints 4

   cout<<square(10)<<'\n';      //prints 100

Term

Why would the following functions return an error?

 

square(2);

int v1 = square();

int v2 = square;

int v3 = square (1,2)

int v3 = square("two")

Definition

unused return value

argument missing

parethesis missing

too many arguments

wrong type of argument, int expected

 

Term
What is a function body?
Definition
The block (body) of the function that actually does the work.
Term
What is the syntax of a function definition?
Definition
type identifier (parameter list) function body
Term
Parameter-list
Definition
The list of arguments required by the function is called a parameler list and its elements are called parameters (or formal arguments).
Term
Void
Definition

When a function takes no argument and returns no value. 

 

ex.

void write_sorry()

{   

   cout << "sorry\n";

}

Term
Why do we use multiple functions?
Definition

Makes the computation logically separate

 

Makes the program text clearer (by naming the computation)

 

Makes it possible to use the function in more than one place in our program

 

Eases testing

 

Term

What do these functions do?

 

void print_square(int v)

{

   cout<<v<<'\t'<<v*v<<'\n';

}

 

int main()

{

   for (int i=0; i<100; ++i) print_square(i)

}

Definition

print_square performs two logically seperate actions. It prints and it calculates a square. Then, main calls the print_square function in a form loop so long that i<100.

 

This program is of poor design, because it is generally better for a function to perform only one action, whereas print_square performs two. 

 

Term
What is a function declaration?
Definition

a way of supplying that information separate

from the complete function definition.

 

ex.

int square(int);         //declaration of square

double sqrt(double);  //declaration of sqrt

Term
Vector
Definition

A vector is simply a sequence of elements that you can access by index. Vectors start at 0, so for example, if we had

 

vector<int>v(6)

 

we have a vector that stores integers into six slots, 0-5. 

 

example:

 

vector<int>v(6);

v[0] =#;

v[1] =#;

v[2] =#;

v[3] =#;

v[4] =#;

v[5] =#;

Term
What do you need to do in order to make a vector?
Definition
You must specify the type of the elements (in brackets) and the initial number of elements (in parenthesis).
Term

Through what numbers would this vector be able to store elements?

 

vector<string>philosopher(4)

Definition
0-3
Term
Will a vector accept elements outside of its element type?
Definition
No
Term
Can you refer to a nonexistant element of a vector? If not, why?
Definition
No, this is known as a range error.
Term
What is the member function call for determining a vector's size?
Definition
v.size()
Term
define the operation push_back()
Definition

an operation that adds a new element to a vector. 

 

example: 

vector<double>v;

 

v.push_back(5.6);

 

v.push_back(7.9);

 

this would end with the vector v having 2 elements, 

 

v[0]==5.6

v[1]==7.9

Term
What is push_back known as?
Definition

a member function call. Push_back is a member function cvector and must be called using the dot notation:

 

object_name.member-function-name (argument list)

Term

What does this code do?

 

int main()

{

   vector<double>temps;

   double temp;

   while(cin>>temp)

   temps.push_back(temp);

   //...do something

}

Definition

first a vector is declared to hold data and a variable into which we can read each number as it comes in. It will read and store only doubles.

 

While the user is inputting numbers, they may continue input until they break the loop by inputting something else. 

 

These doubles (temp) are pushed back into the temps vector.

 

Now we can do whatever we want with the information we've gained. 

Term
Write a function for looping through the elements of a size 3 vector.
Definition

for (int i=0; i<v.size(); ++i);

   cout<<"v["<<i<<"]=="<<v[i]<<'\n';

Term

Identify what every aspect of this code dose. 

 

int main()

{

   vector<double>temps;

   double temp;

   while(cin>>temp)

   temps.push_back(temp);

   

   double sum=0;

   for (int i=0; i<temps.size(); ++i) sum+=temps[i]

   cout<<"average temperature: " <<sum/temps.size()<< endl; 

 

   sort(temps.begin(),temps.end());

   

   cout<<"Median temperature: "<<temps[temps.size()/2]<<endl;

}






 

Definition

first a vector is declared to hold data and a variable into which we can read each number as it comes in. It will read and store only doubles.

 

While the user is inputting numbers, they may continue input until they break the loop by inputting something else. 

 

These doubles (temp) are pushed back into the temps vector.

 

now, for i>the number of elements in temps, the fpr loop will continue. sum is equal to (0+the number of elements in the vector).

 

The function now outputs the average temperature by dividing the sum of all of the elements by the number of vector elements. 

 

Now the member call function sorts the temperatures from beginning to end.

 

Now the function outputs the median temperature, which is the element number that is equal to temps.size()/2 (because that calculates the number that is in the exact middle of the list of the vector elements)

Term

What does this program do?

 

int main()

{

   vector<string>words;

   string temp;

   while (cin>>temp)

      words.push_back(temp);


   cout<<"Number of words: " <<words.size()<<endl;


   sort(words.begin(),words.end());

   

   for (int=0 || words[i-1]!=words[i])

      cout<<words[i]<<"\n";

}


Definition

It takes in string elements into the vector words, outputs the number of words you input, and then sorts the words from beginning to end (alphabetical order). Then it outputs all of the words you typed in without repeated words; however there was no way coded to stop the input stream of cin>>temp, so the user has to use ctrl+z to stop the input stream. 

 

The line

 

if (i==0 || words[i-1]!=words[i]) 

 

is what is used to check and see if the previous word is the same as the next word. 

Term
Compile time error
Definition

Errors found by the compiler. We can further classify

compile-time errors based on which language rules they violate, for example:

Syntax errors

Type errors

Term
Link time errors
Definition

Errors found by the linker when it is trying to combine

object files into an executable program.

Term
Run-time errors
Definition

Errors found by checks in a ru nning program. We can

further classify run-time errors as:

Errors detected by the computer (hardware and/or operating system)

Errors detected by a library

Errors detected by user code

Term
Logic errors
Definition
Errors found by the programmer looking for causes of erroneous results
Term
What are the three approaches to producing acceptable software?
Definition

Organize software to minimize errors.

 

Eliminate most of the errors we made through debugging and testing.

 

Make sure the remaining errors are not serious.

Term
What is poor specification?
Definition

If we are not specific about what a program should do,

we are unlikely to adequately examine the "dark corners" and make sure that all cases are handled (i.e., that every input gives a correct answer or an adequate error message).

Term
What do incomplete programs mean in regards to errors?
Definition

During development, there are obviously cases that

we haven't yet taken care of. That's unavoidable. What we must aim for is to know when we have handled all cases.

Term
What are unexpected arguments in regards to errors?
Definition

Functions take arguments. If a function is given an

argument we don't handle, we have a problem. An example is calling the standard library square root function with - 1.2: sqrt(-1.2). Since sqrt()

of a double returns a double, there is no possible correct return value.

 

Term
What is unexpected input in regards to errors?
Definition

Programs typically read data (from a keyboard. from

files, from GUls, from network connections, etc.). A program makes many assumptions about such input, for example, that the user will input a number. What if the user inputs "aw, fudge!" rather than the expected integer? 

Term
what is an unexpected state
Definition
Most programs keep a lot ofr data ("state") around ror use  by different parts or the system. Examples are address lists, phone directories, and vectors of temperature readings. what if such data is incomplete or wrong? The various parts or the program must still manage.
Term
What are logical errors?
Definition
code that simply doesn't do what it was supposed to do; we'll just have to find and fix such problems.
Term

what kind of error are these?

 

int s1=area(7;

 

int s1=area(7)

 

Int s2=area(7):

 

 

Definition
syntax errors
Term

What kind of errors are these?

int x0=arena(7);

int x1=area(7);

int x2=area("seven",2);

Definition

Type errors.

In order:

undeclared function

wrong number of arguments

1st argument has wrong type

Term

What kind of errors are these?

 

int x4=area(10,-7)

int x5=area(20.6,9.3)

char x6=area(100,9999)

Definition

They are known as non errors because the compiler won't return an error message. In order, the problems these have are: 

 

Logically, you can't have a rectangle with a width of -7

the area function only uses ints, so it would call area(20,9)

it will be assigned to a char, causing the compiler to truncate the result, resulting in the output -36.

 

Term
What are translation units?
Definition
Several seperately compiled parts. Every function in a program must be declared with exactly the same type in every translation unit in which it is used
Term

What kind of error would this program give? 

 

int area(int length , int width); 

 

int main()

{

int x= area(2,3);

}

Definition
a linker error, due to area not being defined in the function it is used in.
Term
What does it mean for a caller to deal with errors?
Definition

It means that the program itself will protect the call of the function in main. for example:

area is a function in a library where we can't modify it.

 

if (x<=0) error("non-positive x");

if (y<=0) error("non-positive y");

int area1 = area(x,y);

Term

Why is the following code wrong?

 

int area(int x, int y){ .... }

 

.....

 

 

double area(double x, double y)

Definition

The area function only calculates the area of ints, as defined earlier. Functions with the same name but different types will not match and will be

ignored.

Term

What is wrong with this program?


int area(int length, int width)

{

   return length*width ;

}


int framed_area(int x, int y)

{

   return area(x-2,y-2);

}


int main()

{

   int x= -1;

   int y = 2;

   int z = 4;

   //...

   int area = area(x,y);

   int area1 = framed_area(1,z);

   int area3 = framed_area(y,z);

   double ratio = double(area1)/area3; 

}

Definition

these calls lead to negative values, representing areas, being assigned to area1 and area2.

 

area3 will be 0, so that double(area1)/area3 divides by zero. this leads to a hardware-detected error that teminates the program with some

cryptic message relating to hardware.

Term
What is the error() function?
Definition
It by default terminates the program with a system error message plus the string we passed as an argument to error.
Term
What does it mean when the callee deals with errors?
Definition

It means that the function itself does the error checking, instead of the other function that calls it.

 

Term
Why wouldn't you add checking arguments for errors in a function?
Definition

sometimes we can't modify the function definition

sometimes the called function doesn't know what to do in case of an error

sometimes the called function doesnt know where it was called from

Sometimes adding checks to every function causes performance loss, or raises the cost of a program.

Term

In this program, what is doing the error checking?

 

char ask_user(string question)

{

cout « question « "? (yes or no)\n";

string answer = " ";

cin»answer;

if (answer =="y" || answer=="yes") return 'y';

if (answer =="n" || answer==" no") return 'n';

return 'b'; 

}

 

 

Definition
The called function
Term
What problems can arise from a callee doing its own error checking?
Definition

Now both the called function and all callers must test. The caller hasonly a simple test to do but must still write that test and decide what to do if it fails.

 

A caller can forget to test. That can lead to unpredictable behavior further along in the program.

Term
exceptions
Definition

The basic idea is that if a function finds an error that it cannot handle, it does not return normally; instead, it throws an exception indicating what went wrong.

Any direct or indirect caller can catch the exception, that is, specify what to do if the called code used throw. A function expresses interest in exceptions by using a try block listing the kinds of exceptions it wants to handle in the catch parts of the try block. if no caller catches an exception, the program terminates. 

Term

What is this?

 

class Bad_area {};

Definition
A type specifically for reporting errors from area()
Term

What does this code do?

 

class Bad_area {};

 int area(int length, int width)

{

   if (length<=0 || width<=0) throw Bad_area();

   return length*width;

}

Definition
It calculates the area of a rectangle and throws a bad area exception in case of a bad argument.
Term

What does this code do?

 

int main()

try {

      int x=-1

      int y=2

      int z=4

      //.... code here

      int area1 = area(x,y);

      int area2 = framed_area(1,z)

      int area3 = framed_area(y,z)

      double ratio = area1/area3;

}


catch (Bad_area) {

      cout<<"Oops! Bad arguments to area()\n";

}

Definition
that this handles all calls to area() , both the one in main() and the two through framed_area().
Term
What is a container, and what is the most common and useful container?
Definition
Collections of data. Vectors.
Term

What error is caused by this code, and why?

 

vector<int>v;

int i;

while (cin>>i) v.push_back(i)

for (int i=0; i<=v.size(); ++i)

   cout<<"v["<<i<<"]=="v[i]<<endl;

Definition

the termination condition is i<=v.size() rather than the correct i<v.size(). This has the unfortunate

consequence that if we read in five integers we' ll try to write out six. We try to read v[5], which is one beyond the end of the vector.

Term
What is a bounds error?
Definition

the index was not within the limits (bounds)

of the vector.

Term

What is the error caused by this code?

 

vector<int> v[5];

inl x = v[5];

Definition
a range error, due to v[5] not existing.
Term
What is the cause of the out_of_range exception?
Definition
When a check fails in regards to something having to do with a vector's range.
Term
How can we test if the last input operation succeeded?
Definition

if (cin) {

//all is well

}

else {

didnt succeed, do something else

}

Term
Write a function for an input error where a double's variable was not input.
Definition

double some_function()

{

   double d=0;

   cin>>d;

   if (!cin) error("couldn't read a double in 'some function()'");

 

}

Term
cerr
Definition
cerr and cout write to the screen, but cerr isn't optimized so it is more resilient to errors, and on some operating systems it can be diverted to a different target, such as a file. Using cerr also has the simple effect of documenting that what we write relates to errors. Consequently, we use cerr for error messages.
Term
runtime_error
Definition

When we deal with a runtime error, we simply want to catch it. so...

 

void error(string s)

{

   throw runtime_error(s)

}

 

int main()

try {

 

//our program

 

return 0;

}

 

catch (runtime_error& s){

   cerr<<"runtime error: "<<s.what()<<'\n';

keep_window_open()

return 1;

}

Term
is out_of_range a runtime_error?
Definition

No, so catching runtime_error does not deal with the out_of range errors that we might get from misuse of

vectors and other standard library container types. However, both out_of_range

and runtime_error are "exceptions," So we can catch exception to deal with both:

 

int mainO

try {

                        // our program

return 0;            // 0 indicates success

}


catch (exception& e) {

cerr « "error:«e.what()« '\n ';

keep_window_open();

return 1;           // 1 indicates failure

}  

               

catch ( ... ){

cerr « "Oops: unknown exception!\n " ;

keep_window_open();

return 2;               //2 indicates failure

}

Term
catch( ... )
Definition
Handles exceptions of any type whatsoever
Term

What does this code do?

 

void error(string s1, string s2)

{

throw runtime_error(s1 +s2);

{

Definition
concatonates two strings to pass on two pieces of information to describe an error, and is simple enough to work for basic programming.
Term
What is narrow_cast, and what does it do?
Definition

it is a runtime_error exception that throws an exception is an assignment or initialization would lead to a changed value. We use narrow cast when we need to convert a value and we are not sure if it will fit. It is defined in std_lib_facilities.h and implemented using error(). the word cast means type conversion.

 

ex.

 

int x1 = narrow_cast<int>(2.9)   //Gets thrown

int x2 = narrow_cast<int>(2.0) //is ok

Term

What is the logical error in this code?


int main()

{

   vector<double> temps;

   double temp = 0;

   double sum = 0;

   double high_temp = 0;

   double low_temp = 0;

 

   while (cin» temp) 

      temps. push_back(temp);

   for (int i = 0; i<temps.size(); ++i)

   {

      if(temps[i] > high_temp) high_temp = temps[i];

      if(temps[i] < low_temp) low_temp = temps[i];

      sum += temps[i];

    }

   cout « "High temperature: " « high_temp« endl;

   cout « "Low temperature : " « low_temp« endl;

   cout « "Average temperature: " « sum/temps.size() « endl;

}

Definition

If you have to deal with a set of temperatures that does not have a low temp that is below 0, it will not change the initialization of low temp to the new temp.

 

If all of the temperatures are below zero, the intitalization for high temp would be the same problem.

Term

What is the logical error in this code?


int main()

{

   vector<double> temps;

   double temp = 0;

   double sum = 0;

   double high_temp = -1000;

   double low_temp = 1000;

 

   while (cin» temp) 

      temps. push_back(temp);

   for (int i = 0; i<temps.size(); ++i)

   {

      if(temps[i] > high_temp) high_temp = temps[i];

      if(temps[i] < low_temp) low_temp = temps[i];

      sum += temps[i];

    }

   cout « "High temperature: " « high_temp« endl;

   cout « "Low temperature : " « low_temp« endl;

   cout « "Average temperature: " « sum/temps.size() « endl;

}

Definition
the initialization of hightemp and lowtemp are magic constants, and are outside the reasonable results for inputs. We should have this program have a hightemp/lowtemp initializer that is "within reason", temperatures that you can actually find on earth. This limits the "usefulness" of our program, but stays in good taste.
Term
Estimization
Definition
an informal set of techniques that are sometimes (humorously) called guesstimation combine a bit of guessing with a bit of calculation. Often, making an estimate involves coming up with estimates of data that are needed for a proper calculation, but that we don't yet have.
Term
debugging
Definition

The act of deliberately searching for errors and removing them. It usually works like...

1. Get the program to compile.

2. Get the program to link.

3. Get the program to do what it is supposed to do.

Term
How NOT to debug
Definition

while {the program doesn't appear to work) {      // pseudo code

   Randomly look through the program for something that "looks odd"

   Change it to look better

}

Term
assertion
Definition
A statement that states (asserts) an invariant
Term
invariants
Definition
conditions that should always hold
Term

What requirement is a compiler going to catch here?

 

int x = my_complicated_function(1, 2, "horsefeathers");

 

Definition

Here, the compiler will catch that the requirement ("precondition") that the third

argument be an integer was violated.

Term

What conditions are checked in this program? What happens to these checked conditions? 


//calculate area of a rectangle;

// throw a Bad_area exception in case of a bad argument


int area(int length, inl width)

{

if (length<=0 || width <=0) throw Bad_area();

return length*width;

 }


int area(int length, int width)

}

if (length<=-0 || width <=0) error("area() pre-condition");

int a = length*width;

if (a<=0) error("area() post-condition");

return a;

}

Definition

What conditions are checked in this program? What happens to these checked conditions? 

 

 preconditions: length and width are positive

 post-condition: returns a positive value that is the area



Term
Pre condition
Definition

A requirement of a function upon its argument.

 

 int my_complicated_funclion (int a, int b, int c)

// the arguments are positive and a < b < c

{

if (!(0<a && a<b && b<c»))

error("bad arguments for mcf") ;


//...


}

Supporting users have an ad free experience!