Monday, April 10, 2017

Navid Plus: C++ Part 44

Navid Plus: C++ Part 44: An array is used to process a collection of data all of which is of the same type, such as a list of numbers or a list of names. An array...

C++ Part 44

An array is used to process a collection of data all of which is of the same type, such as a list of numbers or a list of names.
An array behaves like a list of variables with a uniform naming mechanism that can be declared in a single line of simple code.
Declaring and Referencing Arrays
In C++, an array consisting of five variables of type int can be declared as follows:
int score[5];
This declaration is like declaring the following five variables to all be of type int:
score[0], score[1], score[2], score[3], score[4]
We will call them indexed variables, though they are also sometimes called subscripted variables or elements of the array. The number in square brackets
is called an index or a subscript.




Tuesday, March 28, 2017

C++ Part 43

Review Part VI

Parameters and Arguments
All the different terms that have to do with parameters and arguments can
be confusing. However, if you keep a few simple points in mind, you will
be able to easily handle these terms.
1. The formal parameters for a function are listed in the function declaration
and are used in the body of the function definition. A formal parameter (of
any sort) is a kind of blank or placeholder that is filled in with something
when the function is called.
2. An argument is something that is used to fill in a formal parameter. When
you write down a function call, the arguments are listed in parentheses after
the function name. When the function call is executed, the arguments are
“plugged in” for the formal parameters.
3. The terms call-by-value and call-by-reference refer to the mechanism that is
used in the “plugging in” process. In the call-by-value method only the value
of the argument is used. In this call-by-value mechanism, the formal parameter is a local variable that is initialized to the value of the corresponding argument.
In the call-by-reference mechanism the argument is a variable and the entire
variable is used. In the call-by-reference mechanism, the argument variable is
substituted for the formal parameter so that any change that is made to the
formal parameter is actually made to the argument variable.

A File Has Two Names
Every input and every output file used by your program has two names.
The external file name is the real name of the file, but it is used only in
the call to the function open, which connects the file to a stream. After the
call to open, you always use the stream name as the name of the file.

Calling a Member Function
SYNTAX
Calling _Object.Member_Function_Name(Argument_List);
EXAMPLES
in_stream.open("infile.dat");
out_stream.open("outfile.dat");
out_stream.precision(2);
The meaning of the Member_Function_Name is determined by the class of
(that is, the type of) the Calling _Object.


Classes and Objects
An object is a variable that has functions associated with it. These
functions are called member functions. A class is a type whose variables
are objects. The object’s class (that is, the type of the object) determines
which member functions the object has.

The exit Statement
The exit statement is written
exit(Integer_Value);
When the exit statement is executed, the program ends immediately. Any
Integer_Value may be used, but by convention, 1 is used for a call to
exit that is caused by an error, and 0 is used in other cases. The exit
statement is a call to the function exit, which is in the library with header
file named cstdlib. Therefore, any program that uses the exit statement
must contain the following directives:
#include
using namespace std;
(These directives need not be given one immediately after the other. They
are placed in the same locations as similar directives we have seen.)

Summary of File I/O Statements
In this sample the input comes from a file with the directory name infile.dat, and the output
goes to a file with the directory name outfile.dat.
■ Place the following include directives in your program file:
#include
#include
#include
■ Choose a stream name for the input stream (for example, in_stream), and declare it to be a variable
of type ifstream. Choose a stream name for the output file (for example, out_stream), and declare
it to be of type ofstream:
using namespace std;
ifstream in_stream;
ofstream out_stream;
■ Connect each stream to a file using the member function open with the external file name as an argument.
Remember to use the member function fail to test that the call to open was successful:
in_stream.open("infile.dat");
if (in_stream.fail( ))
{
cout << "Input file opening failed.\n"; exit(1); } out_stream.open("outfile.dat"); if (out_stream.fail( )) { cout << "Output file opening failed.\n"; exit(1); } ■ Use the stream in_stream to get input from the file infile.dat just like you use cin to get input from the keyboard. For example: in_stream >> some_variable >> some_other_variable;
■ Use the stream out_stream to send output to the file outfile.dat just like you use cout to send
output to the screen. For example:
out_stream << "some_variable = " << some_variable << endl; ■ Close the streams using the function close: in_stream.close( ); out_stream.close( );

Appending to a File
If you want to append data to a file so that it goes after any existing
contents of the file, open the file as follows.
SYNTAX
Output_Stream.open(File_Name, ios::app);
EXAMPLE
ofstream outStream;
outStream.open("important.txt", ios::app);

'\n' and "\n"
'\n' and "\n" sometimes seem like the same thing. In a cout statement,
they produce the same effect, but they cannot be used interchangeably in
all situations. '\n' is a value of type char and can be stored in a variable
of type char. On the other hand, "\n" is a string that happens to be made
up of exactly one character. Thus, "\n" is not of type char and cannot be
stored in a variable of type char.



Wednesday, March 22, 2017

C++ Part 42

