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.

C++ Part 38

Review Part I
Identifiers
Identifiers are used as names for variables and other items in a C++
program. An identifier must start with either a letter or the underscore
symbol, and the remaining characters must all be letters, digits, or the
underscore symbol.

Variable Declarations
All variables must be declared before they are used. The syntax for variable
declarations is as follows:
SYNTAX Type_Name Variable_Name_1, Variable_Name_2, . . .;
EXAMPLES:
int count, number_of_dragons, number_of_trolls;
double distance;

Syntax
The syntax for a programming language (or any other kind of language) is
the set of grammar rules for that language. For example, when we talk
about the syntax for a variable declaration (as in the box labeled “Variable
Declarations”), we are talking about the rules for writing down a well-formed
variable declaration. If you follow all the syntax rules for C++, then
the compiler will accept your program. Of course, this only guarantees that
what you write is legal. It guarantees that your program will do something,
but it does not guarantee that your program will do what you want it to do.

Assignment Statements
In an assignment statement, first the expression on the right-hand side of
the equal sign is evaluated, and then the variable on the left-hand side of
the equal sign is set equal to this value.
SYNTAX Variable = Expression;
EXAMPLES distance = rate * time;
count = count + 2;

Initializing Variables in Declarations
You can initialize a variable (that is, give it a value) at the time that you
declare the variable.
SYNTAX
Type_Name Variable_Name_1 = Expression_ for_Value_1,
Variable_Name_2 = Expresssion_ for_Value_2, . . .;
EXAMPLES
int count = 0, limit = 10, fudge_factor = 2;
double distance = 999.99;
Alternative Syntax for Initializing in Declarations
Type_Name Variable_Name_1 (Expression_ for_Value_1),
Variable_Name_2 (Expression_ for_Value_2), . . .;



C++ Part 37

I/O Stream Example :

//Reads three numbers from the file infile.txt, sums the numbers,
//and writes the sum to the file outfile.txt.
#include <fstream>
using std::ifstream;
using std::ofstream;
using std::endl;
int main( )
{
ifstream inStream;
ofstream outStream;
inStream.open("infile.txt");
outStream.open("outfile.txt");
int first, second, third;
inStream >> first >> second >> third;
outStream << "The sum of the first 3\n"
<< "numbers in infile.txt\n"
<< "is " << (first + second + third)
<< endl;
inStream.close( );
outStream.close( );
return 0;
}

C++ Part 36

4. Register Storage Class

Register storage assigns a variable's storage in the CPU registers rather than primary memory. It has its lifetime and visibility same as automatic variable. The purpose of creating register variable is to increase access speed and makes program run faster. If there is no space available in register, these variables are stored in main memory and act similar to variables of automatic storage class. So only those variables which requires fast access should be made register.

Syntax of Register Storage Class Declaration

register datatype var_name1 [= value];
For example,
register int id;
register char a;

Example of Storage Class

Example 2: C++ program to create automatic, global, static and register variables.
#include<iostream>
using namespace std;

int g;    //global variable, initially holds 0

void test_function()
{
    static int s;    //static variable, initially holds 0
    register int r;    //register variable
    r=5;
    s=s+r*2;
    cout<<"Inside test_function"<<endl;
    cout<<"g = "<<g<<endl;
    cout<<"s = "<<s<<endl;
    cout<<"r = "<<r<<endl;
}

int main()
{
    int a;    //automatic variable
    g=25;
    a=17;
    test_function();
    cout<<"Inside main"<<endl;
    cout<<"a = "<<a<<endl;
    cout<<"g = "<<g<<endl;
    test_function();
    return 0;
}
In the above program, g is a global variable, s is static, r is register and a is automatic variable. We have defined two function, first is main() and another is test_function(). Since g is global variable, it can be used in both function. Variables r and s are declared inside test_function() so can only be used inside that function. However, s being static isn't destroyed until the program ends. When test_function() is called for the first time, r is initialized to 5 and the value of s is 10 which is calculated from the statement,
s=s+r*2;
After the termination of test_function(), r is destroyed but s still holds 10. When it is called second time, r is created and initialized to 5 again. Now, the value of s becomes 20 since s initially held 10. Variable a is declared inside main() and can only be used inside main().
Output
Inside test_function
g = 25
s = 10
r = 5
Inside main
a = 17
g = 25
Inside test_function
g = 25
s = 20
r = 5

5. Mutable Storage Class

In C++, a class object can be kept constant using keyword const. This doesn't allow the data members of the class object to be modified during program execution. But, there are cases when some data members of this constant object must be changed. For example, during a bank transfer, a money transaction has to be locked such that no information could be changed but even then, its state has be changed from - started to processing to completed. In those cases, we can make these variables modifiable using a mutable storage class.

Syntax for Mutable Storage Class Declaration

mutable datatype var_name1;
For example,
mutable int x;
mutable char y;

Example of Mutable Storage Class

Example 3: C++ program to create mutable variable.
#include<iostream>
using namespace std;

class test
{
    mutable int a;
    int b;
    public:
        test(int x,int y)
        {
            a=x;
            b=y;
        }
        void square_a() const
        {
            a=a*a;
        }
        void display() const
        {
            cout<<"a = "<<a<<endl;
            cout<<"b = "<<b<<endl;
        }
};

