Tuesday, July 20, 2010

NOTES ON C & C++

Data Types
The following topics are covered in this section:
• Introduction
• Integer
• Floating Type
• Double
• Character
• Boolean
• Data Type Ranges and determining the ranges
• More on Binary Numbers
________________________________________
Every piece of data has to belong to some basic category. Consider a simple example in real life: every number has to be of a particular type. The number 5 is a natural number (or it can be called as a whole number). 6.5 is a real number (it has a decimal point). Similarly, in programming we have what are called as data types. When a variable is declared, the programmer has to specify which data type it belongs to. Only then will the compiler know how many bytes it should allocate for that particular variable. Or in other words, each data type occupies a different memory size and if a variable is declared as belonging to one particular data type it cannot be assigned a different data type value. In simpler terms, suppose the variable ‘x’ is declared such that it can hold only whole numbers; then it cannot (and should not) be assigned some alphabet.
There are two categories of data types: fundamental data types and user-defined data types. The second category of data types will be dealt with later.
The fundamental (or built-in or primitive) data types are:
• Integer
• Floating Point
• Character
• Double
• Bool
The first three data types: integer, floating point and character are used frequently.
________________________________________
Integer (int):
An integer can contain only digits (numbers) from 0 to 9. Examples of integers are:
• 0
• 10
• 345
• 6789
• -23
• -600
It includes positive and negative numbers but the numbers have to be whole numbers. It does accept the decimal point. Hence the following numbers are not integer data types:
• 3.5
• 4.8
• 0.23
These numbers come under the second category (floating point type) and not under integers. If the program has to accept such values from the user do not declare the variable as an integer. If a variable is declared as an integer and the user enters a value of 2.3, the program will assign 2 as the value for that integer variable. Similarly, if the user enters 3.2, the program will assign 3 to the integer variable.
Remember: Once a variable is declared as an integer, it will only store whole numbers (if the user types a value with the decimal point, the program will ignore everything that is typed after the decimal point).
How to declare a variable as belonging to the type integer? The syntax is:
int variable-name;
Each data type occupies a certain amount of memory space. An integer will occupy 2 bytes of memory (which means 16 bits). From this it is possible to calculate the maximum and minimum values that an integer can store. 2^16 = 65536 (hence 65536 different combinations of 16 bits are possible). Divide this by 2 because integers (by default) range from negative to positive values. We have a 0 in between and so subtract one from this to get 32,767. Hence an integer can take values from –32,768 up to +32,767 (a total of 65536 different values).
A natural question springs to mind, "What would happen if a value greater than 32,767 is entered?" Since this value cannot be accommodated within the allocated two bytes, the program will alter the value. It’s not exactly altering the value; it will basically change your value into something different. The user might enter 123456 as the integer value but the program will store it as –7623 or something like that. Whenever you use variables ensure that you have declared them as belonging to the correct data type.
This restriction on maximum range might seem to be a problem. In C++ ‘qualifiers’ can be used to vary the range of fundamental data types. Qualifiers are only supplements to the basic data types and they cannot be used separately on their own. They work only with a basic (or fundamental) data type. The 4 qualifiers available in C++ are:
1. Short
2. Long
3. Signed
4. Unsigned
Signed and unsigned integers were discussed in the first chapter. When an integer is specified as signed, then automatically the most significant bit of the number is used as a sign bit (to denote the sign of the number). Hence it can be used if the programmer needs positive and negative number values for the variable. By declaring a variable as an integer, by default you can specify both positive and negative values. By default an integer is a signed integer. In other words,
int variable-name;
is the same as
signed int variable-name;
In the second form, ‘signed’ is the qualifier and it is used to explicitly state that the variable is a signed integer. For an unsigned integer the syntax will be:
unsigned int variable-name;
An unsigned integer can hold a value up to 65,535 (a signed integer can hold only up to 32,767). Of course, in an unsigned integer you cannot assign a negative value. The range is from 0 to 65,535. To go beyond 65,535 and make use of both positive and negative values as well, the qualifier long should be used.
long int variable-name;
Long integers occupy 4 bytes of memory (32 bits). Remember, long int actually means signed long int (you can give positive and negative values).
If you specify
unsigned long int variable-name;
you can only assign positive values to the variable. Thus, two qualifiers can be used together with a basic data type.
What about the ‘short’ qualifier? Short integer is the same as a signed integer. It occupies two bytes and has the same range of positive and negative values as the normal integer case.
int x;
is usually the same as
short int x;
Compilers (depending on the operating system) will assume ‘int’ as a ‘long int’ or a ‘short int’. VC++ (since it works in the Windows OS) will default to ‘long int’ if you specify a variable as type ‘int’ (i.e. it will allocate 4 bytes to an ‘int’ variable). Turbo C++ (which is a DOS based compiler) will default to ‘short int’ when you specify a variable as type ‘int’. Thus the statement:
int var;
will allocate ‘var’ 4 bytes if you are using VC++ but the same statement will allocate 2 bytes if you are using Turbo C++ compiler.
Programmers sometimes prefer to explicitly state what type of integer they want to use by making use of the ‘short’ and ‘long’ qualifiers. ‘short int’ always occupies only 2 bytes (irrespective of whether the OS is Windows or DOS) while a ‘long int’ always occupies 4 bytes.
Two qualifiers can be used together, but do not try using:
short long int variable-name;
This will cause a compile-time error. So be careful with what qualifiers you use. And remember that the default for int is equivalent to short signed integer.
Floating Types (float):
Floating type data include integers as well as numbers with a decimal point. It can also have an exponent. Exponent means 10 to the power of some integer value (whole number). 20000 = 2 x 10^4 = 2e4 = 2E4.
If you specify decimal numbers, floating point data type will store up to a precision of 6 digits after the decimal point. Suppose 0.1234567 is assigned to a floating-point variable, the actual value stored would be 0.123457 (it will round up to the sixth digit after the decimal place). Valid floating-point numbers are:
• 0.1276
• 1.23
• 1.0
• 10.2
• 2e5 (this will be typed in your code as 2e5)
Do not use an exponent with a decimal point. For example: 2e2.2 is an invalid floating point because the exponent has to be an integer. Floating point numbers use 4 bytes of memory and has a much greater range than integers because of the use of exponents. They can have values up to 10^38 (in positive and negative direction). The same qualifiers used for an integer can be applied to floating point numbers as well. To declare a floating variable, the syntax is:
float variable-name;
Double (double):
This is similar to the floating-point data type but it has an even greater range extending up to 10308. The syntax to declare a variable of type double is:
double variable-name;
Beware: Visual C++ (VC++) usually uses its default as ‘double’ instead of ‘float’. Suppose we type:
float x=31.54;
you will get a warning message saying that a ‘double’ (i.e. 31.54) is being converted into a floating point. It is just to warn you that you are using a ‘float’ and not a ‘double’. (Even if there are warnings, there won’t be any problem in running your program).
Character (char):
A character uses just one byte of memory. It can store any character present on the keyboard (includes alphabets and numbers). It can take numbers from 0 to 9 only. The following are valid characters:
• A
• B
• 3
• a
• :
• ‘
• /
If the number 13 is entered as the value for a character, the program will only store 1 (i.e it will store the first character that it encounters and will discard the rest). A character is stored in one byte (as a binary number). Thus whatever the user enters is converted into a binary number using some character set to perform this conversion. Mostly all computers make use of the ASCII (American Standard Code for Information Interchange). For example, according to the ASCII coding, the letter ‘A’ has a decimal value of 65 and the letter ‘a’ has a value of 97.
There is another form of coding called the EBCDIC (Extended Binary Coded Decimal Information Code) which was developed by IBM and used in IBM computers. However, ASCII remains the most widely used code in all computers. The table at the end of the book gives a listing of the ASCII values and their equivalent characters. The syntax to declare a variable which can hold a character is:
char variable-name;
Boolean Type (bool)
This data type will only accept two values: true or false. In C++, ‘true’ and ‘false’ are keywords. Actually a value of true corresponds to 1 (or a non-zero value) and a value of false corresponds to 0.
#include
int main( )
{
bool check;
check = true;
cout<
int main( )
{
float PI = 3.14; // variables can be initialized during declaration
int rad;
cout<< "Enter the radius" ; cin>>rad;
cout<< "Area of the circle is "<< PI * rad * rad; return 0; } The preprocessor has only one directive and it will include the iostream.h header file into the source code. The compiler will start reading the code from the main ( ) function onwards. Remember: Whatever is typed within the main ( ) function will be executed. The main ( ) function is used as the entry point for a C++ program. PI is a variable name and is declared as a float quantity (because the value of PI has a decimal point). At the point of declaration, PI is initialized to a value of 3.14. This means that whenever PI is used in the program, the compiler will use 3.14 instead of PI. The line: cout<<"Enter the radius"; will cause Enter the radius to be displayed on the screen. This is because "Enter the radius" is typed within double quotes following ‘cout’ and the insertion operator. Anything between double quotes, along with cout<< will be displayed on the screen just as it appears within the double quote. The value entered by the user will be stored in the variable ‘rad’. Then the statement "Area of the circle is " will be displayed on the screen. The compiler will calculate the value of ‘PI * rad * rad’ and display it at the end (* is the multiplication operator in C++). The output for the above program is: Enter the radius 9 Area of the circle is 254.14 Bold indicates that the user entered the value. In this case 9 was entered as the radius. Suppose we type cout<< "rad"; the output will be just the word rad The value of the variable ‘rad’ will not be displayed. Remember: When you want to display some variable’s value on the screen, DO NOT ENCLOSE IT IN DOUBLE QUOTES; just mention the name of the variable after the insertion operator. ________________________________________ Initializing variables: It is a good idea to initialize variables at the time of declaration. Even if you are unsure of the value you can still initialize it to 0. If you are wondering why, just consider the example below: #include
int main( )
{
int correct, choice;
cout<<"\nEnter your guess of the lucky number: "; cin>>choice;
if (choice= =correct)
{
cout<<"\nCongrags. You are correct!"; } else { cout<<"\nSorry. Wrong guess"; } cout<
int main( )
{
char check;
int i;
cout<<"Enter the character that you want to convert to ASCII : "; cin>>check;
i = check;
cout<<"The ASCII value for "<
int main( )
{
int num1, num2;
cout<<"Enter the two numbers : "; cin>>num1>>num2;
cout<<"The product is : "<>num1>>num2;
This is a method of obtaining multiple inputs using a single statement. The above statement is equivalent to writing:
cin>>num1;
cin>>num2;
The two numbers, when entered by the user, can be separated by a space or by a new-line (i.e. the first number is typed and then after pressing the ‘enter’ key the second number is typed).
When you run the program you would get the following on your screen:
Enter the two numbers : 8 4
The product is : 32The sum is : 12The difference is : 4The quotient is : 2The remainder is : 0
Something is not right in this output; the results are correct but the display is on a single line. To display the output in an organized manner, the program should print each output on a new line. For this purpose of formatting the output C++ provides us with ‘escape sequence’.
________________________________________
Escape Sequences/ Backslash Character Constants
If you remember, whatever you type within double quotes following cout<<, will be printed as it is on the screen. There is a problem in case you want to print a new line, or you want to use tabs (because whatever you type within double quotes will be displayed directly on the screen). To solve this problem, escape sequences were developed. Just as the name implies, these escape sequence characters are used to escape from the normal sequence of events. An escape sequence always begins with a backslash ( \ ). For a new line, the escape sequence is \n (n for new line). If you want to push the tab setting then \t should be used (t for tab). The modified program for doing simple arithmetic operations is as follows: #include
int main( )
{
int num1, num2;
cout<<"Enter the two numbers : "; cin>>num1>>num2;
cout<<"\n The product is : "<
int main( )
{
char ch;
double db;
float f;
short int i;
db=55e4;
ch = i = f = db;
cout< , = = , ! = , >= , <= ) Relational operators are also binary operators (since they operate on two operands). They are used for comparing two values and the result of the comparison is either true (value 1) or false (value 0). Some examples are given below: 5>4 will return a value of True (1)
2>3 will return a value of False (0)
In programs that you write, comparisons will usually be made between one variable and a constant or between two variables. For example:
x>y
z>10
> means ‘greater than’ while >= stands for ‘greater than or equal to’.
x>=y
will yield a true value even if x = y whereas x>y will yield a value of false when x = y. Be clear as to what relation you want to test when using these operators.
Suppose you want to test whether two variables are equal, you have to make use of the equality operator. The equality operator is denoted by = = (double equal to signs).
Remember: Many beginners in programming use the equality operator and assignment operator interchangeably. The assignment operator is a single ‘equal to’ sign and it is meant only for assigning values to variables. The equality operator (a double ‘equal to’ sign) is used to check whether two values are equal.
Relational Operator Operation Performed Result of Operation
x>y Is x greater than y? True/False
x=y Is x greater than or equal to y? True/False
x<=y Is x less than or equal to y? True/False x==y Is x equal to y? True/False x!=y Is x not equal to y? True/False We’ll write a simple program for comparing two numbers and displaying the appropriate result. #include
int main( )
{
float num1, num2;
cout<<"Enter the two numbers : "; cin>>num1>>num2;

if (num1>num2)
{
cout<<"The number "<5. Do you think it is valid?
#include
int main ( )
{
int num;
cout<< "Enter the number"; cin>>num;
cout<<(num>5); //Legal?
return 0;
}
Always remember that the result of a comparison yields a value of TRUE (1) or FALSE (0). Hence the above program is perfectly correct. In case you enter a value that is greater than 5 you will get the output as 1 else you will get 0. 0 is considered as false and all other values are considered to be true.
C++ Operators - IV
The following topics are covered in this section:
• Logical Operators
• Unary Operators
5. Logical Operators - AND ( && ) OR ( || ) NOT (!)
These operators are used to combine two or more expressions. The way in which they combine the expression differs depending on the operation used. They are used when we need to test multiple conditions. For example you may write a program that has to check whether the marks scored by a student is greater than 70 and less than 80. If it is so then you will want the program to display a ‘B’ grade. To check whether the average mark is greater than 70 you have to use one expression and to check whether the average is less than 80 you should use another expression. Thus in simple English your statement will be:
If (average mark is greater than 70 AND average mark is less than 80)
Print "B grade"
AND: it combines two conditional expressions and evaluates to true only if both the conditions are true.
First Condition Second condition Result of AND operation
False False False
False True False
True False False
True True True
If the first condition and the second condition are both true then the result of the AND operation will also be true.





Example:

// To check whether the given number is even
# include
int main ( )
{
int num;
cout<< "Enter the number"; cin>>num;
if ( (num!=0) && ((num%2)= =0) ) // Two conditions have to be true
{
cout<<"\n Even Number"; } return 0; } In this program we need to check for two conditions (the number entered should not be zero and the number when divided by 2 should not produce a remainder). Only if both these conditions are satisfied should the program display that the number is even. The AND operator is used to combine the two conditions that are to be tested and if both are true then the message is displayed. OR: operator combines two conditions and evaluates to true if any one of the conditions is fulfilled (i.e. only one of the conditions need to be true). It is designated by using two parallel bars/pipes ( | | ). First Condition Second condition Result of OR operation False False False False True True True False True True True True The ‘AND’ and ‘OR’ operators can be used on a sequence of conditions (i.e. at a time you can check for multiple conditions). For example the following code is legal: if ( (x>y) && (y>5) && (z>y) && (x>4) )
{
//body of the ‘if’ condition…
}
In this case only if all the four conditions are true will the body of the ‘if condition’ be executed.
NOT: NOT is a unary operator. Unlike ‘AND’ and ‘OR’, NOT operates only on one operand. The logical value of the operand is reversed. If the operand is true, then after the NOT operation it will be become false. You might be thinking that the NOT operator can operate only on 1 and 0. Actually, any number greater than 0 will be considered as a true value. Hence the following would give:
• !5 will give 0
• !0 will produce 1
• !1 is equal to 0.
Condition Result of NOT operation
False True
True False
Basically, any number other than zero is considered as true. ‘Not’ of any number (other than 0) will give you FALSE (or zero). Check out the following program that illustrates the NOT operator.
#include
int main ( )
{
int num, result;
cout<< "Enter the number"; cin>>num;
result = (!num);
cout<
int main ( )
{
int a;
cout<
>=
Equality operator ==
Inequality operator !=
Logical Operator &&
||
Conditional operator ?:
Assignment =
Arithmetic assignment *=, /= , %= , += , -=
Beware: It is better to write long expressions using parentheses otherwise it could lead to a lot of confusion and also to potential logical errors.


Associativity
If two operators have a different priority level then their execution order depends on the operator precedence. What will happen if two operators have the same priority level?
When 2 operators in an expression have the same priority, the expression is evaluated using their associativity. Consider the statement:
net = basic + allowance – tax;
Both + and – have the same priority level. Almost all of the operators except the assignment (and arithmetic assignment) operators have associativity from left to right. The assignment operator has associativity from right to left. Since the + and – binary operators have an associativity of left to right the expression for ‘net’ is the same as:
net = (basic + allowance) – tax;
When you perform multiple assignments:
x = y = 0;
the associativity of the assignment operator (=) is taken into account and thus the order of evaluation will be:
y = 0 (which will give ‘y’ a value of 0) followed by x = y (which will assign 0 to ‘x’).
Comma Operator
The comma operator can accept two expressions on either side of the comma. When executed, the left side expression is first evaluated followed by the right side expression. Ultimately it is the expression on the right side that will be the value of the entire expression.
int x,y;
cout<<(x = 1, y = 5); // 5 will be displayed First the ‘x’ will be assigned 1 and then ‘y’ is assigned a value of 5. The comma operator is equivalent to saying "do this task and do this also". In this case the compiler will do: x = 1 and then y = 5 The rightmost expression is y = 5 and hence the value of the entire expression (x=1,y=5) is 5. Be careful while assigning the value of a comma separated expression to a variable. The comma operator has lower operator precedence than the assignment operator. If we type: y = (x = 1 , x = 5 , x + 10); x will have a value of 5 while y will be 15. If we type: y = x = 1, x = 5 , x+10; the value of ‘y’ will be 1 and that of ‘x’ will be 5. This is because the compiler will perform the following operations: y = x = 1; // y and x are set to 1 x = 5; //x value is 5 x + 10; //the value of the entire comma separated expression is 15 The comma operator will be used usually in ‘for’ loops. Bitwise Operator: The bitwise operators available in C++ are tabulated below: Bitwise Operator Symbol Function & AND individual bits | OR individual bits ^ EXOR individual bits ~ NOT of individual bits (or complement operator) >> Right-shift operator
<< Left-shift operator These operators will operate on individual bits of the operand (i.e. on the binary representation of data). These operators are dealt with in detail in Chapter 13. Remember: Do not confuse the && and & operators or the || and | operators (logical operators are entirely different from bitwise operators). Recap • Arithmetic operators are used to perform mathematical operations. • The modulo/remainder operator is applicable only on integer operands. • Escape sequences are character constants that are used to format the output displayed on the screen. • = is the assignment operator and the Rvalue is assigned to the target (or the Lvalue). • Information will not be lost when converting from a smaller data type to a larger data type. • Shorthand operators are a combination of one of the arithmetic operators and the assignment operator. • Relational operators are used to compare two values or expressions. They will return a value of true or false. • Logical operators are used to combine two or more expressions. • The operator precedence determines which operator has a higher priority. • When 2 operators have the same priority the expression is evaluated based on their associativity. • Bitwise operators are used to operate on individual bits. For Loops in Depth The following topics are covered in this section: • Introduction • For Loop Statement • More of For loops • Body of For loops • Nesting For loops Statement and Expression A statement in C++ refers to a part of the code that is terminated in a semicolon. It is the smallest part of the program that can be executed. For example: sum = a + b; is a statement. A C++ program will consist of a set of statements. An expression is a grouping of variables, constants, function calls and operators (arithmetic, logical, relational) to return a value. In the above example, a + b is an expression. While dealing with control mechanisms you will come across blocks of instructions. A block of instruction refers to a set of statements grouped together within a block. The block is identified by using the curly braces ‘{‘ to start the block and ‘}’ to end of the block. Program flow and control: What is program flow? Whenever we write a program we have to decide on the sequence of operations that the program has to perform. Generally this is represented in the form of an algorithm. Writing algorithms for simple programs might seem trivial but when you write complex programs, the algorithm helps reduce programming errors. Let’s take a look at a simple algorithm to calculate the average weight of 3 persons: Step 1: Start the program. Step 2: Obtain the weight of all 3 persons (in weight1, weight2, weight3). Step 3: Calculate the average weight as average = (weight1 + weight2 + weight3)/3 Step 4: Display the result Step 5: Stop the program By looking at the algorithm a programmer can easily write the entire program. When you have a complex program, if you have written an algorithm then you can eliminate potential logical errors in this stage itself. In the algorithm we define the way in which the program control should flow. First the program should get the 3 inputs from the user, then it should calculate the value for average and finally it should display the result. Thus we can say that the program flow has been clearly defined. But program flow needn’t always be so simple. You might need to take some decisions and alter program flow. Control refers to that part of the program which is currently being executed. Let’s write an algorithm to divide 2 numbers obtained from the user. Step 1: Start the program. Step 2: Obtain the 2 numbers (num and den) from the user. Step 3: Check if den is zero. If it is then go to step 4 else go to step 5. Step 4: Display “Denominator is zero. Cannot perform division”. Go to step 7. Step 5: Calculate the quotient by dividing num by den. Step 6: Display the result. Step 7: Stop the program. In this example, there are 2 routes the program can take. If the user enters the denominator as 0 then the error should be produced else normal division should be performed. The pictorial representation of an algorithm is called a flowchart. Loops Suppose you want to add the numbers from 1 to 10, what would you do? Of course you could write a long statement that would calculate 1+2+3+4+…+10. What if 10 were changed to 100 or 1000? Whenever there are statements to be repeated you can make use of loops (in fact you should make use of loops). When using loops, some condition should be specified so that the loop will terminate (otherwise the set of statements within the loop will keep executing infinitely). For loop statement For loop is used for performing a fixed number of iterations (or repetitions). The syntax is: for (initialize-variables; condition-to-test ; assign-new-values-to-variables) { //statements to be repeated (or the body of the loop) } The ‘for’ loop has three expressions that have to specified. Initialize variables: This expression is executed only once (when the program flow enters the loop for the first time). It is usually used to assign the loop variable an initial value. Condition to test: involves relational operators. It is executed each time before the body of the loop is executed. Only if the condition is true will the loop body be executed. If it is false then the loop is terminated and the control passes to the statement following the ‘for’ loop body. Assign new value to variable: It is executed at the end of every loop after the loop body. Usually it is used for assigning a new value to the loop variable. Example: // To find square of numbers from 1 to 10 #include
int main( )
{
int var;
for (var = 1 ; var<=10; var++) { //beginning of ‘for block’ cout<< "Square of "<
int main( )
{
int i = 2;
for ( ; i<8 ; i++ ) // No initialization of loop variable! { cout<
int main( )
{
int i;
for ( i = 1; i != 2 ; i++ )
{
cout<
int main( )
{
int x,y;
for (x=1,y=1; x<10,y<5 ; x++,y++) { cout<<"\n"<>letter;
If you want to check whether the user has entered a ‘y’ or an ‘n’ you can do the following:
if (letter = = ‘y’)
{
//body of if statement
)
You should not compare characters as shown below:
if (letter = = y) //WRONG
This method of comparing a character variable with a character constant is WRONG. It will yield an error. The character constant should always be enclosed in single quotes.
Beware: Beginners often forget the single quotes while using character constants.

//To find the square of a given number
# include
int main( )
{
char reply;
int num, square;
cout<< "Do you want to find the square of a number(y/n)? "; cin>>reply;
while (reply = = 'y') //No blank-space between the two equal signs. See note.
{
cout<<"\nEnter the number : "; cin>>num;
square = num*num;
cout<< "The square is : " <>reply;
}
return 0;
}
Note: A blank space has been left between the two ‘equal to’ symbols just to make it clear that there are two equal signs. Do not leave a space between the two = symbols when you write your program.
At the start of the program, if the user types a ‘y’ the program will execute the loop body. At the end of the while loop, the program will prompt the user to enter the value for ‘reply’. If the user again types ‘y’, then the program will execute the while body a second time. Hence, at the end of each loop the program obtains the value for ‘reply’ and checks whether the test condition is true. As long as the test condition is true, the while loop is executed over and over again.
The difference between the ‘while’ loop and the ‘for’ loop is that the ‘while’ loop does not have a fixed number of repetitions of the loop body. As long as condition is true it keeps executing the loop body. Usually the ‘while’ loop is used when the programmer is not sure about the number of iterations that need to be performed. The ‘for loop’ is used when the programmer knows how many iterations are to be performed. Of course, the use of both can be interchanged as well. In fact, a ‘for loop’ can be modeled into a ‘while loop’. The equivalent ‘while loop’ for a ‘for loop’ will be as below:
Initialize a variable value;
while (condition involving the variable)
{
//body of the loop
//assign a new value to the loop variable;
}
If we use the coding:
while(1= = 1)
{
//body of loop
}
the while loop becomes an infinite loop (because 1 is always equal to 1).
Do…While loop
The ‘do…while’ loop is a modification of the ‘while’ loop. If you noticed in the earlier program for the ‘while’ loop, initially we have to ask the user whether he/she wants to find the square of a number. Only if the user types a ‘y’ will the program enter into the ‘while’ loop. Hence in the program we have to ask the user twice whether he/she wants to square a number (once outside the loop and once inside the loop). The ‘do while’ loop, eliminates this repetition.
When you make use of the ‘do-while’ loop, the body of the loop will be executed at least once. After the first iteration, if the loop condition holds true then the loop is repeated again. Thus the first iteration is compulsory in the ‘do…while’ loop.
The program to find the square of a number can be re-written as follows:
#include
int main( )
{
char reply;
int num, square;
do
{
cout<<"\nEnter the number : "; cin>>num;
square = num*num;
cout<< "The square is : " <>reply;
}while (reply = = 'y');
return 0;
}
In this program, the body of the loop will be executed once for sure. After the first iteration, the user has the option of terminating the program or continuing to use the program for squaring another number.
Beware: when using the ‘do…while’ loop, make sure that you put a semicolon at the end of the while statement:
while (reply = = 'y');
Decision Statements (IF)
So far we have seen statements that help you in repeating a particular task as long as you desire. Another important form of program flow control is to be able to make a decision as to how you want the program to continue. Statements of this kind are referred to as decision statements (sometimes also called selection statements).
The following topics are covered in this section:
• If else
• Nested If
• Conditional Operator

• If…Else If…else…
‘if-else’ is one of the decision statements available in C++. This enables the programmer to provide different paths for the program flow depending on certain conditions. For example: consider a program for dividing two numbers. Division by zero will lead to an error. To avoid this from happening, after obtaining the two numbers from the user the programmer will want to ensure that the denominator is not zero. Hence there needs to be two different program flow options. If the denominator is zero a message saying, "Division not possible" should be displayed. Otherwise the program should carry out the division and display the results. In simpler terms this can be stated as:
If the denominator is zero, then display a message and do not divide
else perform division and display the output.
Syntax:
if (condition)
{
//statements to be executed;
}
else
{
//statements to be executed;
}
The program flow is as follows: If the condition being tested within the ‘if’ statement is true, then the body of ‘if’ will be executed otherwise the body of ‘else’ will be executed. Thus the program takes a decision as to what it should do next.
You can also make use of the ‘if’ statement alone (‘else’ is not compulsory) or you can even make use of a series of ‘if...else’ statements as follows:
if (condition1)
{
//body
}
else if (condition2)
{
//body
}
else
{
//body
}



Example:
// To find the greater among two numbers
#include
int main( )
{
int a, b;
cout<< "Enter the two numbers you want to compare : "; cin>>a>>b;
if (a = =b)
{
cout << "The two numbers are equal"; } else if (a>b)
{
cout <b)
Even if this is not satisfied then only will it go to the next statement, which is an ‘else’ statement. Since ‘a’ was not greater than ‘b’, and equality was also tested earlier the only possibility is that ‘b’ is greater than ‘a’. Thus if the first two conditions have failed then the program flow will go to the body of the ‘else’ block.
Remember: Using the ‘if…else..if’ format, only one of the bodies will be executed (not all). If one condition is satisfied the rest of the ‘else..if…else’ is ignored.
When we use the ‘if..else if’ construct, if one of the conditions is satisfied that corresponding body will be executed and the rest will be ignored. But what would happen if we use a series of ‘if’ statements alone?
#include
int main( )
{
char letter;
cout<<"\n Enter the alphabet 'a' or 'A': "; cin>>letter;
if (letter= ='a')
{
cout<<"\n You entered an 'a'"; } if (letter= ='A') { cout<<"\n You entered an 'A'"; } return 0; } In the above program, the compiler will check for ‘a’ first and then it will check for ‘A’ also. Even if the first condition is satisfied, it will still check for the second ‘if’ condition. In such cases it would be better to use the following: if (letter= ='a') { cout<<"\n You entered an 'a'"; } else if (letter= ='A') { cout<<"\n You entered an 'A'"; } Now if the user enters an ‘a’ then the program will not enter the ‘else if’ statement to check whether the letter is an ‘A’. Remember: It is better to make use of ‘if-else-if’ instead of a series of ‘if’ statements because in that way your program need not check all the conditions unnecessarily. And whenever you use a series of ‘if-else-if’ statements, test the condition that is most likely to be true first (so that the program need not waste time in checking more conditions). Nested If You can have an ‘if’ statement within another ‘if’ statement. This is known as nested ‘if’. The program flow will enter into the inner ‘if’ condition only if the outer ‘if’ condition is satisfied. In general form nested ‘if’ will be of the form: if (condition1) { //code to be executed if condition1 is true if (condition2) { //code to be executed if condition2 is true } } There can be more than one ‘if’ condition (i.e. you can nest as many ‘if’ statements as you want). An example code fragment is given below (‘month’ and ‘year’ are integer variables whose values are obtained from the user): if (month= =2) { cout<< "The month is February"; if ( (year%4) = = 0) { cout<< "This month has 29 days."; } else { cout<< "This month has 28 days."; } } In the above code fragment, only if the variable ‘month’ is equal to 2 will the program enter into the ‘if’ block. Within this block it will print: The month is February Then it will check as to whether the given year is a leap year or not. If it is a leap year then it will display that the month has 29 days else it will say the month has 28 days. Empty ‘if’ statement: We have seen the use of empty ‘for’ statements but empty ‘if’ statements might not be useful. In fact empty ‘if’ statements are usually logical error (because the programmer places the semi colon by mistake at the end of the ‘if’ statement). Example: if (num1b?10:20;
The value of y will be 20 because ‘a’ is not greater than ‘b’. This sort of expression can be written using the ‘if’ statement as:
a=5;
b=6;
if (a>=b)
{
y = 10;
}
else
{
y = 20;
}
Beware: It’s just that you could reduce the amount of coding by using the ternary operator. Be careful that you don’t confuse the logic while trying to reduce the length of the code!
Decision Statements (Switch Case)
There are many instances wherein you may want to test for a series of conditions one after the other. For example: Suppose you obtain the input of month from the user in as a number and you want to display the corresponding name of the month; what would you do? You could write a series of twelve ‘if….else if….else if…else if…’ statements.
The ‘switch…case’ format provides a convenient alternative to using multiple ‘if-else’ statements when you are testing for a single variable alone. The switch statement successively tests the value of a variable against a list of integer or character constants. If a match is found then the statement associated to that particular case will be executed.
First of all, before entering the switch case statement, we have to obtain the value of the switch variable from the user. The switch variable refers to the variable whose value you want to check. In the case of converting numbers into corresponding months, the switch variable will be the month number.


Syntax:
switch (variable/expression that evaluates to an integer)
{
case char/integer-constant :
{
//body
}
case char/integer-constant :
{
//body
}
}
For example:
# include
int main ( )
{
int month;
cout<< "Enter the month of the year: "; cin>>month;
switch (month) // month is the switch variable
{
case 1 : // if month is 1 then the statements are executed
{
cout<<"The month is January"; break; } case 2 : { cout<<"The month is February"; break; } //write case statements for 3 to 10 just as shown above case 11 : { cout<<"The month is November"; break; } case 12 : { cout<<"The month is December"; break; } default : // If value of day is something other than 1 to 7 { cout<<"You entered an invalid number"; break; } } return 0; } As you can see, the compiler gets the value of the variable ‘month’ from the user. This is called the ‘switch variable.’ If the value of ‘month’ is 1, then the compiler performs what is specified under case 1. If the user enters 2, then the output will be February and so on. Since a year has only 12 months, if the user types 0 or 14 then the program should display that the user has typed the wrong number. The ‘default’ statement is used for this purpose. The ‘default’ statement provides the program with an option to do something in case the switch variable does not match any of the case constants. In this program, ‘month’ is called the switch variable and the integer constants from 1 to 12 are called case constants (i.e. they are the values for which the switch variable is tested). Break: It causes an exit from the switch construct (body). For instance, after printing that "The month is January" you don’t want the compiler to go into the other cases. Hence you ask it to break out of the ‘switch…case’ body. If there is no break for each case then the program will perform all the remaining cases as well. Try it: Remove all the break statements from the above program and execute your program. If you now type a value of 1, the program will print: The month is January The month is February …and so on… Beware: A mistake that beginners commit is that they tend to forget the ‘break’ statement. Always use ‘break’ after each case and also make sure that you have a ‘default’ option in your ‘switch…case’ body. The ‘default’ case is executed only if the user enters a value other than the case constants. It does not matter whether you place the default case at the starting of the switch-case body or at the end (but usually programmers prefer to place the default case at the end of the switch-case construct). Suppose you want to test the switch variable against a set of character constants then ensure that you enclose your case constants within single quotes. Suppose the switch variable ‘month’ is a character then the program would be: switch (month) { case 'a' : //‘a’ is within single quotes because it is a character constant { //body of the case break; } //the remaining cases } Beware: There can be an expression in the switch part but it should evaluate to an integer. The switch variable and the case constants should be integers (or characters). You should not use other data types. Controlling flow within a loop statement We’ve seen a few ways of looping within a program. There are a few occasions when you might want to break out of a loop when some particular condition occurs. Or in other words you may not want to go through the all the iterations within a ‘for loop’. Or you may want to break out of the loop for just one particular value of the loop variable. C++ provides a mechanism to break from loops using the ‘break’ and ‘continue’ statements. These are also called as ‘jump statements’. The following topics are covered in this section: • Break • Continue • Go To • Return • Apply what you've learnt • Recap of the entire Unit Break We’ve already seen the use of the ‘break’ statement in the ‘switch…case’ construct. A ‘break’ statement can also be used to terminate (or break out) from a loop (like the ‘for’ and ‘while’ loops). Suppose you are using nested loops, then a ‘break’ specified in the body of the inner loop will lead to breaking out from the inner loop alone. #include
#include
int main ( )
{
int x, i;
for (i = 0; i<15; i++) { x = rand( ); if (x>500)
{
cout<<"\n Iteration number "<
int main ( )
{
int i;
i = 1;
LOOP : if (i<10) { cout<
int main( )
{
char ans;
cout<<"Enter y/n : "; cin>>ans;
if (ans=='n')
{
goto done;
}
int x=5; //ERROR
done:
cout<
int main( )
{
int d,m,y,days;
cout<<"\nEnter the Date (DD MM YYYY): "; cin>>d>>m>>y;
switch(m) //To print the month
{
case 1:
cout<<"\nJanuary"; days=31; break; case 2: cout<<"\nFebruary"; break; case 3: cout<<"\nMarch"; days=31; break; //…write the remaining cases case 11: cout<<"\nNovember"; days=30; break; case 12: cout<<"\nDecember"; days=31; break; default: cout<<"\nInvalid month"; return 0; //quit the program! break; } cout<<" "<
void add ( ); // Function Declaration
int main( )
{
add( ); // Function Call
return 0;
}
void add( ) // Function header
{
int num1,num2,sum; // Body of the function
cout<< "Input the two numbers : "; cin>>num1;
cin>>num2;
sum = num1 + num2;
cout<<"The sum is "<
void add( )
{
int num1,num2,sum;
cout<< "Input the two numbers : "; cin>>num1;
cin>>num2;
sum = num1 + num2;
cout<<"The sum is "<
void add (int var1, int var2) // Parameters var1 and var2
{
int var3;
var3 = var1 + var2;
cout<<"The sum of the two numbers is "<>num1;
cin>>num2;
add(num1,num2); //Arguments num1 and num2
return 0;
}
Two arguments have been passed to add ( ) from the main ( ) function. Observe the function ‘declarator/header’. The parameter specified is ‘int var1’ and ‘int var2’. This means that in the function named ‘add’, ‘var1’ and ‘var2’ are integers that are used within the body of the function. Within the function body we have declared a third integer called ‘var3’.
var1 and var2 are added and stored in var3 using the statement :
var3=var1 + var2;
Now the question might arise, what are the values for var1 and var2? In the main ( ) function the value for two integers ‘num1’ and ‘num2’ are obtained from the user. After obtaining the values, the following statement is encountered:
add(num1,num2);
This statement is the function call. Two arguments namely ‘num1’ and ‘num2’ are passed through this function call. Since the function was declared and defined as having two parameters (and since the data types of the parameters and the arguments are the same), the program will execute the code of the add ( ) function with the value of ‘var1’ being that of ‘num1’ and value of ‘var2’ being equal to ‘num2’. If the data types or number of arguments passed do not match with the parameters, the compiler will produce an error message.
Effectively, var1=num1 and var2=num2. The body of the function ‘add’ is now executed with the values of ‘var1’ and ‘var2’. Thus the arguments are passed from the program (which is the main ( ) function) to the parameters of the function ‘add’.
The variables used to hold the argument values are known as parameters. The function declarator in the function definition specifies both data type and name of parameters. In our example, the parameters were ‘num1’ and ‘num2’. Their data types were int (integer).

Remember: The values of ‘num1’ and ‘num2’ are passed to ‘var1’ and ‘var2’. The function is operating only on ‘var1’ and ‘var2’ (it does not operate on ‘num1’ and ‘num2’).
If we had declared the add ( ) function in the program, it would have been as follows:
void add (int, int);
In the function declaration you don’t have to specify the parameter names (just specifying the data types of the parameter is sufficient).
Remember: You pass arguments to parameters.
A closer look at Functions
The following topics are covered in this section:
• Default Arguments
• Return Values
• Returning void
• int main and void main ( )
• exit( )
• using return to break out from loops
Default Arguments
While using functions with parameters, you can specify default argument values (i.e. in case arguments are not passed to the function then the function will assign the default values to the parameters).
#include
void add (int var1=5, int var2=10) // default values 5 and 10
{
• int var3;
var3 = var1 + var2;
cout<
int add (int , int); // Declaration
int main ( )
{
int sum, var1, var2;
cout<< "Enter the two numbers"; cin>>var1>>var2;
sum = add(var1,var2); //Function call
cout<< "The sum of the two numbers is "<
void convert(int dollar)
{
if (dollar<0) { cout<<"\nCan't convert negative amount!"; return; } cout<<"\nThe equivalent money in Rupees is : "<<46*dollar; } int main( ) { int amount; cout<<"\nEnter the amount in dollars you want to convert: "; cin>>amount;
convert(amount);
return 0;
}
The output when you type a positive value is:
Enter the amount in dollars you want to convert: 5
The equivalent money in Rupees is : 230
The output when you enter a negative value is:
Enter the amount in dollars you want to convert: -1
Can't convert negative amount!
As can be seen from the output in the second case, once the return statement is encountered the program will stop executing the function (thus it does not calculate the value of 46*dollar if the value of dollar is negative).
void main ( ) and int main ( )
The main( ) function can be written in one of two ways. Either you can use:
void main ( )
or you can use:
int main ( )
{
//code
return 0;
}
int main ( ) returns an integer value while void main ( ) doesn’t return anything. Consider the following program:
# include
int main ( )
{

int test;
cout<<"Enter a value :"; cin>>test;
if (test= =1)
{
cout<<"You typed 1"; return 1; } cout<<"This line is displayed if you typed a value other than 1"; return 0; } What do you think happens when the user types 1 as the value of ‘test’? Since ‘test’ is equal to 1, the compiler will go into the body of if. It will display "You typed 1" on the screen. Then the compiler will return a value of 1. Generally a return value of a non-zero number is used when errors are encountered. You can't use this return value anywhere else in your program (Why? Because the caller for the main ( ) function is your operating system). In other functions (functions other than ‘main’ ), you can make use of the return value. After returning the value, the program exits. This means that the compiler will not even read the remaining few lines and hence nothing else will display on the screen. The compiler will quit once any integer has been returned by the main ( ) function. If you type anything other than 1 for test, the compiler will skip the ‘if’ body, display the last statement and then return 0. Better to use int main ( )? We could now delve one step further into the topic. Which one is better? Or which one should we use and why? Void is generally used to declare functions that do not return values. When you use int main ( ), the main function returns an integer to the operating system (since the OS is what calls the program and in turn the main function). Returning a value from main ( ) is like an exit function. The value is returned to the operating system and the program terminates. What will the OS do with your returned value? Actually, the OS never wants to know what you return. The program which started your program might need to know. In any OS, a program when running is called a "process". When booting up, the operating system starts the first process (called "init" in UNIX systems). Thereafter the first process starts other processes such as a shell (shell is just a program, which reads commands from the user and converts it to system calls). So when you write a program and execute it in the shell, the shell starts your program. So now, the shell is the parent process of your program (and your program is the child of the shell). Now, in the same way, suppose you want one of your programs to load another program to do a particular job and you want to know just whether the job was successful or not, then the OS gets the exit code of the child process and gives it to the parent process; just like returning from a function. So it is a standard to give the exit code as '0' for a success and any non-zero integer for an error. When programming in C/C++ you can give this exit code when you return from the main function. So you've to declare main as 'int main( )' to do that. If you declare it as 'void main( )' C++ wont allow you to set a value to be returned to your parent program. So the variable which should contain the return code will be filled by nothing, which means that memory can be in any state (unpredictable). Hence you have no control on what value your parent process gets when your child program exits. This is not just for UNIX, it holds good for MSDOS and Windows too. In the UNIXes the shell is usually 'sh' or 'bash'. In MSDOS the shell is called 'command.com'. In Windows the shell is 'explorer.exe'. Hence it's always better to use int main ( ) along with a return value at the end of the main ( ) function. A return value of zero indicates a normally terminated program. A non-zero value is used in case of errors. Of course this does not mean that a program written with void main ( ) won’t work; but it is better to avoid writing such programs. exit() There is a function called exit ( ) which can be used to terminate (or break out from) the program. The function is: void exit (int r); where ‘r’ is an integer value returned to the OS. Usually a value of 0 is used to indicate normal termination while a non-zero number is used in the case of abnormal termination (due to errors). Thus, the syntax (or function call) will be: exit (0); or exit (1); Instead of using integers we can also use two predefined macros: EXIT_SUCCESS (which is equivalent to 0) or EXIT_FAILURE (which is a non zero number). The exit ( ) function is declared in the stdlib.h library file. Hence you should type: #include
in case you want to use this function.
________________________________________
Using ‘return’ to break out from loops
The ‘return’ statement will return program flow control to the caller and this feature can be used to break out from loops. An example program is given below:
#include
int display( )
{
int i;
for (i=0;i<10;i++) { if (i!=5) { cout<<"\n"<
int main( )
{
int choice;
cout<<"\nWelcome to prog1"; cout<<"\nEnter 1 to skip 2nd program:"; cin>>choice;
if(choice==1)
{
return 5;
}
else
{
return 0;
}
}
Our second program just displays a statement to indicate that we are executing the second program.
//prog2.cpp – This program simply displays a statement on the screen
#include
int main( )
{
cout<<"\nCongrags.You are in the second program!"; return 0; } Build the two executable files: prog1.exe and prog2.exe. Note: If you are using VC++, the exe files will be created in a folder called “Debug” within your project. Turbo C++ will create the exe files in the same folder itself. So, now we have 2 programs but how do we conditionally execute the 2nd one depending on the return code of the first? The answer lies in batch programming (if you are using DOS) or in shell programming (if you are using Unix/Linux). We’ll deal with batch programming. This is basically the creation of *.bat files (so far we’ve been creating *.exe files). I won’t go into this topic deeply but I’ll cover a bit of it so that you can appreciate return codes from programs. Before starting to write a *.bat file, you can copy the 2 exe files we created (prog1.exe and prog2.exe) into the same folder (I’ve copied them into my C:\). I assume that you have used a bit of MS-DOS (at least you should be familiar with the command prompt, changing directories etc.). Command prompt: To get to this from Windows go to START->RUN and type “command” in the pop-up box. You’ll be taken to the DOS prompt (this is the place from where you can give commands to DOS). The prompt on my system is:
C:\MYWIN\Desktop>
Now type cd\ to go to C:\
C:\>
Let’s create a batch file named combo.bat. To do this simply type:
C:\>edit combo.bat
You’ll be taken to an MS-DOS text editor (similar to Notepad in Windows). Type the following in the file, save it and return back to DOS.
@ECHO OFF
ECHO **** WELCOME TO BATCH PROGRAMMING ****
ECHO Executing the prog1
prog1
IF errorlevel 5 GOTO end
prog2
:end
ECHO End of batch file
Perhaps everything seems weird?
Remember: MS-DOS command.com is not case-sensitive (i.e. typing DIR or dir is the same).
The first 3 lines of our batch file are used for the purpose of displaying something on the screen (equivalent to cout<< in C++). On the 4th line we say: prog1 This is equivalent to executing the program ‘prog1.exe’ on the command prompt. Batch files are used basically to execute a set of instructions/programs in a particular sequence. If every time you log into the system, you want to perform 10 commands, then each time you’ll have to keep typing the 10 commands on your prompt. You can save time (and also needn’t worry about remembering the sequence of commands) if you write those 10 command in a batch file. Now, each time you log into the system, you just need to type the name of the batch file and voila! (all your 10 commands will be executed faithfully). Coming back to our program, prog1 in the batch file will execute our first program. You’ll see the display: Welcome to prog1 Enter 1 to skip 2nd program: 1 Let’s assume the user types 1. According to our program: if(choice==1) { return 5;| } Now prog1 returns a value of 5 to the caller. The caller is our batch program combo.bat. The next line of the batch program checks for this return code. IF errorlevel 5 GOTO end The IF condition becomes true if the previous step had a return value of 5 or greater. In our case the previous step was the execution of ‘prog1’ and this returned a value of 5. Thus the condition is true and the combo.bat will go to the section labeled ‘end’. Here we just display a statement saying that it’s the end of the batch program (echo is used to display on the screen). If the user had entered some other value then the batch file would have executed prog2 since the return value would have been less than 5 (in our case it was 0) and so the IF condition would be false. The output if you entered 1 would be: C:\>combo
**** WELCOME TO BATCH PROGRAMMING ****
Executing the prog1
Welcome to prog1
Enter 1 to skip 2nd program:1
End of batch file
C:\>
The output if you entered some other number would be:
C:\>combo
**** WELCOME TO BATCH PROGRAMMING ****
Executing the prog1
Welcome to prog1
Enter 1 to skip 2nd program:3
Congrags.You are in the second program!End of batch file
C:\>
Just follow the above steps, create the batch file and try it out on your system. To execute batch files you don’t need to compile the file (i.e. combo.bat can be directly executed). This is because the command prompt is an interpreter (it executes commands one at a time and does not require compilation as we do for C++ programs).
In Unix/Linux, this is called shell programming (and instead of batch files we call them shell scripts). In large applications, you would need to execute a series of programs everyday and these are written in shell scripts. The execution of programs would depend on the return code of the previous program (if the previous program failed because of some error then you might not want to continue execution of the remaining programs). By now you should have understood about the difference between void main( ) and int main( ).
Note: If you are using Unix/Linux then refer to the Appendix for the above section.



A closer look at Functions
The following topics are covered in this section:
• Types of Functions
• Function Overloading
• Apply what you've learnt
Types of Functions
There are two types of functions namely:
1. Library Functions
• The declaration of library function is in the header file specified at the beginning of the program.
• The definition is in a library file that is automatically linked to the program
• Declaration and definition are not required. We will only call the function. Example : rand( ), clrscr ( ), exit( ) etc.
2. User Defined Functions
• Declaration and definition are part of the source file (*.cpp file).
• Function definition and declaration have to be written by the programmer.
• Example of user defined functions is the add ( ) function that we used in the previous section.
There are many functions which are provided by the compiler. These functions that come with the compiler are called as library functions. The prototype for the library functions will be present in some header file. To use a library function, you only need to include the header file (where the function prototype exists) and should know the name of the function.
It is common for programmers to write coding for functions and then use them later in some other program when needed. In fact in C programming, this was quite common. You can do the same in C++ as well. You could define a set of general-purpose functions in a header file and include the header file in the programs where you want to use those defined functions (by specifying a function call statement). But using functions in this way can lead to some problems, which will be discussed later (the main problem is when there is a clash of function names). In C++ we make use of ‘classes’ and reuse classes, rather than functions directly.
Using library functions: rand( ), srand ( ), time( )
There may be instances wherein you will want to generate numbers randomly. For example if you are simulating a game played with dice then you should be able to produce numbers between 1 to 6 randomly (corresponding to the 6 faces of a dice). Or if you want to simulate the tossing of a coin you should be able to retain the randomness of the event (i.e. these are events which you can’t predict. It could be a head or a tail).
We can make use of the rand ( )library function to perform such tasks. The rand ( ) function is defined in the stdlib.h library. Let us write a program to toss a coin and ask the user for his/her choice. If the user’s choice and the result of the toss are the same then the user wins the game.
#include
#include
int main( )
{
int move;
char choice;
do
{
cout<<"Enter 1 for head and 0 for tail: "; cin>>move;
if (rand( )%2= =move)
{
cout<<"You win."; } else { cout<<"You lose."; } cout<<"\n\nDo you want to play again? "; cin>>choice;
}while(choice= ='y');
return 0;
}
The rand ( ) function will generate integers upto a maximum of 32767. But in the case of tossing a coin we have only two possibilities (a head or a tail). To scale down 32767 to two cases we divide the rand ( ) value by 2 and use the remainder (the remainder will either be 1 or 0). Thus we assume that 1 is head and 0 means tail in the above program. The output for the above program will be:
Enter 1 for head and 0 for tail: 1
You win.
Do you want to play again? y
Enter 1 for head and 0 for tail: 1
You win.
Do you want to play again? y
Enter 1 for head and 0 for tail: 1
You lose.
Do you want to play again? n
If you run the program again a second time the result will be:
Enter 1 for head and 0 for tail: 1
You win.
Do you want to play again? y
Enter 1 for head and 0 for tail: 1
You win.
Do you want to play again? y
Enter 1 for head and 0 for tail: 1
You lose.
As you might have noticed the sequence is the same (i.e. each time the program is run the same set of random numbers are produced). This is because the random number is generated in a sequence and unless you ask the computer to start the sequence from a different position it will always keep starting at the same place. We have another function called srand( ) than can be used to alter the start of the sequence. To do this just add the satement:
srand( time(0) );
before the ‘do’ statement. The function time ( ) is defined in ‘time.h’ header file. The output will now be:
Enter 1 for head and 0 for tail: 1
You win.
Do you want to play again? y
Enter 1 for head and 0 for tail: 1
You lose.
If you run the program there is a good chance of getting a different result for the same inputs. This is because we are setting the random generator differently each time the program is run. The function time (0) will give the present system time in seconds. Each time you run this the time (0) value will be different.
Suppose you want to simulate the throw of a dice then you should scale down the outcomes of the rand( ) function to 6. For this (instead of rand( )%2, you could use the statement:
( ( rand( ) % 6 ) + 1 )
We have to add 1 because rand ( )%6 will produce values between 0 and 5 but we need values from 1 to 6.
Function Overloading
Can two functions have the same name?
More than one function can have the same name but they should have different number of parameters or the types of the parameters should be different. This is known as function overloading. The name of a function along with its parameter data types forms the function signature. The signature helps differentiate between two functions. In function overloading the signatures of the functions with the same name will be different.
In general, overloading is the process of assigning several meanings to a function (or an operator as in operator overloading, which we will discuss in a later chapter). Consider the example given below:
// A PROGRAM TO ILLUSTRATE FUNCTION OVERLOADING
void display( ); // Function declaration – This function has no arguments
void display (char); // One argument
void display (char, int); // Two arguments
int main( )
{
display ( );
display (‘=’);
display (‘+’, 30);
return 0;
}
void display( )
{
cout<< "Hi!"; } void display (char ch) { cout <
#include //to make use of the system("CLS"); function
int menu( ); //provide a menu for the user
void fibo( ); //function for generating fibonacci series
void fact( ); // to find the factorial of a number

int main ( )
{
int ch;
while (1= =1) //an infinite loop which can be broken
{
system("CLS"); //to clear the screen before the menu is displayed
ch=menu( );
switch (ch)
{
case 1:
fibo( );
break;
case 2:
fact( );
break;
case 3:
cout<<"\n Program Terminated."; break; default: cout<<"\n Invalid choice."; break; } if (ch= =3) { break; //break from while loop } } return 0; } //All the function definitions below: int menu( ) { int choice; cout<<"\n\n\n Welcome to my Program"; cout<<"\n 1.) Generate a Fibonacci Series."; cout<<"\n 2.) Find the factorial of a number."; cout<<"\n 3.) Exit."; cout<<"\n\n Enter your choice : "; cin>>choice;
return choice;
}
void fibo( )
{
int max, sum, a1, a2;
cout<<"\n\nHow many terms do you want in the series? "; cin>>max;
a1=1;
a2=1;
cout<<"1,1"; for (int i=2;i>num;
for (i=num;i>0;i--)
{
result = result*i;
}
cout<<"\n\n The factorial of "<
int fact(int n)
{
int result;
if (n= =1)
{
return 1;
}
else
{
result = n * fact(n-1);
return result;
}
}
int main( )
{
int num;
cout<<"\nFor what function do you want to find the factorial : "; cin>>num;
cout<<"\n\n The result is : "<
using namespace std;
void backwards( )
{
char ch;
ch=getchar( );
if (ch!='\n')
{
backwards( );
}
cout<
inline double dollartors (double d) // The function is inline.
{
return 47*d; // Inline functions usually contain only one/two body lines
}
int main ( )
{
double dollar;
cout << "How many dollars :"; cin>>dollar;
cout<< "Rupees : "<>dollar;
cout<< "Rupees : "<< 47*d; //Inline function body substituted return 0; } The advantage is that the program needn’t save its present memory address, go to the function’s memory address, execute the function and return back to the original address. Instead the function code is brought into the main program and it is executed just like a normal C++ statement. Thus processing time can be reduced significantly. Remember: It is useful to make a function inline if its body consists of just one or two lines. Recap • A function is a group of statements written for a specific purpose and grouped within a single block. • A function has to be declared if it is called before being defined. • Arguments are passed to a function’s parameters. • The data type of the arguments should match the data type of the parameters. • If a function is declared as returning a value to the caller then it should return the corresponding data type value (unless it returns void). • The return statement is used to return a value to the caller as well as give back program control to the caller. • The main ( ) function returns value to the OS. • Overloaded functions should have the same name but different parameters. • Return data type cannot be used as a basis for function overloading. • Inline functions are used when the body of the function is very small (one or two lines). • Recursive functions are functions that call themselves. Some provision has to be provided for them to break out of recursivity. • Recursive functions have more overheads and are generally not used. More On Data Types and Variables The following topics are covered in this section: • Scope of Variables • Storage Classes Scope of variables Scope refers to the region where something is valid or the region where something can exist. Variables in C++ have a defined scope, which depends on the way they are declared. There are three places where a variable can be declared: as local variables, formal parameters and global variables. Remember: In C we can declare variables only in the starting of the function. In C++, we can declare variables anywhere within the program. Local Variables Variables declared within a function are called local variables (sometimes called automatic variables). These variables can be used only within the block (or function) in which they are declared. A block starts with an opening curly brace and ends in a closing curly brace. A local variable is created upon entry into the block and destroyed when the program exits that block. If you create a variable in the main ( ) function then it can be used only within the main ( ) function. That variable cannot be accessed by some other function that you may have created. For example: void test ( ) { // Start of block int q; q = 2; } // End of block void test2 ( ) // Start of another block { int q; q = 5; } The two q's declared in the two functions (test and test2) have no relationship with each other. Each q is known only within its own block (since it is a local variable). The main advantage is that a local variable cannot be accidentally altered from outside the block. Try it: Compile the following piece of code in your compiler and check the results int main( ) { int outer; { int inner; cout<<"enter the outer variable value : "; cin>>outer;
}
cout<<"\n Enter inner variable value : "; cin>>inner;
return 0;
}
What do you think will happen? The above program will lead to a compile-time error. Variables are visible only within the block of code where they are declared (unless they are global variables). The coding enclosed within the two braces is called as a ‘block’ of code. Thus:
{
int inner;
cout<<"enter the outer variable value : "; cin>>outer;
}
is a block of code within which we have declared an integer variable ‘inner’. This variable ‘inner’ is not visible outside of this block. Thus the statement:
cin>>inner;
will lead to an error because ‘inner’ is only known inside this block and not outside the block.
Note the difference between the two codes given below:
int main( )
{
int i=5;
{
int i; //This ‘i' is only visible within this block.
i=6;
}
cout<
int count; // count is a global variable
void increment( )
{
count=count+2;
}
int main ( )
{
count=1;
• increment( ); //count is now 3
count=count+1; //count is now 4
}
The above program is not complete but you can see that two functions (increment and main) can access the same variable ‘count’.
count=1;
The increment ( ) function increases the same count value by 2. Now count is 3 and finally the main ( ) function increases count by 1. The final count value is 4. This is a case of more than two variables accessing the same global variable.
Remember: Global variables will take up more memory because the compiler has to always keep it in memory. Avoid using too many global variables. Use it only if the variable is going to be used by a number of functions.
What would happen if a program uses an identifier as both local and global variable name? Consider the program below:
#include
int var=55; //Global variable
int main( )
{
int var=20; //Local variable with same name
cout<<"\nGlobal variable value is : "<<::var; var=var+1; cout<<"\nLocal variable value is : "<
#define PI 3.14 //Macro definition
int main( )
{
cout<
int main ( )
{
int test[20]; //we assume that the maximum limit is 20 numbers.
int size,i,j;
int temp;
cout<<"How many numbers do you want to compare : "; cin>>size;
cout<<"Enter the numbers you want to check : "; for(i = 0; i>test[ i ];
}
for(i = 0; itest[j] )
{
temp = test[ i ];
test[ i ] = test[ j ];
test[ j ] = temp;
}
}
}
cout<<"The numbers in ascending order are : "; for (i = 0; i
int main ( )
{
char name[15];
cout<< "Enter your name : "; cin>> name;
cout<< "Your name is "<
int main ( )
{
char name[20];
cout<<"Enter your full name : "; cin>>name;
cout<<"You entered your full name as : "<
int main( )
{
char name[10];
cout<<"Enter the name: "; cin.get(name,10); cout<
int main( )
{
char name[80];
cout<<"Enter the name: "; cin.get(name,80,'*'); cout<> a[ i ][ j ];
}
}
The outer ‘for’ loop starts with a value of 0.
i = 0
Corresponding to i=0 we will have two values for j (0 and 1). Hence with this you can get the values for a[0][0] and a[0][1]. This corresponds to the first row of the matrix. For the second row, the ‘i’ loop will execute a second time with a value of 1. Hence you can get the values for a[1][0] and a[1][1].
In the cout statement we have mentioned ‘i + 1’ and ‘j + 1’. This is just for the purpose of display. Remember that the compiler will start numbering from zero. The first element for the compiler will be the 0 x 0 element. For the user it is better if you refer to the first element as 1 x 1 rather than referring to it as 0 x 0.
Similarly, two ‘for’ loops can be used to display the values of a two-dimensional array.
Initializing multi-dimensional arrays:
Initializing a 2-D array is similar to that of a 1-D array.
int marks[2][3]={ 40,50,60,
70,80,90};
The above notation is used for readability. You might as well initialize the array as:
int marks[2][3]={ 40,50,60, 70,80,90};
Thus if you use the following initialization (hoping that marks[0][2] will be 0):
int marks[2][3]={ 40,50,
70,80,90};
the compiler will treat it as:
int marks[2][3]={ 40,50,70,80,90};
and marks[0][2] will be 70 while marks[1][2] will be 0. Only trailing elements will be automatically initialized to 0. There is a better way to initialize multi-dimensional arrays. The following initialization:
int marks[2][3]={
{40,50},
{70,80,90}
};
actually produces the result we were looking for earlier. Now, marks[0][2] is zero. The additional pair of parentheses makes a big difference. Readability is improved further and now the compiler will set the trailing elements (which haven’t been initialized) in each row to 0. In our case, only the 3rd element of the first row is missing and hence this is initialized to zero.
You might recollect that in one dimensional arrays we could specify:
int a[] = {1,2,3};
and the compiler would translate this into:
int a[3] = {1,2,3};
The question arises as to whether we can extend this to 2-D arrays as well:
int marks[ ][ ]={
{40,50},
{70,80,90}
};
This will give a compile-time error. The compiler wouldn’t know how many columns you want to specify for the array (you’ll understand this concept when we deal with pointers and 2-D arrays in the next chapter). But for the time being remember that you can forget the 1st dimension but shouldn’t leave out the subsequent ones.
Let’s go one step further. What is a 3-D array?
int a[5];
int ab[2][5];
int abc[3][2][5];
‘ab’ is a 2-D array which consists of 2 one dimensional arrays (each of which can hold 5 elements). ‘abc’ is a 3-D array which consists of 3 two dimensional arrays (each of the 2-D arrays contains a 1-D array which can hold 5 elements). The concept can be extended to higher dimension arrays as well (but generally we wouldn’t use more than 3 dimensions).
How do we initialize a 3-D array?
int abc[3][3][2]={
{
{40,50},
{10,70},
{20,30}
},
{
{45,55},
{15,75},
{25,35}
}
};
The parentheses make the initialization pretty clear. Of course you can remove all the braces but the declaration wouldn’t be easy to understand. Again in the case of a 3-D arrays, you can drop the first dimension but should mention the other 2.
The following declaration is legal:
int abc[ ][3][2]={
{
{40,50},
{10,70},
{20,30}
},
{
{45,55},
{15,75},
{25,35}
}
};
You’ll have to take care of the braces. In the above example:
abc[0][0][0] = 40
abc[0][0][1] = 50
abc[0][1][0] = 10
abc[0][1][1] = 70
abc[0][2][0] = 20
abc[0][2][1] = 30
What happens in the following declaration?
int abc[ ][3][2]={
{40,50},
{10,70},
{20,30},
{45,55},
{15,75},
{25,35}
};
All that we’ve done is removed the braces which were used to denote that the 1st dimension was 2. But the compiler isn’t smart enough to know what’s on our mind and now it would create the array as: int abc[5][3][2].
abc[0][0][0] = 40
abc[0][0][1] = 50
abc[0][1][0] = 0
abc[0][1][1] = 0
abc[0][2][0] = 0
abc[0][2][1] = 0
abc[1][0][0] = 10
abc[1][0][1] = 70
abc[1][1][0] = 0
abc[1][1][1] = 0
abc[1][2][0] = 0
abc[1][2][1] = 0
and so on.
Moral of the story is that you should do your best to make things explicit when dealing with computers rather than assume that the computer would think the way you’re thinking.
Passing an Array to a Function
This topic is dealt with in depth when discussing about pointers. A simple method of passing arrays to functions is illustrated below: #include
void disp(int a[ ] )
{
for (int i=0;i<3;i++) { cout<
#include //needed for using the manipulator setw ( )
int main( )
{
int i , j , r1 , r2 , c1 , c2 , a[20][20] , b[20][20] , c[20][20];
cout<<"Enter the number of rows and columns of first matrix :"; cin>>r1>>c1;
cout<<"Enter the number of rows and columns of second matrix :"; cin>>r2>>c2;

// If the matrix orders are not equal then addition is not possible
if ( (r1! = r2) || (c1!=c2) )
{
cout<>a[ i ][ j ];
}
}
for (i = 0; i>b[ i ] [ j ];
}
}
cout<>a1.name;
cout<<"Enter the city : "; cin>>a1.city;
cout<<"Enter the telephone number : "; cin>>a1.tel;
cout<<"\nThe size of the structure variable is : "<>a1.name;
cout<<"Enter the city : "; cin>>a1.city;
cout<<"Enter the telephone number : "; cin>>a1.tel;
cout<<"Enter the date of birth (day, month and year) : "; cin>>a1.birthday.day>>a1.birthday.month>>a1.birthday.year;
cout<<"\nThe size of the structure variable is : "<
union shirt
{
char size;
int chest;
int height;
};
int main( )
{
shirt mine;
cout<<"\nSize of the union is : "<>mine.size;
cout<<"\nThe size is : "<>mine.chest;
cout<<"\nThe size is : "<>mine.height;
cout<<"\nThe size is : "<
int main ( )
{
int var=100;
cout<<"Value : "<
int main( )
{
int marks[3];
int* p;
p = &marks[2]; // Pointer points to the third element of array.
marks[0]=58;
marks[1]=61;
marks[2]=70;
p = p-1; //pointer decrements by one, goes to the previous integer address
cout<
void clear(int *point, int size)
{
for (int i=0;i
int square (int x)
{
return x*x;
}
int main ( )
{
int num = 10;
int answer;
answer = square(num);
cout<<"Answer is "<
void square (int *x)
{
*x = (*x) * (*x);
}

int main ( )
{
int num = 10;
square(&num);
cout<<" Value of num is "<
int main( )
{

int x;
int &ref = x; //ref is a reference variable
x=5;
cout<
void swap (int &x, int &y) //pass by reference
{
int t;
t = x;
x = y;
y = t;
}
int main ( )
{
int a , b;
cout<<"Enter the value for a : "; cin>>a;
cout<<"Enter the value for b : "; cin>>b;
cout<<"a and b before swap are : "<
int* create( )
{
int marks[3];
int *pt=marks;
for (int i=0;i<3;i++) { marks[i]=80; } return pt; } int main( ) { int *p; p=create( ); cout<
int main ( )
{
int size,i;
cout<<"Enter the size of the array : "; cin>>size;
int marks[size]; //WRONG
cout<<"\nEnter the marks: "; for (i = 0; i>marks[i];
}
cout<>size;
with:
size=4;
Now everything should be fine. Is it so? Try it and you’ll get the same compiler error. The compiler reads and stores the value of 4 for ‘size’ but it still will not substitute that value in:
int marks[size];
The compiler assumes that ‘size’ is a variable (since it was declared like that) and since a variable’s value can change in the program, it will not compile the code. One way to correct this is by declaring the maximum size of the ‘marks’ array by saying:
int marks[4]; //program will compile
There is no need for the variable ‘size’ and the user can enter only a maximum of 4 values because that is the space allocated for the array ‘marks’.
Another way to correct the program is to declare the variable ‘size’ as a constant.
const int size=4;
Now you can use:
int marks[size];
The reason that this is valid is because the compiler makes note of the fact that ‘size’ is a constant and has been given a constant value 4. Since this value will never change in the program and space will be allocated for 4 elements in the array ‘marks’. C programmers made use of macros (instead of ‘const’):
#define SIZE 4
to define constants. When the compiler comes across the term ‘SIZE’ anywhere in the program it will simply substitute the value of 4 for ‘SIZE’.
But whatever you do, the compiler limits you to fixing the size of the array at compile-time. Can you decide the array size at run-time? Dynamic allocation comes to the rescue.
Dynamic allocation means allocating (or obtaining) and freeing memory at run-time. There are certain cases where run-time decisions are better. For example, deciding the size of an array. Similarly you can free up allotted memory in your program when you don’t need a particular array by deleting the entire array itself. The two operators used for this purpose are: ‘new’ and ‘delete’.
‘new’ is used to allocate memory while ‘delete’ is used to free the allocated memory (memory which was allocated by ‘new’). The free memory available is sometimes referred to as the heap. Memory that has been allocated by ‘new’ should be freed by using ‘delete’. If you don't use ‘delete’ then the memory becomes a waste and cannot be used by the system. This is called memory leak (i.e. when allocated memory is never returned to the heap). You could go on taking memory from the heap till it gets exhausted. This will lead to memory leak and can cause problems to your program and to other programs which attempt to take memory from the heap.
The syntax is:
data-type * name = new data-type;
delete name ;
Beware: Both data types should be the same.
Example:
int * p = new int;
delete p;
Remember: delete p;
means that the data pointed to by ‘p’ is deleted. The pointer ‘p’ will not get deleted. The following coding is correct:
int m = 20;
int *p = new int;
*p=5;
cout<<*p<>size;
int *marks = new int[size];
cout<<"\nEnter the marks: "; for (i = 0; i>marks[i];
}
cout<
int sum(int a, int b)
{
return (a+b);
}
void func(int d, int e, int (*p1)(int,int))
{
cout<<"The result is : "<<(*p1)(d,e); } int main( ) { int (*p)(int,int); p=sum; func(5,6,p); return 0; } The output is: The result is : 11 Though the program is simple a few statements might appear confusing. The statement int (*p) (int,int); declares a pointer to a function that has a return value of integer and takes two arguments of type integer. sum( ) is a function with return data type of integer and also with two arguments of type integer. Hence the pointer ‘p’ can point to the function sum ( ). Thus we assign the address of the function sum ( ) to ‘p’: p = sum; We’ve also defined another function called as ‘func ( )’ which takes two integer arguments and a third argument which is a pointer to a function. The idea is to pass the function sum ( ) to the function ‘func( )’ and call the sum ( ) function from func ( ). func(5,6,p); will call the func ( ) function and it will pass pointer ‘p’ to func ( ). Remember that p is a pointer to sum ( ). Hence in reality we are actually passing a function as argument to another function. Let’s expand the program one step further by creating another function called product( ) which will return the product of the two arguments. #include
int sum(int a, int b)
{
return (a+b);
}
int product(int x,int y)
{
return (x*y);
}
void func(int d, int e, int (*p1)(int,int))
{
cout<pin=60004;
p->tel=23451;
p=p+1; //Now points to record[1]
p->pin=50023;
p->tel=89732;
p=record;
cout<pin;
cout<tel;
p=p+1; //Points to record[1]
cout<pin;
cout<tel;
return 0;
}
The output is:
The pincode is : 60004
The tel. no. is : 23451
The pincode is : 50023
The tel. no. is : 89732
You’ll notice that to access the individual elements we have made use of different operators. When you use pointers, you should not use the dot operator. Instead we make use of the arrow operator (->).
p->pin=60004;
Actually, the dot operator (or the member operator) can be used but you have to be careful about operator precedence. To use the member operator we’ll have to dereference the pointer and then use it. The following expression:
*p.pin
would be wrong. The dot operator is a post-fix operator and it has higher precedence over the dereferencing operator (which is a pre-fix operator). So to set it right we will have to use:
(*p).pin
Thus we could also have used the following code in our program:
cout<>id;
cout<<”Salary of that employee is:”<
#include
/* This function can accept varying number of integer arguments.
It will sum the arguments and return the result.
*/
int sum(int a, ...)
{
va_list args;
va_start(args,a);
int result=a;
for(; ;)
{
int temp=va_arg(args,int);
if (temp==0) //can also check for NULL
{
break;
}
else
{
result+=temp;
}
}
va_end(args);
return result;
}
int main( )
{
cout<<"\nThe sum is : "<

C & C++

C and C++
Dennis Ritchie developed C and it was quite popular. An interesting feature in C is the use of functions. The programmer could write a function for checking whether a number is odd or even and store it in a separate file. In the program, whenever it is needed to check for even numbers, the programmer could simply call that function instead of rewriting the whole code. Usually a set of commonly used functions would be stored in a separate file and that file can be included in the current project by simply using the #include syntax. Thus the current program will be able to access all functions available in ‘filename’. Programs written in C were more structured compared to high level languages and another feature was the ability to create your own data types like structures. For instance if you want to create an address book program, you will need to store information like name and telephone number. The name is a string of characters while the telephone number is an integer number. Using structures you can combine both into one unit. Similarly there are many more advantages of using C.
Though C seemed to be ideal, it was not effective when the programs became even more complex (or larger). One of the problems was the use of many functions (developed by various users) which led to a clash of variable names. Though C is much more efficient than BASIC, a new concept called Object Oriented Programming seemed better than C. OOP was the basis of C++ (which was initially called ‘C with classes’). C++ was developed by Bjarne Strastroup. In object oriented programming, the programmer can solve problems by breaking them down into real-life objects (it presented the programmer with an opportunity to mirror real life). What is an object? This topic is dealt with extensively in the chapter on ‘Objects and Classes’ but a brief introduction is provided here.
Consider the category of cars. All cars have some common features (for example all cars have four wheels, an engine, some body colour, seats etc.). Are all cars the same? Of course not. A Fiat and a Ford aren’t the same but they are called as cars in general. In this example cars will form a class and Ford (or Fiat) will be an object.
For those people who know C programming, it would be useful to know the differences between C and C++. Basically C++ includes everything present in C but the use of some C features is deprecated in C++.
• C does not have classes and objects (C does not support OOP)
• Structures in C cannot have functions.
• C does not have namespaces (namespaces are used to avoid name collisions).
• The I/O functions are entirely different in C and C++ (ex: printf( ), scanf( ) etc. are part of the C language).
• You cannot overload a function in C (i.e. you cannot have 2 functions with the same name in C).
• Better dynamic memory management operators are available in C++.
• C does not have reference variables (in C++ reference variables are used in functions).
• In C constants are defined as macros (in C++ we can make use of ‘const’ to declare a constant).
• Inline functions are not available in C.
Let’s recap the evolution of programming languages: initially programs were written in terms of 1s and 0s (machine language). The drawback was that the process was very tedious and highly error-prone. Assembly language was developed to write programs easily (short abbreviations were used instead of 1s and 0s). To make it even simpler for programmers, high level languages were developed (instructions were more similar to regular English). As the complexity of programs increased, these languages were found to be inadequate (because they were unstructured). C was developed but even that was not capable of dealing with complex or larger programs. This led to the development of C++.
Note: Sometimes languages are divided into low level and high level only. In such a classification, C/C++ will come under high level languages.
Why do you need to learn C++?
There are many people who ask the question, "why should I learn C++? What use is it in my field?" It is a well-known fact that computers are used in all areas today. Programming is useful wherever computers are used because it provides you the flexibility of creating a program that suits your requirements. Even research work can be simulated on your computer if you have programming knowledge. Construction and programming may appear to be miles apart but even a civil engineer could use C++ programming. Consider the case of constructing a physical structure (like a pillar) in which the civil engineer has to decide on the diameter of the rods and the number of rods to be used. There are 2 variables in this case:
1. The number of rods needed (let’s denote it as ‘n’) and
2. The diameter of each rod (let’s call it as ‘d’)
The civil engineer might have to make a decision like: "Is it cost-effective for me to have 10 rods of 5cm diameter or is it better to have 8 rods of 6cm diameter?" This is just one of the simple questions he may have in his mind. There are a few related questions: "What is the best combination of number of rods, their diameters and will that combination be able to handle the maximum stress?"
Usually equations are developed for each of the factors involved. It would be much easier if the civil engineer could simply run a program and find out what is the best combination instead of manually trying out random values and arriving at a solution. This is where programming knowledge would benefit the engineer. Any person can write a good program if he has adequate knowledge about the domain (domain refers to the area for which the software is developed. In this case it is construction). Since the civil engineer has the best domain knowledge he would be able to write a program to suit his requirements if he knew programming.
Programming is applicable to almost every field- banking (for maintaining all account details as well as the transactions), educational institutions (for maintaining a database of the students), supermarkets (used for billing), libraries (to locate and search for books), medicine, electrical engineering (programs have been developed for simulating circuits) etc.
Binary Numbering System
________________________________________
The following 2 sections on binary numbering system and memory are optional but recommended. If you’ve taken a course in electronics you probably already know about this and can use the material provided here as a refresher. Having knowledge of the binary system and computer memory will help in understanding some features in programming.
________________________________________
The heart of the computer is the microprocessor, which is also referred to as the processor. The microprocessor is the main part of the computer’s CPU (central processing unit). A processor consists of millions of electronic switches; a switch can be either in ON or OFF state. Thus there are only two distinct states possible in these devices. In our real-world calculations we make use of the decimal system (which has 10 distinct states/numbers: 0 to 9). Counting up to ten is easy for humans but would be quite difficult for computers. It is easier to create a device capable of sensing 2 states than one capable of sensing 10 states (this also helps reduce on errors). Computers make use of the binary system (i.e. they store data in binary format and also perform calculations in binary format). The binary system (binary meaning two) has just two numbers: 1 and 0 (which correspond to the ON and OFF state respectively – this is analogous to a switch which can either be in ON state or in OFF state).
When we have different systems (binary, decimal etc.), there ought to be a way of converting data from one system to the other. In the decimal system the number 247 stands for 7*100 + 4*101 + 2*102 (add it up and the result will be 247; i.e. in each place we can have one of the 10 digits and to find the actual place value we have to multiply the digit by the corresponding power of 10). For example:
247 = (2 x 102) + (4 x 101) + (7 x 100) = 200 + 40 + 7
1258 = (1 x 103) + (2 x 102) + (5 x 101) + (8 x 100) = 1000 + 200 + 50 + 8
Note: In C++ and most other computer languages, * is used as the multiplication operator.
The same concept holds good for a binary number but since only two states are possible, they should be multiplied by powers of 2.
Remember: A binary digit is called a bit.
So, what is the value of 1101? Multiply each position by its corresponding power of 2 (but remember, you have to start from 20 and not from 21). The value for 1101 is 13 as illustrated in the figure below:

An alternate method to obtain the value is illustrated below (but the underlying concept is the same as above):

It is easy to obtain the values which are written above each bit (27=128, 26=64 and so on). Write these values on top and then write the binary number within the squares. To find the equivalent decimal value, add up the values above the square (if the number in the square is 1). If a number is denoted as 1101, then this stands for the lower (or last) four bits of the binary number (the upper bits are set to 0). Hence 1101 will come under the values 8, 4, 2 and 1. Now, wherever there is a 1, just add the value above it (8+4+1=13). Thus 13 is the decimal equivalent of 1101 (in binary format). To distinguish between decimal and binary we usually represent the system used (decimal or binary) by subscripting the base of the system (10 is the base for the decimal system while 2 is the base for the binary system).
Hence (13)10 = (1101)2

Computers store information in the form of bits and 8 bits make a byte. But memory capacity is expressed as multiples of 210 bytes (which is equal to 1024 bytes). 1024 bytes is called a Kilobyte. You may wonder why it is 1024 and not 1000 bytes. The answer lies in the binary system. Keeping uniformity with the binary system, 210=1024 and not 1000 (the idea is to maintain conformity with the binary system).
Beware: The bit in position 7 in fig 1.1 is actually the 8th bit of the number (the numbering of bit starts from 0 and not 1). The bit in the highest position is called as the most significant bit. In an 8 bit number, the 7th bit position is called the most significant bit (MSB) and the 0th bit is known as the least significant bit (or LSB). This is because the MSB in this case has a value of 128 (28) while the LSB has a value of just 1.
________________________________________
Computer Memory
________________________________________
We know that computers can operate only on bits (0s and 1s). Thus any data that has to be processed by the computer should be converted into 0s and 1s.
Let us suppose that we want to create a text file containing a single word “Hello”. This file has to be stored physically in the computer’s memory so that we can read the file anytime in the future. For the time being forget about the file-storage part. Let’s just concentrate on how the word “hello” is stored in the computer’s memory. Computers can only store binary information; so how will the computer know which number corresponds to which alphabet? Obviously we cannot map a single bit to a character. So instead of bits we’ll consider a byte (8 bits). Now we can represent 256 characters. To perform map a character to a byte we’ll need to use some coding mechanism. For this purpose the ASCII (American Standard Code for Information Interchange) is used. In this coding system, every alphabet has an equivalent decimal value. When the computer uses ASCII, it cannot directly use the decimal value and it will convert this into an 8-bit binary number (in other words, into a byte) and store it in memory.
The following table shows part of the ASCII code.
Character Equivalent decimal value Binary value
A 65 0100 0001
B 66 0100 0010
a 97 0110 0001
b 98 0110 0010
In this way each character is mapped to a numeric value. If we type the word hello, then it is converted into bytes (5 bytes- one for each character) based on the ASCII chart and is stored in memory. So ‘hello’ occupies 5 bytes or 40 bits in memory.
Note: It is very important to know the binary system if you want to use the bitwise operators available in C++. The concept of memory is useful while learning pointers.
A question arises, “where are the individual bits stored in memory?” Each individual bit is stored in an electronic device (the electronic device is technically called a flip-flop; which is something like a switch). A single flip-flop can store one bit. Consider the fig. below:

As mentioned earlier we deal in terms of bytes rather than bits. The figure shows a 4-byte memory (which means it can hold 32 bits – each cell can store one bit). All information is stored in memory and the computer needs some method to access this data (i.e. there should be some way of distinguishing between the different memory locations). Memory addresses serve this purpose. Each bit can be individually accessed and has a unique memory address. To access the first byte, the computer will attempt to read the byte stored at memory address 1.
If memories didn’t have addresses then the computer would not know from where it has to read data (or where it has to store data). An analogy to memory address is the postal address system used in real-life. A city will have a number of houses and each house has a unique address. Just imagine the situation if we didn’t have any postal address (we wouldn’t be able to locate any house in the city!). One difference is that a memory address can house only bits and nothing else.
Memory address representations are not as simple as shown above. In the above case we’ve considered a memory that has capacity to store just 4 bytes. Memories usually contain kilobytes or gigabytes of space. As the amount of memory available increases, so does the size of the address (the address number might be in the range of millions). Thus instead of using the decimal system for addresses, the hexadecimal numbering system is used. Hexa means 16 and the distinct numbers in this system are 0 to 9 followed by A, B, C, D, E and F where A= 10 in decimal, B= 11 in decimal and F= 15 in decimal.
Counting in hexadecimal system will be 0…9, A, B…F, 10,11,12,13…19,1A, 1B, 1C…and so on.
It is quite clear that 10 in hexadecimal does not equal 10 in decimal. Instead, (0F)16 = (15)10, (10)16 = (16)10 and (11)16 = (17)10
Four bits form a ‘nibble’. Eight bits form a ‘byte’ and four bytes of memory are known as a ‘word’. There is some significance attached to a ‘word’ which we shall deal with later.
Another term related to memory is ‘register’. A register consists of a set of flip-flops (flip-flops are electronic devices that can store one bit) for storing information. An 8-bit register can store 8 bits. Every processor has a set of internal registers (i.e. these registers are present within the processor and not in an external device like a hard disk). These registers (which are limited in number depending on the processor) are used by the processor for performing its calculations and computations. They usually contain the data which the processor is currently using. The size of the register (i.e. whether the registers will be 16-bit, 32-bit or 64-bit registers also depends on the processor). The common computers today use 32-bit registers (or 4-byte registers). The size of a register determines the ‘word-size’ of a computer. A computer is more comfortable (and prefers) working with data that is of the word-size (if the word-size is 4 bytes then the computer will be efficient in computations involving blocks of 4 byte data). You’ll understand this when we get into data types in the subsequent chapters.
The different types of memory are:
1. Secondary storage (for example the hard disk, floppy disks, magnetic disks, CD-ROM) where one can store information for long periods of time (i.e. data is retained in memory irrespective of whether the system is running or not).
2. The RAM (random access memory) is used by the computer to store data needed by programs that are currently running. RAM is used for the main (primary) memory of the computer (all programs which are executed need to be present in the main memory). The RAM will lose whatever is stored in memory once the computer is switched off.
3. ROM (read only memory): This contains instructions for booting up the system and performing other start-up operations. We cannot write to this memory.
4. The internal registers within the processor- these are used by the computer for performing its internal operations. The compiler will decide what has to be stored in which register when it converts our high-level code into low-level language. As such we won’t be able to use these registers in our C++ code (unless we write assembly code).
Remember: Secondary storage (also called auxiliary memory) is not directly accessible by the CPU. But RAM is directly accessible (thus secondary memory is much slower than the primary memory). For a program to execute it needs to be present in the main memory.
Which memory has lowest access time (or which memory can the CPU access quickly)?
The internal registers can be accessed quickly and the secondary storage devices take much longer to access. Computers also make use of a cache-memory. Cache memory is a high-speed memory which stores recently accessed data (cache access is faster than main memory access).

Related concept: In general cache means storing frequently accessed data temporarily in a place where it can be accessed quickly. Web browsers tend to cache web pages you visit frequently on the hard disk. Generally when we type in a website address, the browser needs to query the website and request for the page; which is a time consuming process. When the browser displays this webpage, it internally caches (stores a copy) this webpage on our hard disk also. The next time we time the same website address, the browser will directly read out from the hard disk rather than query the website (reading from hard disk is faster than accessing a web server).
Remember: Computers store information using the binary system, addresses are represented in the hexadecimal system and in real-life we use the decimal system.
A 3-bit number can be used to form 8 different combinations (including the 000 combination).
Binary Decimal Equivalent
000 0
001 1
010 2
011 3
100 4
101 5
110 6
111 7
If 3 bits are used then the maximum possible decimal number that can be represented is 7 (not 8 because the first number is 0). Similarly if an 8-bit number can be used to represent up to (2^8) different values (0 to 255 in the decimal system).
A binary number can be either signed or unsigned. When a number is unsigned (we don’t bother about the sign), it means that the number is always positive. If a number is signed, then it could be positive or negative. +33 is a signed number (with a positive sign). In real life, we can use + or – to indicate whether a number is positive or negative but in computers only 1s and 0s can be used. Every decimal number has a binary equivalent. The binary equivalent for the decimal number 8 is 00001000. If this is a signed number then +8 would be written as 00001000 and –8 would be denoted by 10001000. Notice the difference between the two. The 7th bit (or the most significant bit) is set to 1 to indicate that the number is negative.
Assume the number 127.
For +127 you will write: 01111111
For –127 you will write: 11111111
For 255 you will write: ?
Well, the value for 255 cannot be written using a signed 8-bit number (because the 7th bit is reserved for the sign). If the unsigned representation was used then 255 can be represented as 11111111 (in this case the MSB signifies a value and is not concerned about the sign of the number).
What is the point to note here? By using a signed representation the maximum value that can be represented is reduced. An 8 bit unsigned binary number can be used to represent values from 0 to 255 (11111111 will mean 255). On the other hand, if the 8 bit binary number is a signed number then it can represent from –127 to +127 only (again a total of 255 values but the maximum value that can be represented is only 127).
Beware: Signed representation in binary format will be explained in detail later. Computers store negative numbers in 2s complement rather than storing them directly as shown above.
Remember: In signed numbers the MSB (in the binary representation) is used to indicate the sign of the number.

Your very first C++ Program
________________________________________
All the example programs in this book have been tested in Turbo C++ compiler (the programs were also tested in Visual C++ 6.0). They should run on other C++ compilers as well.
Let us start with a basic C++ program. This will give you an idea about the general structure of a C++ program. Let’s write a program in which the user can enter a character and the program will display the character that was typed:
// My first C++ program
# include
int main( )
{
char letter;
cout << "Enter any letter" ; cin >>letter;
cout << "The letter you entered is : " <, it will physically include the iostream header file in your source code (i.e. the entire file called iostream.h file will be pasted in your source code). This is one of the standard header files which you’ll use in almost all of your C++ programs.

• int main( ) : Every C++ program has to have one ‘main’ function. Functions will be explained later. Remember that the compiler will execute whatever comes within the ‘main’ function. Hence the instructions that have to be executed should be written within the ‘main’ function. Just as the name implies, ‘main’ is the main part of the C++ program and this is the entry point for a C++ program.
• { : Functions are defined within a block of code. Everything within the opening and closing braces is considered a block of code. ‘main’ is a function and hence we define this function within braces. This is as good as telling the compiler, “The ‘main’ function starts here”.
• char letter; : ‘letter’ is the name of a variable. Instead of the name ‘letter’ we could also use any other name. ‘char’ defines ‘letter’ as a character variable. Therefore, the variable ‘letter’ will accept the value of only one character.
• cout << "Enter any letter" ; : This is followed by the << operator (known as the insertion operator). Following this operator, anything typed within double quotes will be displayed on the screen. Remember that cout and << go together. ‘cout’ is known to the compiler already (since it is defined in the iostream header file which has been included). So when the compiler comes across cout<<, it knows what to do. • cin >>letter;: cin is the opposite of cout. cin>> is used to obtain the value for a variable from the user. (>> is known as the extraction operator). Input is usually obtained from the keyboard.
• return 0; : This statement tells the compiler that the ‘main’ function returns zero to the operating system (return values will be discussed in the chapter on functions).
• }: The closing brace is used to tell the compiler that ‘this is the end of the function’. In our case, it is the end of the ‘main’ function and this indicates the end of the program as well.
You might have noticed in the above program that every statement is terminated with a semi-colon (;). That is exactly the use of the semi-colon. It is used to tell the compiler that one instruction line is over. If you don’t put semi-colons in your program, you will get errors while compiling.
A variable is used for temporary storage of some data in a program. In the above example, ‘letter’ was a variable. Every variable belongs to a particular type (referred to as data type). The different data types in C++ are discussed later. In the above program:
char letter;
declares ‘letter’ as a character variable (a character is one of the basic data types in C++). When the compiler encounters this statement, it will allocate some memory space for this variable (i.e. any value which is assigned to the variable ‘letter’ will be stored in this allocated memory location). When the required memory space has been allocated we say that the variable has been defined (in this case a single statement will declare and define the variable ‘letter’).
________________________________________
Some points to remember:
When we want to display something on the screen we will code it as:
cout<>variable-name;
Beware of the direction of the >> and << operators. In the statement cout<>variable;
information (the value of the variable) flows from ‘cin’ (which would be the keyboard) into the variable (i.e. the value is stored in the variable). Information will flow in the direction of the arrows (<< or >>). ‘cout’ is linked to the standard display device (i.e. the monitor) while ‘cin’ is linked to the standard input device (i.e. the keyboard). Hence, you can’t use
cout>>variable;
This will cause an error while compiling. ‘cout’ and ‘cin’ are already pre-defined and so you can use them directly in your programs. 'iostream.h’ is a header file that is used to perform basic input and output operation (or general I/O like using ‘cin’ and ‘cout’).
Remember: C++ is a case-sensitive language, which means that the compiler will not consider ‘letter’, ‘LETTER’ and ‘Letter’ as the same.
How to run your first program in the compiler?
Saving and compiling the program:
There are many C++ compilers available in the market. Some of them are freeware (meaning that they are free to use) while others have to be paid for. Turbo C++ compiler might be the simplest to use (but it is not freeware). Simply choose "New File" and type out the program coding. Suppose you are using some other compiler, click on File and choose "New". Some compilers may have the option of creating a C++ source file while other compilers may require a new project to be created. Whatever the method you will ultimately come to the step of creating a C++ source file. After typing the code in the compiler, save the file by giving it some name. The "Save As" option will appear under the "File" menu. Give a name (for example: first). Now the file is saved as first.cpp. All C++ source files are saved in *.cpp format. Just like *.doc represents a Word document file, *.cpp denotes a C++ (C Plus Plus) source file.
In the compiler program there will be an option called ‘Compile’ in the menu bar. Select the compile option and the compiler will do its work. It will compile the program (or in other words, it will read whatever has been typed) and in case there are any errors, the compiler will point out the line where the error was detected. Check whether the program has been typed exactly as given earlier. Even if a semi-colon is missing, it will lead to errors. If the compiler says no errors (or if the message "compiled successfully" appears), then you can go to the next stage: building the *.exe file.
*.exe file extension stands for executable files. A *.cpp file cannot be run directly on the computer. This has to be converted into a *.exe file and to do so select the "Make or Build exe" option in the compiler. The file ‘first.exe’ will be created. Now the program can be executed from the DOS prompt by typing ‘first’. But instead of running the program every time from DOS, it will be convenient to run the program from the compiler itself and check the output. In the compiler there will be another option called "Run". Just click on this and the program will run from the compiler itself (you needn’t switch back and forth between DOS and the compiler screen).
The figure should give you a rough idea as to how the executable file is created from the C++ source code.


The source code is the program that you type. Source code is converted into object code by the compiler. The linker will link your object code with other object codes. This process of creating a C++ program is discussed in the last chapter.
Modification that might be needed in first.cpp (depending on your compiler):
A little problem might be encountered while running your program from the compiler (this problem will exist in Turbo C++ compiler). While running the program from the DOS prompt, this problem will not occur.
What’s the problem? When first.cpp is executed from the compiler the program will ask the user to enter a character. Once a character has been entered, the program will return to the compiler screen. You won't see your output! It might appear as if there is some problem with the program. What happens is that the program displays the character on the screen, immediately terminates the program and returns to the compiler screen. This happens so fast that you can’t see the output being displayed.
Modify your program as shown below (if you are using Turbo C++):
// Your first program modified: first.cpp
# include
# include
int main( )
{
char letter;
cout<< "Enter any letter" ; cin>>letter;
cout<< "The letter you entered is : " <>letter;
at the end of the program just before return 0;
The program flow will be the same as described earlier.
The latest compilers, like VC++ (Microsoft Visual C++ compiler) do not have any of the above problems even if the program is run from the compiler. VC++ will always ask the user to press a character to terminate the program.
Another alternative is to use a function called ‘system’, which is defined, in the header file: stdlib.h.
• system("PAUSE");
can be used to pause the program (i.e. execution of the program will continue only when the user presses a key).
• system("CLS");
can be used to clear the display screen. To use these two functions you have to type #include header file in your source code. The system( ) function actually executes a DOS command. (Try giving the commands ‘cls’ and ‘pause’ in your DOS prompt).

ISO - OSI MODEL

INTRODUCTION
The ISO (International Standards Organization) has created a layered model called the OSI (Open Systems Interconnect) model to describe defined layers in a network operating system. The purpose of the layers is to provide clearly defined functions to improve internetwork connectivity between "computer" manufacturing companies. Each layer has a standard defined input and a standard defined output.
Understanding the function of each layer is instrumental in understanding data communication within networks whether Local, Metropolitan or Wide.

ISO OSI The International Standards Organization (ISO) Open Systems Interconnect (OSI) is a standard set of rules describing the transfer of data between each layer. Each layer has a specific function. For example the Physical layer deals with the electrical and cable specifications. The OSI Model clearly defines the interfaces between each layer. This allows different network operating systems and protocols to work together by having each manufacturere adhere to the standard interfaces. The application of the ISO OSI model has allowed the modern multi­protocol networks that exist today. There are 7 Layers of the OSI model:
7. Application Layer (Top Layer) 6. Presentation Layer 5. Session Layer 4. Transport Layer 3. Network Layer 2. Data Link Layer 1. Physical Layer (Bottom Layer) The OSI model provides the basic rules that allow multiprotocol networks to operate. Understanding the OSI model is instrument in understanding how the many different protocols fit into the networking jigsaw puzzle. The OSI model is discussed in detail in


OSI Model Explained

This is a top-down explanation of the OSI Model, starting with the user's PC and what happens to the user's file as it passes though the different OSI Model layers. The top-down approach was selected specifically (as opposed to starting at the Physical Layer and working up to the Application Layer) for ease of understanding of how the user's files are transformed through the layers into a bit stream for transmission on the network.
There are 7 Layers of the OSI model:
· Application Layer (Top Layer) · Presentation Layer · Session Layer · Transport Layer · Network Layer · Data Link Layer · Physical Layer (Bottom Layer)

The OSI Seven-Layer Model In the 1980s, the European-dominated International Standards Organization (ISO), began to develop its Open Systems Interconnection (OSI) networking suite. OSI has two major components: an abstract model of networking (the Basic Reference Model, or -- seven-layer model --), and a set of concrete protocols. The standard documents that describe OSI are for sale and not currently available online.
Parts of OSI have influenced Internet protocol development, but none more than the abstract model itself, documented in OSI 7498 and its various addenda. In this model, a networking system is divided into layers. Within each layer, one or more entities implement its functionality. Each entity interacts directly only with the layer immediately beneath it, and provides facilities for use by the layer above it. Protocols enable an entity in one host to interact with a corresponding entity at the same layer in a remote host.

The seven layers of the OSI Basic Reference Model are (from bottom to top):
The Physical Layer describes the physical properties of the various communications media, as well as the electrical properties and interpretation of the exchanged signals. This layer defines the size of Ethernet coaxial cable, the type of BNC connector used, and the termination method. The Data Link Layer describes the logical organization of data bits transmitted on a particular medium. Ex: this layer defines the framing, addressing and checksumming of Ethernet packets. The Network Layer describes how a series of exchanges over various data links can deliver data between any two nodes in a network. Ex: this layer defines the addressing and routing structure of the Internet. The Transport Layer describes the quality and nature of the data delivery. Ex: this layer defines if and how retransmissions will be used to ensure data delivery. The Session Layer describes the organization of data sequences larger than the packets handled by lower layers. Ex: this layer describes how request and reply packets are paired in a remote procedure call. The Presentation Layer describes the syntax of data being transferred. Ex: this layer describes how floating point numbers can be exchanged between hosts with different math formats. The Application Layer describes how real work actually gets done. Ex: this layer would implement file system operations. The original Internet protocol specifications defined a four-level model, and protocols designed around it (like TCP) have difficulty fitting neatly into the seven-layer model. Most newer designs use the seven-layer model.
OSI's biggest problem is that it doesn't really offer anything new. The strongest case for its implementation comes from its status as an "international standard", but we already have a de facto international standard - the Internet. OSI protocols will be around, but its most significant contribution is the philosophy of networking represented by its layered model.
Protocol Layering Protocol layering is a common technique to simplify networking designs by dividing them into functional layers, and assigning protocols to perform each layer's task.
For example, it is common to separate the functions of data delivery and connection management into separate layers, and therefore separate protocols. Thus, one protocol is designed to perform data delivery, and another protocol, layered above the first, performs connection management. The data delivery protocol is fairly simple and knows nothing of connection management. The connection management protocol is also fairly simple, since it doesn't need to concern itself with data delivery.
Protocol layering produces simple protocols, each with a few well-defined tasks. These protocols can then be assembled into a useful whole. Individual protocols can also be removed or replaced.
The most important layered protocol designs are the Internet's original DoD model, and the OSI Seven Layer Model. The modern Internet represents a fusion of both models.
DoD Four-Layer ModelThe Department of Defense Four-Layer Model was developed in the 1970s for the DARPA Internetwork Project that eventually grew into the Internet. The core Internet protocols adhere to this model, although the OSI Seven Layer Model is justly preferred for new designs.
The four layers in the DoD model, from bottom to top, are:
The Network Access Layer is responsible for delivering data over the particular hardware media in use. Different protocols are selected from this layer, depending on the type of physical network. The Internet Layer is responsible for delivering data across a series of different physical networks that interconnect a source and destination machine. Routing protocols are most closely associated with this layer, as is the IP Protocol, the Internet's fundamental protocol. The Host-to-Host Layer handles connection rendezvous, flow control, retransmission of lost data, and other generic data flow management. The mutually exclusive TCP and UDP protocols are this layer's most important members. The Process Layer contains protocols that implement user-level functions, such as mail delivery, file transfer and remote login. DoD Four-Layer ModelThe Department of Defense Four-Layer Model was developed in the 1970s for the DARPA Internetwork Project that eventually grew into the Internet. The core Internet protocols adhere to this model, although the OSI Seven Layer Model is justly preferred for new designs.
The four layers in the DoD model, from bottom to top, are:
The Network Access Layer is responsible for delivering data over the particular hardware media in use. Different protocols are selected from this layer, depending on the type of physical network. The Internet Layer is responsible for delivering data across a series of different physical networks that interconnect a source and destination machine. Routing protocols are most closely associated with this layer, as is the IP Protocol, the Internet's fundamental protocol. The Host-to-Host Layer handles connection rendezvous, flow control, retransmission of lost data, and other generic data flow management. The mutually exclusive TCP and UDP protocols are this layer's most important members. The Process Layer contains protocols that implement user-level functions, such as mail delivery, file transfer and remote login.

World Wide Web

A Network Architecture Example: WWW

The World Wide Web is the Big New Thing in computer networking.
History:
In 1989, Tim Berners Lee proposed a global hypertext project, to be known as the World Wide Web. Based on the earlier "Enquire" work, it was designed to allow people to work together by combining their knowledge in a web of hypertext documents. Tim Berners Lee wrote the first World Wide Web server and the first client, a wysiwyg hypertext browser/editor which ran in the NeXTStep environment. This work was started in October 1990, and the program "WorldWideWeb" was first made available within CERN in December, and on the Internet at large in the summer of 1991.
Through 1991 and 1993, Tim Berners Lee continued working on the design of the Web, coordinating feedback from users across the Internet. His initial specifications of URIs, HTTP and HTML were refined and discussed in larger circles as the Web technology spread.

A browser, or viewer program is used to fetch and display "pages" of information from a server. A page is simply an ASCII text file, written using a simple markup language called Hypertext Meta Language (HTML).

Uniform Resource Locators - URLs

The URL is the basis of the WWW. Think of a URL as an address that can lead you to any file on any machine anywhere in the world. Unlike the common postal address, however, these are written backwards. (Actually backwards makes more sense. My postal adddress is:
HP Bischof
3002 ST RT 48
Oswego, 13126 NY,
USA.
But if you want to deliver a letter to me, shouldn't you first go to the USA, then NY, then Oswego, then 3002 ST RT 48, then to HP Bischof? The URL is written in that more logical order.)
A URL defines the location of a WWW page in the following way:
service:host:port/file and resource details
For example:

http://www.cs.oswego.edu:80/~hp/445/all-2.2.html#section4
http://www.av.digital.com/cgi-bin/query?pg=q&what=web
URLs on the Web don't have to use the HTTP protocol. Some other URLs you might encounter are:
ftp
file transfer protocol
news
for Usenet news groups
telnet
for telnet
mailto
to send email to a specific address

Connection Establishment

To fetch a WWW page, the browser application process running on your local computer first establishes a connection to the remote host.
What this means is that the browser process uses the facilities of the network connecting the two computers to send a "connection request" message to a server process running on the computer whose name was given in the URL.
If the remote server process is prepared to accept the connection, it responds with a "connection accepted" message.
Note that we are, for the moment, ignoring the process of "looking up" the remote host - discovering the network address associated with its domain name.

The HTTP Protocol

Once the two application processes have an established connection between them, they can communicate reliably.
The browser then sends a request, in ordinary plain text, to the server, thus:
GET /home.html
The string GET something is one of many commands defined in the Hypertext Transfer Protocol, HTTP. The server responds by returning the contents of a file.
Finally, the browser process interprets the HTML markup in the returned file, and displays it to the user.