Review Part V
Local Variables
Variables that are declared within the body of a function definition are
said to be local to that function or to have that function as their scope.
Variables that are declared within the main part of the program are said to
be local to the main part of the program or to have the main part of the
program as their scope. When we say that a variable is a local variable
without any mention of a function and without any mention of the main
part of the program, we mean that the variable is local to some function
definition. If a variable is local to a function, then you can have another
variable with the same name that is declared in the main part of the
program or in another function definition, and these will be two different
variables, even though they have the same name.

Overloading a Function Name
If you have two or more function definitions for the same function name,
that is called overloading. When you overload a function name, the
function definitions must have different numbers of formal parameters or
some formal parameters of different types. When there is a function call,
the compiler uses the function definition whose number of formal
parameters and types of formal parameters match the arguments in the
function call.

Call-by-Reference
To make a formal parameter a call-by-reference parameter, append the
ampersand sign & to its type name. The corresponding argument in a call
to the function should then be a variable, not a constant or other
expression.
When the function is called, the corresponding variable argument
(not its value) will be substituted for the formal parameter. Any
change made to the formal parameter in the function body will be made
to the argument variable when the function is called. The exact details of
the substitution mechanisms are given in the text of this chapter.
EXAMPLE
(OF CALL-BY-REFERENCE PARAMETERS IN A FUNCTION
DECLARATION):
void get_data(int& first_in, double& second_in);

Both void functions and functions that return a value can have return
statements. In the case of a function that returns a value, the return statement
specifies the value returned. In the case of a void function, the return
statement simply ends the function call.


C++ Part 41

Review Part IV

Function Call
A function call is an expression consisting of the function name followed
by arguments enclosed in parentheses. If there is more than one argument,
the arguments are separated by commas. A function call is an expression
that can be used like any other expression of the type specified for the
value returned by the function.
SYNTAX
Function_Name(Argument_List)
where the Argument_List is a comma-separated list of arguments:
Argument_1, Argument_2, . . . , Argument_Last
EXAMPLES
side = sqrt(area);
cout << "2.5 to the power 3.0 is " << pow(2.5, 3.0);

A Function to Convert from int to double
The notation static_cast can be used as a predefined function
and will convert a value of some other type to a value of type double. For
example, static_cast(2) returns 2.0. This is called type casting.
(Type casting can be done with types other than double, but until later in
this book, we will do type casting only with the type double.)
SYNTAX
static_cast(Expression_of_Type_int)
EXAMPLE
int total_pot, number_of_winners;
double your_winnings;
. . .
your_winnings =
static_cast(total_pot)/number_of_winners;

Function Declaration
A function declaration tells you all you need to know to write a call to the
function. A function declaration is required to appear in your code prior to
a call to a function whose definition has not yet appeared. Function
declarations are normally placed before the main part of your program.
SYNTAX
Type_Returned Function_Name(Parameter_List);
Function_Declaration_Comment
where the Parameter_List is a comma-separated list of parameters:
Type_1 Formal_Parameter_1, Type_2 Formal_Parameter_2,...
..., Type_Last Formal_Parameter_Last
Example
double total_weight(int number, double weight_of_one);
//Returns the total weight of number items that
//each weigh weight_of_one.

A Function Is Like a Small Program
To understand functions, keep the following three points in mind:
■ A function definition is like a small program and calling the function is the
same thing as running this “small program.”
■ A function uses formal parameters, rather than cin, for input. The arguments to
the function are the input and they are plugged in for the formal parameters.
■ A function (of the kind discussed in this chapter) does not normally send any output
to the screen, but it does send a kind of “output” back to the program. The
function returns a value, which is like the “output” for the function. The function
uses a return statement instead of a cout statement for this “output.”

Procedural Abstraction
When applied to a function definition, the principle of procedural
abstraction means that your function should be written so that it can be
used like a black box. This means that the programmer who uses the
function should not need to look at the body of the function definition to
see how the function works. The function declaration and the accompanying
comment should be all the programmer needs to know in order to use
the function. To ensure that your function definitions have this important
property, you should strictly adhere to the following rules:
HOW TO WRITE A BLACK-BOX FUNCTION DEFINITION (THAT RETURNS
A VALUE)
■ The function declaration comment should tell the programmer any and all conditions
that are required of the arguments to the function and should describe
the value that is returned by the function when called with these arguments.
■ All variables used in the function body should be declared in the function body.
(The formal parameters do not need to be declared, because they are listed in
the function declaration.)

Make a Loop Body a Function Call
Whenever you have a loop nested within a loop, or any other complex
computation included in a loop body, make the loop body a function call.
This way you can separate the design of the loop body from the design of
the rest of the program. This divides your programming task into two
smaller subtasks.

C++ Part 40

Review Part III
Naming Constants with the const Modifier
When you initialize a variable inside a declaration, you can mark the
variable so that the program is not allowed to change its value. To do this
place the word const in front of the declaration, as described below:
SYNTAX const Type_Name Variable_Name = Constant;
EXAMPLES const int MAX_TRIES = 3;
const double PI = 3.14159;