int main()
{
    const test x(2,3);
    cout<<"Initial value"<<endl;
    x.display();
    x.square_a();
    cout<<"Final value"<<endl;
    x.display();
    return 0;
}
A class test is defined in the program. It consists of a mutable data member a. A constant object x of class test is created and the value of data members are initialized using user-defined constructor. Since, b is a normal data member, its value can't be changed after initialization. However a being mutable, its value can be changed which is done by invoking square_a() method. display() method is used to display the value the data members.
Output
Initial value
a = 2
b = 3
Final value
a = 4
__________________________________ 
Source: www.programtopia.net, submitted  by:Sagun Shrestha

C++ Part 35

Typical Program Organization

# include <iostream>  //Setup section used by compiler
storage class of a variable defines the lifetime and visibility of a variable.
Lifetime means the duration till which the variable remains active and visibility defines in which module of the program the variable is accessible.
There are five types of storage classes in C++.
They are:
  1. Automatic
  2. External
  3. Static
  4. Register // Next Post
  5. Mutable // Next Post
______________________________

1. Automatic Storage Class

Automatic storage class assigns a variable to its default storage type. auto keyword is used to declare automatic variables. However, if a variable is declared without any keyword inside a function, it is automatic by default.
This variable is visible only within the function it is declared and its lifetime is same as the lifetime of the function as well. Once the execution of function is finished, the variable is destroyed.

Syntax of Automatic Storage Class Declaration

datatype var_name1 [= value];
or
auto datatype var_name1 [= value];

Example of Automatic Storage Class

auto int x;
float y = 5.67;

2. External Storage Class

External storage class assigns variable a reference to a global variable declared outside the given program. extern keyword is used to declare external variables. They are visible throughout the program and its lifetime is same as the lifetime of the program where it is declared. This visible to all the functions present in the program.

Syntax of External Storage Class Declaration

extern datatype var_name1;
For example,
extern float var1;

Example of External Storage Class

Example 1: C++ program to create and use external storage.
File: sub.cpp
int test=100;  // assigning value to test

void multiply(int n)
{
    test=test*n;
}
File: main.cpp
#include<iostream>
#include "sub.cpp"  // includes the content of sub.cpp
using namespace std;

extern int test;  // declaring test

int main()
{
    cout<<test<<endl;
    multiply(5);
    cout<<test<<endl;
    return 0;
}
A variable test is declared as external in main.cpp. It is a global variable and it is assigned to 100 in sub.cpp. It can be accessed in both files. The function multiply() multiplies the value of test with the parameter passed to it while invoking it. The program performs the multiplication and changes the global variable test to 500.
Note: Run the main.cpp program
Output
100
500

3. Static Storage Class

Static storage class ensures a variable has the visibility mode of a local variable but lifetime of an external variable. It can be used only within the function where it is declared but destroyed only after the program execution has finished. When a function is called, the variable defined as static inside the function retains its previous value and operates on it. This is mostly used to save values in a recursive function.

Syntax of Static Storage Class Declaration

static datatype var_name1 [= value];
For example,
static int x = 101;
static float sum;

_________

source:  www.programtopia.net

Tuesday, March 21, 2017

C++ Part 34

The call by reference method of passing arguments to a function copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.
To pass the value by reference, argument reference is passed to the functions just like any other value. So accordingly you need to declare the function parameters as reference types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments.
// function definition to swap the values.
void swap(int &x, int &y) {
   int temp;
   temp = x; /* save the value at address x */
   x = y;    /* put y into x */
   y = temp; /* put x into y */
  
   return;
}
For now, let us call the function swap() by passing values by reference as in the following example:
#include <iostream>
using namespace std;

// function declaration
void swap(int &x, int &y);

int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
 
   cout << "Before swap, value of a :" << a << endl;
   cout << "Before swap, value of b :" << b << endl;

   /* calling a function to swap the values using variable reference.*/
   swap(a, b);

   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;
 
   return 0;
}
When the above code is put together in a file, compiled and executed, it produces the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
 

Sunday, March 19, 2017

C++ Part 33

ASCII - Binary Character Table


Letter
ASCII Code
Binary
Letter
ASCII Code
Binary
a
097
01100001
A
065
01000001
b
098
01100010
B
066
01000010
c
099
01100011
C
067
01000011
d
100
01100100
D
068
01000100
e
101
01100101
E
069
01000101
f
102
01100110
F
070
01000110
g
103
01100111
G
071
01000111
h
104
01101000
H
072
01001000
i
105
01101001
I
073
01001001
j
106
01101010
J
074
01001010
k
107
01101011
K
075
01001011
l
108
01101100
L
076
01001100
m
109
01101101
M
077
01001101
n
110
01101110
N
078
01001110
o
111
01101111
O
079
01001111
p
112
01110000
P
080
01010000
q
113
01110001
Q
081
01010001
r
114
01110010
R
082
01010010
s
115
01110011
S
083
01010011
t
116
01110100
T
084
01010100
u
117
01110101
U
085
01010101
v
118
01110110
V
086
01010110
w
119
01110111
W
087
01010111
x
120
01111000
X
088
01011000
y
121
01111001
Y
089
01011001
z
122
01111010
Z
090
01011010