Boolean (bool) values are true and false
In C++, a Boolean expression evaluates to the bool value true when it is
satisfied and to the bool value false when it is not satisfied.
The Type bool Is New
Older versions of C++ have no type bool, but instead use the integers 1 and
0 for true and false. If you have an older version of C++ that does not
have the type bool, you should obtain a new compiler.


Multiway if-else Statement
SYNTAX
if (Boolean_Expression_1)
Statement_1
else if (Boolean_Expression_2)
Statement_2
.
.
.
else if (Boolean_Expression_n)
Statement_n
else
Statement_For_All_Other_Possibilities
EXAMPLE
if ((temperature < −10) && (day == SUNDAY)) cout << "Stay home."; else if (temperature < −10) //and day != SUNDAY cout << "Stay home, but call work."; else if (temperature <= 0) //and temperature >= −10
cout << "Dress warm."; else //temperature > 0
cout << "Work hard and play hard."; The Boolean expressions are checked in order until the first true Boolean expression is encountered, and then the corresponding statement is executed. If none of the Boolean expressions is true, then the Statement_For_All_Other_Possibilities is executed.

Blocks
A block is some C++ code enclosed in braces. The variables declared in a
block are local to the block and so the variable names can be used outside
of the block for something else (such as being reused as the name for a
different variable).

Scope Rule for Nested Blocks
If an identifier is declared as a variable in each of two blocks, one within
the other, then these are two different variables with the same name. One
variable exists only within the inner block and cannot be accessed outside
of the inner block. The other variable exists only in the outer block and
cannot be accessed in the inner block. The two variables are distinct, so
changes made to one of these variables will have no effect on the other of
these two variables.


The break Statement
The break statement can be used to exit a loop statement. When the
break statement is executed, the loop statement ends immediately and
execution continues with the statement following the loop statement. The
break statement may be used in any form of loop, in a while loop, in a dowhile
loop, or in a for loop. This is the same break statement that we
have already used in switch statements.

Repeat “This Many Times”
A for statement can be used to produce a loop that repeats the loop body
a predetermined number of times.
Pseudocode
Repeat the following This_Many times:
Loop_Body
Equivalent for Statement
for (int count = 1; count <= This_Many; count++) Loop_Body Example for (int count = 1; count <= 3; count++) cout << "Hip, Hip, Hurray\n";

Testing a Loop
Every loop should be tested with inputs that cause each of the following
loop behaviors (or as many as are possible): zero iterations of the loop
body, one iteration of the loop body, the maximum number of iterations
of the loop body, and one less than the maximum number of iterations of
the loop body. (This is only a minimal set of test situations. You should also
conduct other tests that are particular to the loop you are testing.)

Debugging a Very Bad Program
If your program is very bad, do not try to debug it. Instead, throw it out
and start over.

C++ Part 39

Review Part II
Starting New Lines in Output
To start a new output line, you can include \n in a quoted string, as in the
following example:
cout << "You have definitely won\n" << "one of the following prizes:\n"; Recall that \n is typed as two symbols with no space in-between the two symbols. Alternatively, you can start a new line by outputting endl. An equivalent way to write the above cout statement is as follows: cout << "You have definitely won" << endl << "one of the following prizes:" << endl;

Outputting Values of Type double
If you insert the following “magic formula” in your program, then all
numbers of type double (or any other type that allows for digits after the
decimal point) will be output in ordinary everyday notation with two digits
after the decimal point:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
You can use any other nonnegative whole number in place of the 2 to
specify a different number of digits after the decimal point. You can even
use a variable of type int in place of the 2

cin Statements
A cin statement sets variables equal to values typed in at the keyboard.
SYNTAX cin >> Variable_1 >> Variable_2 >> . . . ;
EXAMPLE cin >> number >> size;
cin >> time_to_go
>> points_needed;

The “and” Operator &&
You can form a more elaborate Boolean expression by combining two
simple tests using the “and” operator &&.
SYNTAX (FOR A BOOLEAN EXPRESSION USING &&)
(Comparison_1) && (Comparison_2)
EXAMPLE
(WITHIN AN if-else STATEMENT)
if ( (score > 0) && (score < 10) ) cout << "score is between 0 and 10\n"; else cout << "score is not between 0 and 10.\n"; If the value of score is greater than 0 and the value of score is also less than 10, then the first cout statement will be executed; otherwise, the second cout statement will be executed.

The “or” Operator ||
You can form a more elaborate Boolean expression by combining two
simple tests using the “or” operator ||.
SYNTAX (FOR A BOOLEAN EXPRESSION USING ||)
(Comparison_1) || (Comparison_2)
EXAMPLE
(WITHIN AN if-else STATEMENT)
if ( (x == 1) || (x == y) )
cout << "x is 1 or x equals y.\n";
else
cout << "x is neither 1 nor equal to y.\n";
If the value of x is equal to 1 or the value of x is equal to the value of y (or
both), then the first cout statement will be executed; otherwise, the
second cout statement will be executed.