getting started


MY FIRST C++ PROGRAM


Introduction to C++
C++ is an object oriented language, which combines the best of the structured programming techniques of C, thus making it a very powerful language. C++ is based on C and Simula 67 language. C was invented by Bjarne Stroustrup.
Since C++ is a superset of C, therefore most of C language constructs apply in C++ as well. A program in C++ can be written in both C style and Object Oriented style.
First Program
Let us start our tour of C++ with a simple program. Here is a simple program which outputs a line of text. It’s output is shown in the right column.

// This is my first C++ program
//It prints a line of text
# include <iostream>
int main()
{
std:: cout << “My first C++ program ” << std::endl;
return 0;  

 My first C++ program  


Structure of the C++ Program and C++ features
 Above program demonstrates several important features of C++ language. The structure of the program above is as follows:-
// This is my first C++ program
//It prints a line of text
are comments in C++ language.
# include <iostream>
is a preprocessor directive. It tells the preprocessor to include the contents of iostream header file in the program before compilation. This file is required for input output statements.
main Function
 int main()
is a function. C++ program is a collection of functions. Every program in C++ begins executing at the function main(). Every C++ program has exactly one main function and a collection of other functions.
A function is the main entity where all of the functionality of a program is defined. A function takes some input, processes it according to the some code written in the function body and produces an output which can be either sent to the user or can be used by other functions.
Keyword int in int main()
specifies the return type of a function. int specifies that the function main returns an integer value.
Brackets () after main signify that main is a function. Every function should be followed by a pair of brackets. The purpose of brackets is to pass the parameters list to the functions. Parameters are the number and type of arguments (inputs) which a function takes.
Opening brace ( { ) and closing brace ( ) mark the beginning and end of a function. Anything which is inside the braces is the body of that function.
In our example, the function body consists of only two statements,
{
std::cout << “My first C++ program. \n”;
return 0;
 }
Statement
std::cout << “My first C++ program ” << std::endl;
The above line is a statement in C++. A statement must always terminate with a semicolon (;) otherwise it causes a syntax error. This statement introduces two new features of C++ language, cout and <<operator.
When this statement is executed, it sends the string between the quotation marks to the standard output stream object – coutcout is a predefined object in C++ and the standard output stream is normally the screen.
The purpose of standard output stream object is to print the output on the device to which it is connected. Normally, the output device is screen but it can be programmed to output to any other device such as a printer. The following diagram illustrated the concept of cout.
User Screen
Monitor


  
 



                Object                              Insertion Operator                                 String variable
We used std:: before cout. This is required when we use # include <iostream> .
It specifies that we are using a name (cout) which belongs to namespace std. Namespace is a new concept introduced by ANSI C++ which defines the scope of identifiers which are used in the program. stdis the namespace where C++ standard libraries are defined.
Operator << is the insertion stream operator. It sends contents of variable on its right to the object on its left. In our case, right operand is the string “My first C++ program” and left operand is cout object. So it sends the string to the cout object and cout object then displays it on the output screen.
endl is the line feed operator in C++. It acts as a stream manipulator whose purpose is to feed the whole line and then point the cursor to the beginning of the next line. We can use \n (\n is an escape sequence) instead of endl for the same purpose. Then the code would be
std::cout << “My first C++ program \n”;
Return Statement
Last line in the body of our first program is
return 0;
The keyword return is a special statement which is used to exit a function and return a value. This statement exits the function main indicating its completion and returns the value 0 to the operating system indicating that the program successfully ran to completion. return statement is included at the end of every main function.
OUTPUT
When this program is run, it prints the following output
My first C++ program
For programs to do exciting things, they should be written, compiled and then run on a computer using a compile or IDE. Next tutorial, How to compile and run programs shows how to run programs.
Congratulations!! You have just run your first C++ program and have understood many important features of C++.

-----------------------------------------------------------------------------------------------------------------------------------

How to write and compile C++ programs

In order to run a program and see it doing wonderful things, you should first write the program. The program can be written in any text editor, such as vi and emacs in Unix environment and using command prompt in DOS. There are also several Integrated Development Environment (IDE) packages available which provide a complete programming environment for C++ in which you can write, compile, run, and debug your program.
C++ programs are saved with extensions .C, .cc, .cpp, .cxx depending on the platform you are working upon.
Once you have saved a program, next stage is compiling it using a compiler which converts your C++ program into the object code which the computer can understand.
Compile using g++ compiler
If you are using UNIX environment and using g++ compiler, then compiling your C++ program is simple. After you have saved the program file, simply type the command
g++ program.cc –o program
where program is the name of the program. For example the name of our first program is first, then save it using extension “first.cc”. To compile, type
g++ first.cc –o first
To run the program, type first or ./first at the command prompt and your program will run.
Compile using DevC++ compiler
If you work on Windows and use DevC++, then editing and compiling is as easy as click of a button. DevC++ is an IDE which allows you to edit, compile, run and debug your program in the IDE itself.  If you want to install DevC++ then install it from here.
  1. Once you have installed and configured the software, Write and save your program using DevC++ itself. Create a new program by clicking on New à Project.

  1. Choose Empty Project from New Project dialog and choose a name for the program, in our case first and click Ok.
  1. Write the code of the program and save it.
  1. Click on Compile button (third row, first button) to compile your source code. If there are any errors in your program, then a window at the bottom will specify the warnings.
  2. After program is compiled, click on Run button (next to compile).
  3. However, DevC++ has a problem. As soon as you Run the program, output window opens momentarily and then it closes. So to come around this solution, set a breakpoint at the end of main function and then click on Debug instead of running it.


  1. When you run the program, output window will show the string.

Compile using VC++
If you use Visual C++ toolkit for C++ programming, then the procedure is same as in DevC++.
  1. To write the source code, Click on File à New Project. A dialog box will appear, click on A Empty Project and click Finish. Write your source code in the source code window.
  2. After you have saved your source code, click on Build button to compile the source code.
  3. Once the source code is compiled, click on Execute button to run the program. An output window will show the output of the program.


Now we have learnt how to edit, compile and run programs using compilers and IDE, its time to learn about more features of C++ language to get some real action. Next tutorial, Data Types and Variables tells about data types in C++, keywords and variables.
-------------------------------------------------------------------------------------------------------------------------------------
DATA TYPES AND VARIABLES

Before reading this tutorial, you must read First C++ Program.
CPU AND MEMORY
A computer acts on some data according to the instructions specified in a program (like our previous C++ program) and produces the output. This computation is done by Central Processing Unit(CPU) of the computer. A CPU of computer performs arithmetic operations such as addition, subtraction, multiplication and division and also performs logical operation on the data such as comparing two numbers.
     Memory of a computer is the area where data and programs are stored. A computer memory is made up of registers and cells which are capable of holding information in the form of binary digits 0 and 1 (bits). This is the way information is stored in a memory just like we memorize numbers using 0 to 9. Collection of 8 bits is called a byte. Normally the CPU does not accessed memory by individual bits. Instead, it accesses data in a collection of bits, typically 8 bits, 16 bit, 32 bit or 64 bit. The amount if bits on which it can operate simultaneously is known as the word length of the computer. When we say that Pentium 4 is a 32 bit machine, it means that it simultaneously operates on 32 bit of data. Data is stored in the memory at physical memory locations. These locations are known as the memory address.  It is very difficult for humans to remember the memory addresses in numbers like 46735, so instead we name a memory address by a variable.
VARIABLES
   Variables  are a way of reserving memory to hold some data and assign names to them so that we don't have to remember the numbers like 46735 and instead we can use the memory location by simply referring to the variable. Every variable is mapped to a unique memory address. For example, we have 3 variable v1, v2, v3. They may be assigned the memory addresses 32000, 12456, 67893 respectively. Here is the illustration.

a

32.45

86
                        
v1                                           v2                                           v3
32000                                     12456                                     67893

It specifies that there are three variables v1v2v3 (named by programmer) and have assigned the memory locations 32000, 12456 and 67893. These memory locations are not their values. The values of the variables are what you assign to them. You can assign value 86 to v1, 32.45 to v2 and 'a' to v3.
Declaring and defining variables
A variable in C++ must be declared (the type of variable) and defined (values assigned to a variable) before it can be used in a program. Following shows how to declare a variable.
DATA TYPES
Every variable in C++ can store a value. However, the type of value which the variable can store has to be specified by the programmer. C++ supports the following inbuilt data types:- int (to store integer values), float (to store decimal values) and char (to store characters), bool (to store Boolean value either 0 or 1) and void (signifies absence of information).
Integer data type
Integer (int) variables are used to store integer values like 34, 68704 etc. To declare a variable of type integer, type keyword int followed by the name of the variable. You can give any name to a variable but there are certain constraints, they are specified in Identifiers section. For example, the statement
int  sum;
declares that sum is a variable of type int. You can assign a value to it now or later. In order to assign values along with declaration use the assignment operator (=).
int sum = 25;
assigns value 25 to variable sum.
There are three types of integer variables in C++, shortint and long int. All of them store values of type integer but the size of values they can store increases from short to long int. This is because of the size occupied by them in memory of the computer. The size which they can take is dependent on type of computer and varies. More is the size, more the value they can hold. For example, int variable has 2 or 4 bytes reserved in memory so it can hold 2 32= 65536 values. Variables can be signed or unsigned depending they store only positive values or both positive and negative values. And short, variable has 2 bytes. Long int variable has 4 bytes.
Float data type
To store decimal values, you use float data type. Floating point data types comes in three sizes, namely floatdouble and long double. The difference is in the length of value and amount of precision which they can take and it increases from float to long double. For example, statement
float average = 2.34;
declares a variable average which is of type float and has the initial value 2.34
Character data type
A variable of type char stores one character. It size of a variable of type char is typically 1 byte. The statement
char name = 'c';
declares a variable of type char (can hold characters) and has the initial values as character c. Note that value has to be under single quotes.
Boolean
A variable of type bool can store either value true or false and is mostly used in comparisons and logical operations. When converted to integer, true is any non zero value and false corresponds to zero.
You can find typical size of all data types here.
KEYWORDS
Keywords are the reserved words in any language which have a special pre defined meaning and cannot be used for any other purpose. You cannot use keywords for naming variables or some other purpose. We saw the use of keywords main, include, return, int in our first C++ program.
IDENTIFIERS
Identifiers are the name of functions, variables, classes, arrays etc. which you create while writing your programs. Identifiers are just like names in any language. There are certain rules to name identifiers in C++. They are:-
  1. Identifiers must contain combinations of digits, characters and underscore (_).
  2. Identifier names cannot start with digit.
  3. Keyword cannot be used as an identifier name and upper case and lower case are distinct.
Identifier names can contain any combination of characters as opposed to the restriction of 31 letters in C.
CONSTANTS
Constants are fixed values which cannot change. For example 123, 12.23, 'a' are constants.
Now it's time to move on to our next tutorial Input values using cin operator.
------------------------------------------------------------------------------------------------------------------------------------
    Math Operations

Before reading this tutorial, you should learn about variables and input values using cin.


In any language, there are some operators to perform arithmetic, logical and control operations.

The basic operators which are used to perform arithmetic operations on integers are as follows:-

Operator                                              Operation
  
   +                                                       Addition, also called unary addition
  • Subtraction, also called unary subtraction
*                                                        Multiplication
   /                                                         Division
   %                                                       Modulus (remainder after division)
   ++                                                      Increment
--                                                       Decrement

The operators +,-,* and / perform the same operation as they do in other languages.  The operators + and – are unary operators and can take one or two operands. The multiply and divide are called binary operators as they take two operands.

Integer division will always give the result which is of integer type and truncates the remainder. The output of integer division will be the quotient. For example, 5/2 will give the answer 2 and not 2.5. The modulus operator gives the remainder after the integer division. For example, 5/2 will give the answer 1, which is the remainder. Here is a program which illustrates the functioning of the operators.




The result is: -


When the statement
d=a+b; is executed, it takes the values 20 and 30 of variables a and b respectively, performs their sum and assigns the result to variable d which gets the value 50.

Similarly, statement
e=a-b;  gives the result -10,

f=a*b;  gives the result 600, where integer variable a is equal to 20 and variable b is equal to 30.

The output of statement
h=a% b operator is 20 as it is modulo operator which gives the remainder when a is divided by b.

The output of division operator is 0 as the quotient of 20/30 is 0. 

Note here that all the answers are in integers as we have defined the variables to be of type int. If we define them to be of type float or double, then the answers would be different. Also, modulo operator (%) does not works with float and double.


In an expression which involves several operators, the order in which the operators are evaluated depends on the priority given to them. The priority given to the operators is called precedence. The operators such as *, /, % have higher precedence than the operators +,-. The operators *, / and % have same precedence and operators + and - have same precedence. For example, in the statement
a+b*c;  b*c is evaluated before and the result of b*c is added to a. It is same as

(a+(b*c));


If the expression contains operators of same precedence then the order in which they are evaluated can be either left associative or right associative. Left associative means that left most operators are evaluated first then the operators on the right. Right associative means that right most operators are evaluated first than the operators on the left. If the expression a+b+c is evaluated in the left associative manner, then result of a+b is added to c. Similarly in the right associative, result of b+c is added to a.


If the expression contains parentheses, then the natural order of execution of the operators is overridden by the parentheses. The parentheses are given more priority than the any of the operators. Parentheses force the operations to have higher precedence. If the expression contains nested parentheses, then the innermost parentheses are evaluated first. For example in the expression a*(b+c), b+c is evaluated before the multiplication operation.

Here is the program which illustrates the meaning of precedence, associativity and parentheses.


The result of the program is


In the given program a=20, b=30 and c=40. In the statement

a+a*b-c;

a*b is evaluated first then the operators + and – are evaluated. The operation a*b gives 600 and then a is added and c is subtracted which gives the final result 580.

In the statement a*b/c, the operators * and / have same precedence and it is left associative. The multiplication operator is evaluated before the division operator. The operation a*b gives the result 600 which is then divided by 40 and giving the final result as 15.

In the last statement parentheses are used, the innermost expression (b/c) is evaluated first giving the result 0 where b=20 and c=40, which is then multiplied with variable a and the final result is 0.
           

The operator ++ and -- are called an increment operator and decrement operator respectively. They are unary operators and are applied to integers. They perform the same function as x=x+1 in the case of increment operator and performs the function x=x-1 in the case of decrement operator. Increment operator increments the value of variable x by 1 whereas decrement operator decreases the value of variable x by 1.  For example ++x and x=x+1 have same effect. These operators are more precise and directly modify the values. If the operator is written in front of the variable then it is called prefix form whereas if the operator is written after the variable then it is called postfix form. Prefix form and postfix form have different meanings.

Prefix form - ++x. It means that value of variable x is incremented before the value is used in context. For example, z=++x; when x=6 gives z=7 and x=7. Same is the case with decrement operator for example, the expression z=--x when x=6 gives z=5 and x=5.

Postfix form - x++. It means that value of variable x is incremented after the value is used in context. For example z=x++, when x=6 gives z=6 and x=7.  Same is the case with decrement operator for example, the expression z=x--    when x=6 gives z=6 and x-5.


These operators consist of an operator sign and equality operator. They modify the current value of the variable by performing an operation. Consider the following case

x +=2; is same as x=x+2;
x *=2 ; performs the operation x = x * 2 and gives the value 6 when the original value of x was 3.

Basically these operators are short hand notations for the normal operators where the meaning is that the operation specified in the statement has to be performed on the variable left to the operator with the variable right to the equality operator and the value is stored in the variable left to the operator.

Let us discuss the next tutorial on control structures in C++.
-------------------------------------------------------------------------------------------------------------------------------------

Input values using cin operator

Before reading the tutorial, you should be familiar with variables and data types, find about them in tutorial on Variables and Data Types.
A computer program is an interactive program which takes values from user. To input values, C++ uses the Stan  Standard Input Stream cin operator. It is same as cout operator and is a predefined object in C++ which is normally attached to keyboard but can be attached to any other input device such as printer. Following example illustrates use of cin operator, where we input two values using cin operator and print sum and average of those values.
# include <iostream>
int main ()
{
float var1, var2, sum, avg;
std::cout << "Input first value" << endl;
std::cin >> var1;
std::cout << "Input second value" << endl;
std::cin >> var2;
sum = var1+ var2;
avg = sum / 2;
std::cout << "Sum is" << sum << endl;
std::cout << "Average is " << avg << endl;
return 0;
}

Input first Value
32.45
Input second value
12.76
Sum is 45.21
Average is 22.605

Lets say we in input the values 32.45 and 12.76, so the program will output sum as  45.21 and average as 22.605.
The program is similar to our first C++ program except that it declares variables var1var2sum and avg of type float to take values from user and to compute sum and average. Statement
float var1, var2, sum, avg; does this.
Next, we prompt the user to input values and take values using the cin operator. When the user inputs values and hits enter, then the value entered by user is collected by the cout object and send to the variable var2. Similarly, we input second value and send it to var2. Statements
std::cin << var1;
std::cin << var2; accomplish this.
<< is a stream extraction operator and its work is to extract values from operand on its left hand and assign it to operand on its right hand. In this case, it takes value from cin and assigns to variables var1 and var2.
Statements
sum = var1 + var2;
avg =  sum/2;
compute sum and average of the two values. First statement computes sum of values in var1 and var2 and assigns it to variable sum.
Second statement computes average by dividing sum by 2 and assigning the result to avg variable. These statements make use of arithmetic addition (+) operator. It will be discussed later in tutorial on Operators in C++.
Next statement
std::cout << "Sum is" << sum << endl;
prints the string and "Sum is" and then prints the value of sum variable and points the cursor the next line in the screen. Here, you can use multiple stream insertion operators (<<) in a single statement. This is known as cascading of operators. Similarly,
std::cout << "Average is " << avg << endl;
prints string "Average is " and then prints values of avg variable and points the cursor to the next line in the screen.
Finally the last statement returns value 0 to operating systems indicating that the program completed successfully.
Here is the screenshot of program when run in DevC++ compiler.

Here is the output of the program.

-------------------------------------------------------------------------------------------------------------------------------------
   If Else

Before reading this tutorial, you should have knowledge of math operators.

The if else statement is a type of control structure. A control structure is a instruction, statement or group of statements which determines the sequence of execution of other statements. The basic operation of if else statement is that a statement or group of statements is executed under if, if the value of expression is true and if the expression is false, statements under else are evaluated. In C++ language, zero is false everything else is true. Statement associated either with if or else are executed not both group of statements are executed. The else clause is optional. The general form of if else statement is:-

if (expression)
{
statement;
}
else
{
            statement;
}

Or

if (expression)
{
statement;
}

The curly braces mark the beginning and the end statements under if and else.
Here is a program which illustrates the functioning of if else statement.




The result of the program is:-



The statement

if (c>=10)

checks whether the value of variable c is less than or equal to 10. The expression evaluates to be true and as a result statement

cout << “Number is less then equal to 10”

is executedThe statement

cout << “Number is greater then 10”

under else is not executed as value of the variable c is not greater than 10.

The position of semicolon is after the first statement following if and the expression. There is no semicolon after the expression in parentheses as if and expression are bounded to the statement or group of statements following the expression.  Here is the program which illustrates the working of statements under else.




The result of the program is:-



The statement

if (c>=10)

now evaluates to be false because the value of variable c is 15.  The statement under if is not executed. The statement

cout << “Number is greater then 10”

under else is executed as the expression evaluates to be false. 


The statement that is executed either after if or else can be itself be an if statement.  This arrangement is called nested if. In the nested if, the else statement is always associated with the nearest if statement within the same block. Here is a program which illustrates the working of nested ifs.


The result of the program is: -


The value of the variable c is 6. The statement

if (c<=10)

evaluates to be true. Then the statement

if (c<=5)

evaluates to be false and hence the statement

cout << “Number is greater than 5 and less than equal to 10”

under else in executed. It shows that else statement is associated with inner if statement.  Here is a program which makes things more clear.


The result of the program is: -



Now the value of the variable c is 12. The statement

if (c<=10)

evaluates to be false and hence the statement under else is executed. The statement

cout << “Number is greater than 10”

is executed as value of c is greater than 10. Now the else statement is associated with the outer if as else statement is outside the inner block.

After an introduction of if/else statements, let us move on to discuss switch statements.

-------------------------------------------------------------------------------------------------------------------------------------
  Loops

Before reading this tutorial, you should have knowledge of switch statements.

Loops are iteration statements. Loop provides a mechanism to execute same sequence of instructions repeatedly until a condition is reached. There are two elements of the loop: the body of loop which is to be executed number of times and a loop condition which terminates the loop when a particular condition is met.  The three different kinds of a loop are: -

  • The for loop
  • The while loop
  • The do while loop

The for loop

The for loop is used to execute same sequence of statements for the predetermined number of times. The general form of the for loop is: -

for(initialization; condition; iteration_expression)
{
statement;
}

The initialization is used to initialize the control variable of the loop. The initialization is executed once at the beginning of the loop. The condition is checked at the beginning of every iteration and if the condition is false then the loop is terminated. The iteration_expression is executed at the end of each loop iteration. It modifies the control variables of the loop initialized in the beginning.  Here is a program which illustrates the working of the for loop.


The result of the program is: -



The program is used to calculate the sum of first 10 numbers using a loop. There are 10 iterations of the loop. The variable c is initialized to zero. In the statement

            for (int i=1; i<=10; i++)

i=1; is the initialization expression which sets the value of control variable to be 1. The condition is
                        i<=10;

and at the beginning of each iteration  this condition is checked whether the value of variable i exceeds value 10 . The iteration_expression is

            i++;

and at the end of each iteration the value if variable i  is incremented by 1.  In the body of the loop the statement

            cout << i << endl;

prints the value of  i for every iteration and the statement

            c=c+i;

computes the sum of the values of the variable i. At the last iteration the value of the variable i becomes 11 when statement i++; is executed and then the condition i<=10; is checked and now the condition is false and as a result the loop is terminated. The control of the program is transferred to the statement following the for loop. The statement

            cout << “The sum is” << c << endl;

is executed and which prints the sum as 55.  

In the for loop, the body of the loop is never executed if the condition is false at the beginning of the first iteration. There are many variations of the for loop. User can use comma operator to declare two or more variables to control the loop. For example,

            for(int i=0 , int j=0; i+j<=10; i++)
                        j++;

variables i and j are controlling the loop. The statement int i=0, int j=0; are initialization statements.

The Infinite loop

The for loop can be used to create infinite loop. The infinite loop can be made by leaving the conditional expression empty. Here is the program of  the infinite loop .


The statement
            cout << “infinite loop” << endl;

is executed infinite times as there is no condition expression in the for statement. The infinite loop can be broken using an if and break statement. Here is the program which shows how to discontinue the infinite loop.







The result of the program is:-


In each iteration the user is allowed to enter a character by using the statement

                        cin >> c;
The statement
                        If(c==’A’)
checks whether the character entered is A. If the character is ‘A’ the loop terminates with the help of statement
                       
                        break;

If the character is not ‘A’ loop continues.  The loop will continue as long as user does not enter character ‘A’.

The While Loop

The while loop uses a condition to control the execution of the body of the loop. The general form the while loop is: -
            while(condition)
            {
                   statement;
            }
The condition is an expression which is executed at the beginning of each iteration. If the condition is true then the body of the loop is executed and if it is false loop is terminated and control is transferred to the statement following the while loop. The condition evaluates to a type bool, or to a value of an integer type. If the condition produces the integer, the loop will execute as long as integer is non zero. Non zero integer is converted to type bool as true and if the value of integer is zero it is taken as false. Here is the program which illustrates the working of while loop.


The result of the program is: -


In the program value of the variable i is incremented by 1 in each iteration. The condition

                                    i<10
checks whether the value of i is less than 10 in every iteration. In every iteration of the loop value of i is incremented by 1 by the statement

                                    i=i+1;
In the last iteration the value of i becomes 10. Then the condition is checked and it returns false, loop is terminated and control is transferred to the statement

                                    return(0);
-------------------------------------------------------------------------------------------------------------------------------------
The do while loop

The do while loop works same as the while loop and the loop is iterated as long as condition remains true. The do while loop checks the condition at the bottom of the loop while for and while loop checks the condition at the beginning of the loop and as a result the body of the loop is executed at least once. The general form of the do while loop is: -

do{
   statement;
} while(condition);

The body of the loop is executed until the condition becomes false. Here is a program which illustrates the working of the do while loop.


The result of the program is: -


In the program the condition is checked at the end of the loop by the statement

            while(str==’y’);
The body of the loop is iterated once without checking the given condition. The statements
                        cout << “Enter the number you want to add” << endl;
                        cin >>i;
allow the user to enter the number to be added. Then the statements
                       
                        cout << “Do you want to enter the number y/n” << endl;
                        cin >> str;
ask the user whether he or she wants to add another number. If the user enters ‘y’ then the condition is true and the loop is executed once more. If the user enters any character other than ‘y’ then the condition is false and loop is terminated.

After an introduction of loops, let us move on to discuss arrays.
-------------------------------------------------------------------------------------------------------------------------------------
       Switch Statement

Before reading this tutorial, you should have knowledge of if else statements.

The switch statement is a type of control structure. The general form of a switch statement is

switch (expression)
           
     case constant 1 :
             statement sequence
             break;
       
    case constant 2 :
            statement sequence
            break;
     .
     .
     default:
              statement sequence
            

The switch statement allows doing multiple selections depending upon the value of expression.  It tests the value of the expression against the integer or character constants. The value of the expression must be integer or character. The value of the expression is tested against the constants in the case statements. When a correct match is found sequence of statements associated with the constant is executed until the break statement or the end of the switch statement is reached. If no match is found then sequence of statements associated with default is executed. The case values appear in case labels. No two or more case labels can contain same constant values. The case values can occur in any sequence. Here is a program which illustrates the working of switch statement.


The result of the program is: -


The user has entered the number 3 corresponding to the statement

            cin >> c;

The value of variable c is now 3. The switch statement
           
            switch(c)

is now executed. The value of the variable c is matched against the constants in the case statements.  The value matches with the constant 3 in the case label and as a result the statement
            cout << “ You have chosen cookies” << endl;

is executed.  The statement

break ;

switches the control to the statement following the switch which is the statement

            return(0);

If the user has entered value other than the constants in the case labels then the statement associated with the default would have been executed. Here is the result of the same program which shows the execution of default statement.



Now the user has entered the value 7.  The value of variable c is 7. The value 7 does not
match with any of the constants in the case labels and as a result statement

            cout << “ You have not chosen any item” <<  endl;

is executed.   

The break statement is necessary as it switches the control to the statement following the switch statement after executing sequence of statements associated with case value. If the break statement is omitted then the sequence of statements for all the following cases are executed till a break statement is encountered or end of the switch is reached.  Here is a program which shows how the statements are executed when there is no break statement.


The result of the program is: -


The user has entered value 1. The value of the variable c is 1. The switch statement is executed. The value of the variable c is matched against the constants in the case labels. It matches with the value of the first case statement. As there is no break statement the execution is transferred to the statement

            case (2) :

As there is no break statement associated with this case statement also the control is transferred to the third case statement

            case (3) :

The next statement
           
            cout << “ You have chosen one of the first 3 items” <<  endl;

is executed. Then the statement

            break;

is executed and control is transferred to the statement following the switch statement. Omitting the break statement can be helpful when sequence of statements for two or more case statements is same. For example, in this program statement

cout << You have chosen one of the first 3 items “ <<

is same for first 3 case statements. Instead of typing the same statement along with every case label you can ignore the break statement with the case statements and insert the break statement where termination is necessary. It avoids unnecessary duplication of sequence of statements.

The statement switch can be used instead of if statement. Instead of using ifs statements for checking the expression against two or more constant values, switch should be used. Here is a program which performs the same function but uses ifs statements.


The task of writing nested ifs is tedious and switch should be used.

After an introduction of switch statements, let us move on to discuss loop statements.
--------------------------------------------------------------------------------------------------------------------------------------
 Functions

Before reading this tutorial you should have knowledge of pointers.

Functions are building blocks of the programs. They make the programs more modular and easy to read and manage. All C++ programs must contain the function main( ). The execution of the program starts from the function main( ). A C++ program can contain any number of functions according to the needs. The general form of the function is: -

return_type  function_name(parameter list)
{
            body of the function

}

The function of consists of two parts function header and function body. The function header is:-

            return_type   function_name(parameter list)

The return_type specifies the type of the data the function returns. The return_type can be void which means function does not return any data type. The function_name is the name of the function. The name of the function should begin with the alphabet or underscore. The parameter list consists of variables separated with comma along with their data types. The parameter list could be empty which means the function do not contain any parameters. The parameter list should contain both data type and name of the variable. For example,

            int factorial(int n, float j)

is the function header of the function factorial. The return type is of integer which means function should return data of type integer. The parameter list contains two variables n and j of type integer and float respectively. The body of the function performs the computations.



Function Declaration

A function declaration is made by declaring the return type of the function, name of the function and the data types of the parameters of the function.  A function declaration is same as the declaration of the variable. The function declaration is always terminated by the semicolon. A call to the function cannot be made unless it is declared. The general form of the declaration is:-

return_type function_name(parameter list);

For example function declaration can be
            int factorial(int n1,float j1);

The variables name need not be same as the variables of parameter list of the function. Another method can be
           
int factorial(int , float);

The variables in the function declaration can be optional but data types are necessary.

Function Arguments

The information is transferred to the function by the means of arguments when a call to a function is made.  Arguments contain the actual value which is to be passed to the function when it is called.  The sequence of the arguments in the call of the function should be same as the sequence of the parameters in the parameter list of the declaration of the function. The data types of the arguments should correspond with the data types of the parameters. When a function call is made arguments replace the parameters of the function.

The Return Statement and Return values

A return statement is used to exit from the function where it is. It returns the execution of the program to the point where the function call was made. It returns a value to the calling code. The general form of the return statement is:-

return expression;

The expression evaluates to a value which has type same as the return type specified in the function declaration. For example the statement,

            return(n);

is the return statement of the factorial function. The type of variable n should be integer as specified in the declaration of the factorial function. If a function has return type as void then return statement does not contain any expression. It is written as:-

            return; 

The function with return type as void can ignore the return statement. The closing braces at the end indicate the exit of the function. Here is a program which illustrates the working of functions.

#include<iostream>
using namespace std;
int factorial(int n);

int main ()
{
            int n1,fact;
            cout <<"Enter the number whose factorial has to be calculated" <<  endl;
            cin >> n1;
            fact=factorial(n1);
            cout << "The factorial of " << n1 << "  is : " << fact << endl;
            return(0);
           
}
int factorial(int n)
{
            int i=0,fact=1;
            if(n<=1)
            {
                        return(1);
            }
            else
            {
                        for(i=1;i<=n;i++)
                        {
                                    fact=fact*i;
                        }
                        return(fact);
            }
}

The result of the program is:-


The function factorial calculates the factorial of the number entered by the user. If the number is less than or equal to 1 then function returns 1 else it returns the factorial of the number. The statement

            int factorial(int n);

is a declaration of the function. The return type is of integer. The parameter list consists of one data type which is integer. The statement

            cout <<"Enter the number whose factorial has to be calculated" <<  endl;
            cin >> n1;
makes the user enter the number whose factorial is to be calculated. The variable n1 stores the number entered by the user. The user has entered number 5. The statement
           
            fact=factorial(n1);

makes a call to the function. The variable n1 is now argument to the function factorial. The argument is mapped to the parameters in the parameter list of the function. The function header is
           
            int factorial(int n)

The body of the function contains two return statements. If the value entered by the user is less than and equal to 1 then value 1 is returned else computed factorial is returned. The type of the expression returned is integer.

Parameter passing mechanism

There are two parameter passing mechanisms for passing arguments to functions such as pass by value and pass by reference.

Pass by value

In pass be value mechanism copies of the arguments are created and which are stored in the temporary locations of the memory. The parameters are mapped to the copies of the arguments created. The changes made to the parameter do not affect the arguments. Pass by value mechanism provides security to the calling program. Here is a program which illustrates the working of pass by value mechanism.

#include<iostream>
using namespace std;
int add(int n);

int main()
{
            int number,result;
            number=5;
            cout << " The initial value of number : " << number << endl;
            result=add(number);
            cout << " The final value of number : " << number << endl;
            cout << " The result is : " << result << endl;
            return(0);
}

int add(int number)
{
            number=number+100;
            return(number);
}

The result of the program is:-


The value of the variable number before calling the function is 5. The function call is made and function adds 100 to the parameter number. When the function is returned the result contains the added value. The final value of the number remains same as 5. This shows that operation on parameter does not produce effect on arguments.

Pass by reference

Pass by reference is the second way of passing parameters to the function. The address of the argument is copied into the parameter. The changes made to the parameter affect the arguments.  The address of the argument is passed to the function and function modifies the values of the arguments in the calling function. Here is a program which illustrates the working of pass by reference mechanism.

#include<iostream>
using namespace std;
int add(int &number);

int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(&number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}

int add(int &p)
{
            *p=*p+100;
            return(*p);
}

The result of the program is:-

           

The address of the variable is passed to the function. The variable p points to the memory address of the variable number. The value is incremented by 100. It changes the actual contents of the variable number. The value of variable number before calling the function is 100 and after the function is returned the value of variable number is changed to 105.

           
           
After an introduction of functions, let us move on to discuss structures.
------------------------------------------------------------------------------------------------------------------------------------
 Arrays

Before reading this tutorial, you should have knowledge of loop statements.

An array is a collection of several data items of the same data type. It consists of several contiguous memory locations storing data. It removes the cumbersome task of defining separate variables for each data item. A single variable can be used to store one or more data items. For example, if you want to store ages of 10 students of a class, you can easily declare an array of integer type of size 10 instead of declaring 10 variables of integer type each storing age of a student. The general form of the single dimension array is:-

type variable_name[size];

The type is the base type of the array and which is the type of each of the element of the array. The size is the no of the elements in the array. The variable_name is the name of the identifier holding the array. For example,

int age [10];

The age is an array of type integer whose size is 10. It can hold 10 data values. The specific element in the array  can be accessed using an index. An index is the offset from the first element of the array. For example, first element has an index of 0 while the third element has an index of 2. The integer age has elements from age[0] to age[9]. Here is a program which illustrates the working of arrays.
#include<iostream>
using namespacestd

#include<iostream>
using namespace std;
int main ()
{
           int age[10];
           int i,sum=0, avg=0;
           int max=0,min=100;
            for(i=0;i<10;i++)
            {
                       cout << "Enter the age of the student  " << i+1 <<endl;
                       cin >> age[i];
             }
            for(i=0;i<10;i++)
            {
                        sum=sum+age[i];
                        if(age[i]>max)
                        {
                                    max=age[i];
                        }
                        if(age[i]<min)
                        {
                                    min=age[i];
                        }
            }
            avg=sum/10;
            cout << "Average age of the students of the class : " << avg << endl;
            cout << "Maximum age of the student of the class : " << max << endl;
            cout << "Minimum age of the student of the class : " << min << endl;
            return(0);
}

The result of the program is:-


In the program the array is declared by the statement

            int age[10];

age is the identifier of the array which is of type integer and whose size is 10. In the for loop user is asked to enter the age of the student, the age is stored in the element of the array by the statement
                       
            cin >> age[i];

here i is the index of the array. The index starts from 0.  In the next for loop, average age, minimum age and maximum age of the students is calculated. Each element is accessed by index i. The sum of the elements of the array is calculated by the statement
            sum=sum+age[i];

age[i] is the (i+1)th element of the array. The maximum age is calculated by the if statement
                        if(max>age[i])
                        {
                                    max=age[i];
                        }
The minimum age is calculated by the another if statement
                       
                        if(min<age[i])
                        {
                                    min=age[i];      
                        }
The average is calculated by the statement

                        avg=sum/10;

The total no bytes used to store an array is equal to
                        Total bytes=size of(base type)×size of array.

Initializing Arrays

The arrays can be initialized by giving the initial values in a list and enclosed in curly brackets, which is placed after the equal sign which is put after the declaration of the array. For example,
           
            int age[5]={12,13,10,24,15};

elements of the array have values 12, 13, 10, 24, 15. The elements age[0] has value 12 and age[4] will have 15.  If the elements of the array are not initialized then they take some garbage value before they are assigned to some specified value. There is also another way of initializing all the elements of the array to be zero. For example,

            int age[5]={0};

will initialize all the elements of the array age to be zero. If you want some of the elements to be initialized with specific value and rest of the values to be zero then here is an example.
                       
            int age[5]={12,13};

The elements age[0] and age[1] will be initialized to 12 and 13 respectively and rest of the elements will be initialized to zero.


Null Terminated Strings

The most common use of one dimensional array is for character strings.  The null terminated string is a character array with a null character at the end. The characters form the string with a null character indicating the termination of the string. A null terminated string can be declared as

            char name[10];

it will hold 10 characters with a null at the end. The size of the array can be more than the length of the array. The array can be initialized as

            char name[10]={'j','e','s','u','s'};

The first 5 elements are initialized and rest elements are null characters. Here is a program which calculates the length of the string.

#include<iostream>
using namespace std;

int main()
{
            char name[15];
            int i=0;
            cout << " Enter your name " << endl;
            cin >> name;
            while(name[i]!='\0')
            {
                        i++;
            }
            cout << "Lenght of the name is : " << i << endl;
            return(0);
}

The result of the program is


The character array is declared by the statement

            char name[15];

The length of the name can be at most 15.  The arrays is assigned by taking the input from the user by the statements
                       
            cout << " Enter your name " << endl;
            cin >> name

Variable name is assigned the string entered by the user.  Each element of the array is referenced and checked whether it is null or not by the statement
                       
while(name[i]!='\0')

Until a null character is not encountered variable i is incremented by the statement
           
i++;

When a null character is encountered while loop is terminated and length is printed by the statement

            cout << "Length of the name is : " << i << endl;


Multidimensional Arrays

The multidimensional arrays are arrays of arrays. The general form of a multidimensional array is: -
            type variable_name[Size1][Size2]..[Size n];

The two dimensional array can be declared as

            int age[2][5];

this array has two rows and 5 columns. The three dimensional array can be declared as

            int age[2][3][5];

When an element of the array of n dimensional is referenced it uses n index values. For example first element of a two dimensional array declared above is referred as age[0][0] as the index starts from zero and last element is referred as age[1][4]. Here is a program which calculates the average of the elements of the row of the two dimensional array.

#include<iostream>
using namespace std;

int main ()
{
            int age[2][5]= { {12,13,14,15,15}, { 12,16,17,13,12}};
            int i,j;
            int sum=0,avg=0;
            for(i=0;i<2;i++)
            {
                        for(j=0;j<5;j++)
                        {
                                    sum=sum+age[i][j];
                        }
                        avg=sum/5;
                        cout << "Average of the elements of the row " << i+1  << " is " << avg << endl;
                        sum=0;
            }
            return(0);
}

The result of the program is: -


The program initializes and declares the two dimensional array by the statement

            int age[2][5]= { {12,13,14,15,15}, { 12,16,17,13,12}};

Elements of the first row and second row are initialized as {12,13,14,15,15} and
{ 12,16,17,13,12}  respectively. The elements are accessed using the statement as

            sum=sum+age[i][j];

age[i][j] refers to the element of row i and column j. This statement calculates the sum of the elements of the row.  After the sum of the elements of a row is calculated then average is calculated by the statement.
           
avg=sum/5;

sum is again initialized to zero. Then again the same process repeats for the second row.

After an introduction of arrays, let us move on to discuss pointers.
-------------------------------------------------------------------------------------------------------------------------------------
   Pointers

Before reading this tutorial, you should have knowledge of arrays.

A pointer is a variable that is used to store a memory address. The address is the location of the variable in the memory. Pointers help in allocating memory dynamically. Pointers improve execution time and saves space.  Pointer points to a particular data type. The general form of declaring pointer is:-

            type *variable_name;

type is the base type of the pointer and variable_name is the name of the variable of the pointer. For example,

            int *x;

x is the variable name and it is the pointer of type integer.  

Pointer Operators

There are two important pointer operators such as ‘*’ and ‘&’. The ‘&’ is a unary operator. The unary operator returns the address of the memory where a variable is located.  For example,

            int x*;
            int c;
            x=&c;

variable x is the pointer of the type integer and it points to location of the variable c. When the statement
                       
                        x=&c;

is executed, ‘&’ operator returns the memory address of the variable c and as a result x will point to the memory location of variable c.

The ‘*’ operator is called the indirection operator. It returns the contents of the memory location pointed to.  The indirection operator is also called deference operator. For example,

            int x*;
            int c=100;
            int p;
x=&c;
            p=*x;

variable x is the pointer of integer type. It points to the address of the location of the variable c. The pointer x will contain the contents of the memory location of variable c. It will contain value 100. When statement
                       
p=*x;

is executed, ‘*’ operator returns the content of the pointer x and variable p will contain value 100 as the pointer x contain value 100 at its memory location.  Here is a program which illustrates the working of pointers.

#include<iostream>
using namespace std;

int main ()
{
            int *x;
            int c=200;
            int p;
            x=&c;
            p=*x;
            cout << " The address of the memory location of x : " << x << endl;
            cout << " The contents of the pointer x : " << *x << endl;
            cout << " The contents of the variable p : " << p << endl;
            return(0);
}

The result of the program is:-


In the program variable x is the pointer of integer type. The statement

            x=&c;

points variable x to the memory location of variable c. The statement

            p=*x;

makes the contents of the variable p same as the contents of the variable c as x is pointing to the memory location of c.  The statement

          cout << " The address of the memory location of x : " << x << endl;

prints the memory address of variable x which it is pointing to. It prints the hexadecimal address 0012FF78. This address will be different when the program is run on different computers. The statement

             cout << " The contents of the pointer x : " << *x << endl;

prints the contents of memory location of the variable x which it is pointing to. The contents are same as the variable c which has value 200.  The statement

            cout << " The contents of the variable p : " << p << endl;

has the same output 200 as the statement above. The contents of variable p is same as the contents of the pointer x.

Pointer Arithmetic

There are only two arithmetic operations that can be performed on pointers such as addition and subtraction. The integer value can be added or subtracted from the pointer. The result of addition and subtraction is an address. The difference of the two memory addresses results an integer and not the memory address. When a pointer is incremented it points to the memory location of the next element of its base type and when it is decremented it points to the memory location of the previous element of the same base type. For example,

            int *x;
            int *p;
            p=x++;

here x and p are pointers of integer type. Pointer x is incremented by 1. Now variable p points to the memory location next to the memory location of the pointer x. Suppose memory address of x is 2000 and as a result p will contain memory address 2004 because integer type takes four bytes so the memory address is incremented by 4. Incrementing the pointer results in incrementing the memory address by the number of bytes occupied by the base type. For example,

      double *x;
      double *p;
      p=x++;

variables x and p are pointers of double type. Pointer x is incremented by 1. Now if the memory address of x was 2000 and after incrementing p will contain memory address 2008 as double takes 8 bytes. Decrementing the pointer results in decrementing the memory address by the number of bytes occupied by the base type. You cannot add two pointers. No multiplication and division can be performed on pointers. Here is a program which illustrates the working of pointer arithmetic.

#include<iostream>
using namespace std;

int main ()
{
            int *x;
            int *p,*q;
            int c=100,a;
            x=&c;
            p=x+2;
            q=x-2;
            a=p-q;
            cout << "The address of x : " << x << endl;
            cout << "The address of p after incrementing x by 2 : " << p << endl;
            cout << "The address of q after derementing  x by 2 : " << q << endl;
            cout << " The no of elements between p and q :" << a << endl;
            return(0);
}

The result of the program is:-


In the program x, p and q are pointers of integer type. The statement

            p=x+2;

makes p to point to the memory address which is next two memory locations apart from the location of x.  The statement

          q=x-2;

makes q to point to memory address which is previous two memory locations apart from the location of x. The statement

            a=p-q;

computes the no of memory locations between p and q will come out to be 4. The statement
           
cout << "The address of x : " << x << endl;

prints the address of the memory location of x which is 0012FF70. The statement

            cout << "The address of p after incrementing x by 2 : " << p << endl;

prints the memory address of p which comes out to be 0012FF78. Each memory location occupies 4 bytes. Therefore after incrementing by 2, memory address is incremented by 8. The statement

            cout << "The address of q after decrementing  x by 2 : " << q << endl;

prints the memory address of q which is 0012FF68. After decrementing, the memory address is decremented by 8. The statement

            cout << " The no of elements between p and q :" << a << endl;

prints the no of memory locations between p and q which comes out to be 4 as p points to next two memory locations of x and q points to the previous two memory locations of x.

Pointers and Arrays

The pointers and arrays have a very close relationship. The pointer can be set to the address of the first element of the array. For example,

            int age[];
            int *p;
            p=&age;
p will point to the address of the first element of the array. For example

            (p+4)

will point to the fifth element of the array.  Pointers are helpful where size of the array is unknown. Declaring the array with a size of large value wastes lot of space. Pointers improve the execution time. Here is a program which illustrates the working of arrays and pointers.

#include<iostream>
using namespace std;

int main()
{
            int age[5];
            int *p;
            int sum=0,i;
            char yes='y';
            p=age;
            for(i=0;i<5;i++)
            {
                        cout << "Enter the age of a student" << endl;
                        cin >> *p;
                        sum=sum+*p;
                        p++;
            }
            p=age;
            cout << "The sum of the ages" << sum << endl;\
            cout << "The age of the last student is : " << *(p + 4) << endl;
            return(0);
}

The result of the program is:-


The array age is of integer type. The pointer p points to the first element of the array.
           
            p=age;

The user is allowed to enter the age of the student. The statement

            cin >> *p;

stores the age of the person in contents of the array.  The pointer is incremented by one memory location so that next time age is stored in new memory location.

            p++;

sum of the ages is calculated. The pointer is again referred to the address of the first element of the array. The age of the last student cab be accessed using *(p+4) which contains the value of the 5thelement of the array.


After an introduction of arrays, let us move on to discuss functions.
-------------------------------------------------------------------------------------------------------------------------------------
 Structures

Before reading this tutorial you should have knowledge of functions.

A structure is a form of compound data type. It is an aggregate of data items of different data types. It acts as a cluster of variables of different data types. The variables that form the structure are called members. For example, you can have a structure of type employee which stores name, age, qualification, and telephone no and other information about the employee under one data type. A structure can be declared as:-

            struct Employee
            {
                        char name[50];
                        int age;
                        char quali[70];
                        int teleno;
                        char info[80];
            };

The keyword struct declares that Employee is a structure. The type name of the structure is Employee. The variables declared are the members of the structure Employee. Every variable of type Employee will contain members name, age, quali, teleno and info. The declaration of the structure is terminated by a semicolon. The data types of the members can be of any type except the type of the structure being defined. The amount of memory need to store a structure type is the total of the memory required by the data types of the members of the structure. The variables of the type Employee can be declared as follows:-

            struct Employee emp1;   or   Employee emp1;

The keyword struct is optional in C++. The variable emp1 is of type Employee. The variables of the structure can be declared along with declaration of the structure. For example,

            struct Employee
            {
                        char name[50];
                        int age;
                        char quali[70];
                        int teleno;
                        char info[80];
            }emp1,emp2;

The variables emp1 and emp2 are of type Employee. The members of the structure can be accessed using a dot operator. The general form for accessing the member of a structure is:-
            structure_name.member_name

The structure_name is the variable of type structure. The member_name is the name of the member of the structure. For example

                        emp1.age=20

The variable emp1 is of type Employee and age is the member of the structure Employee. Here is a program which illustrates the working of structures.

#include<iostream>
using namespace std;
struct Employee
{
                        char name[50];
                        int age;
                        char quali[70];
                        int teleno;
                        char info[80];

}emp1;

int main ()
{
            Employee emp2;
            cout << "Enter the name of the employee" << endl;
            cin >> emp1.name;
            cout << endl << "Enter the age of the employee" << endl;
            cin >> emp1.age;
            cout << endl << "Enter the qualification of the employee" << endl;
            cin >> emp1.quali;
            cout << endl << "Enter the telephone no of the employee" << endl;
            cin >> emp1.teleno;
            cout << endl << "Enter other information about the employee" << endl;
            cin >> emp1.info;
            emp2=emp1;
            cout << endl << "The name of the employee : " << emp2.name << endl;
            cout << "The age of the employee : " << emp2.age << endl;
            return(0);
}


The result of the program is:-

           
The statement
           
            struct Employee
{
                        char name[50];
                        int age;
                        char quali[70];
                        int teleno;
                        char info[80];

}emp1;

declares a structure of type Employee. The members of employee are name, age, quali, teleno and info. The variable emp1 is of type Employee. The declaration ends with a semicolon.  The statement

            Employee emp2;

declares a variable emp2 of type employee. Members are accessed by using a dot operator. The statements

            cout << "Enter the name of the employee" << endl;
            cin >> emp1.name;

make the user to enter the name of the employee. The emp1.name stores the name of the employee. Similarly all the other information is entered by the user. The statement

            emp2=emp1;

assigns the information contained in emp1 of type Employee to emp2 of type Employee. Now emp2.name is same as emp1.name and similarly all the information of emp1 is same as emp2.

Arrays of Structures

An array of structures can be declared. For example, if we want to store information about 50 employees of the company then we can declare an array of structure of type Employee. For example,

            Employee emp[100];

declares array emp of type Employee. Each variable can be accessed using an index. The index begins with zero like other arrays. For example,
           
cout << "Name of the first employee" << emp[0].name << endl;

will display the name of the first employee. Similarly emp[0].age contains the age of the first employee.

Passing Structures to Functions

The structures and their members can be passed to functions. The structure and member can act as an argument for the function. Here is a program which shows how structures are passed to functions.

#include<iostream>
using namespace std;

struct Employee
{
                        char name[50];
                        int age;
                        char quali[70];
                        int teleno;
                        char info[80];

}emp1;

void display(Employee emp3,char name3[50], int age2);

int main()
{         
            cout << "Enter the name of the employee" << endl;
            cin >> emp1.name;
            cout << endl << "Enter the age of the employee" << endl;
            cin >> emp1.age;
            cout << endl << "Enter the qualification of the employee" << endl;
            cin >> emp1.quali;
            cout << endl << "Enter the telephone no of the employee" << endl;
            cin >> emp1.teleno;
            cout << endl << "Enter other information about the employee" << endl;
            cin >> emp1.info;
            display(emp1,emp1.name,emp1.age);
            return(0);
}

void display(Employee emp3, char name3[50],int age3)
{         
            cout << endl << "The name of the employee : " << name3 << endl;
            cout << "The age of the employee : " << age3 << endl;
cout << "The qualification of the employee : " << emp3.quali << endl;
            cout << "The telephone no of the employee : " << emp3.teleno << endl;
}
           
The result of the program is:-


The statement

            void display(Employee emp3,char name3[50], int age2);

declares a function whose parameter are emp3 of type Employee, name3 of char type and age2 of type integer. The statement

            display(emp1,emp1.name,emp1.age);


make a call to the function display. The arguments are emp1 of type Employee, emp1.name and emp1.age which are members of emp1. The arguments are mapped to the parameters of the function.  The information of emp1 is mapped to emp3. The members emp1.name and emp1.age are mapped to name3 and age3 respectively. The statements

            cout << endl << "The name of the employee : " << name3 << endl;
            cout << "The age of the employee : " << age3 << endl;
            cout << "The qualification of the employee : " << emp3.quali << endl;
            cout << "The telephone no of the employee : " << emp3.teleno << endl;

display the information of emp1.
           
Pointers and Structures

There can be pointers to structures. Pointers are used for structures for passing structures by reference and for creating linked lists. The structure pointers can be declared as follows:-
           
            Employee *emp1;

Now emp1 is a pointer to the type Employee. The members of the structure using a pointer are accessed using an arrow operator. The '->' is called an arrow operator which consists of minus sign followed by a greater than operator.  The members are accessed using arrow operator in the same way as they are accessed using a dot operator. Here is a program which illustrates the working of pointers and structures.

#include<iostream>
using namespace std;

struct Employee
{
                        char name[50];
                        int age;
                        char quali[70];
                        int teleno;
                        char info[80];

}emp1;

void display(Employee *emp3);

int main()
{
            cout << "Enter the name of the employee" << endl;
            cin >> emp1.name;
            cout << endl << "Enter the age of the employee" << endl;
            cin >> emp1.age;
            cout << endl << "Enter the qualification of the employee" << endl;
            cin >> emp1.quali;
            cout << endl << "Enter the telephone no of the employee" << endl;
            cin >> emp1.teleno;
            cout << endl << "Enter other information about the employee" << endl;
            cin >> emp1.info;
            display(&emp1);
            cout << endl << "The modified age of the Employee : " << emp1.age << endl;
            cout << " The modified telephone no of the Employee : " << emp1.teleno << endl;
            return(0);
}

void display(Employee *emp3)
{
            emp3->age=emp3->age+10;
            emp3->teleno=3299574;
}

The result of the program is:-


The statement

            void display(Employee *emp3);

declares a function whose parameter is a pointer of type Employee. The statement

            display(&emp1);

passes the address of emp1 to the function. In the function the statements

            emp3->age=emp3->age+10;
            emp3->teleno=3299574;

modify the values of the member age and telephone of emp3. The member age and teleno are accessed using an arrow operator. The age is incremented by 10 and telephone no is changed. The statements

            cout << endl << "The modified age of the Employee : " << emp1.age << endl;
            cout << " The modified telephone no of the Employee : " << emp1.teleno <<

print the modified age and telephone of the employee. The function alters the arguments passed as this pass by reference.



After an introduction of structures, let us move on to discuss standard library functions.
-------------------------------------------------------------------------------------------------------------------------------------
   C++ Character Functions

The C++ char functions are extremely useful for testing and transforming characters. These functions are widely used and accepted. In order to use character functions header file <cctype> is included into the program. Some of the commonly used character functions are:

  • isalnum()-  The function isalnum()  returns nonzero value if its argument is either an alphabet or integer. If the character is not an integer or alphabet then it returns zero.

  •  isalpha() - The function isalpha() returns nonzero if the character is an uppercase or lower case letter otherwise it returns zero.

  •  iscntrl() - The function iscntrl() returns nonzero if the character is a control character otherwise it returns zero.

  •  isdigit()- The function isdigit() returns nonzero if the character is a digit, i.e. through 0 to 9. It returns zero for non digit character.

  • isgraph()- The function isgraph() returns nonzero if the character is any printable character other than space otherwise it returns zero.

  • islower()- The function islower() returns nonzero for a lowercase letter otherwise it returns zero.

  • isprint()- The function isprint() returns nonzero for printable character including space otherwise it returns zero.

  • isspace()- The function isspace() returns nonzero for space, horizontal tabnewline character, vertical tab, formfeed, carriage return; otherwise it returns zero.

  • ispunct()- The function ispunct() returns nonzero for punctuation characters otherwise it returns zero. The punctuation character excludes alphabets, digits and space.

  • isupper() - The function isupper() returns nonzero for an uppercase letter otherwise it returns zero.

  • tolower()- The function tolower() changes the upper case letter to its equivalent lower case letter. The character other than upper case letter remains unchanged.

  • toupper()- The function toupper() changes the lower case letter to its equivalent upper case letter. The character other than lower case letter remains unchanged.

  • isxdigit() - The function isxdigit() returns nonzero for hexadecimal digit i.e. digit from 0 to 9, alphabet 'a' to 'f' or 'A' to 'F' otherwise it returns zero.

Here is a program which illustrates the working of character functions.

#include<iostream>
#include<cctype>
using namespace std;

int main ()
{
            char ch='a';
            char ch1='Z';
            char ch2=' ';
            char ch3='0';
            char ch4='?';
            char ch5='F';
            if(isalpha(ch))
            {
                        if(islower(ch))
                        {
                                    cout << "The character 'a' is an lower case letter." << endl;
                        }
            }
            if(isupper(ch5))
            {
                        if(isxdigit(ch5))
                        {
                                    cout << "The character 'F' is a upper case letter and hexadecimal digit" << endl;
                        }
            }
            if(isalnum(ch3))
            {
                        if(isdigit(ch3))
                        {
                                    cout << "The character '0' is an alphanumeric character and a digit" << endl;
                        }
            }
            if(isprint(ch2))
            {
                        if(isspace(ch2))
                        {
                                    if(isgraph(ch2))
                                    {
                                                cout << "The character is a graphic character" << endl;
                                    }
                                    else
                                    {
                                                cout << "The character " " is a printable character and space" << endl;
                                    }
                        }
            }
            if(ispunct(ch4))
            {
                        cout << "The character '?' is a punctuation character" << endl;
            }
            cout << "The uppercase letter of 'a' is : " << static_cast<char>(toupper(ch)) << endl;
            return(0);
}

The result of the program is:-

program output

The statement
           
            #include<cctype>
I
includes a header file <cctype> into the program. The statement

              if(isalpha(ch))

checks whether character ch is alphanumeric. It returns nonzero value as 'a' is alphanumeric. The statement

            if(islower(ch))

checks whether character ch is a lower case letter. It returns nonzero value as 'a' is lower case letter. The statement

            if(isupper(ch5))

checks whether character ch5 is a upper case letter. It returns nonzero value as 'F' is a upper case letter. The statement

            if(isxdigit(ch5))

checks whether character ch5 is a hexadecimal digit. It returns nonzero value as 'F' is a hexadecimal digit. The statement

            if(isalnum(ch3))

checks whether character ch3 is a alphanumeric character. It returns nonzero value as '0' is an alphanumeric character. The statement

            if(isdigit(ch3))

checks whether character ch3 is a digit. It returns nonzero value as '0' is digit. The statement

            if(isprint(ch2))

checks whether character ch2 is a printable character . It returns nonzero value as character ch2 ' '  is a printable character. The statement

            if(isspace(ch2))

checks whether character ch2 is a space character . It returns nonzero value as character ch2 ' '  is space. The statement

            if(isgraph(ch2))

checks whether character ch2 is a graphical character . It returns zero value as character ch2 is not a graphical character. The statement

            if(ispunct(ch4))

checks whether character ch4 is punctuation character. It returns nonzero value as character ch4 '?' is a question mark. The statement

            cout << "The uppercase letter of 'a' is : " << static_cast<char>(toupper(ch)) << endl;

displays the upper case equivalent of letter 'a'. The function toupper(ch) converts lower case letter to upper case letter and it returns integer value therefore type casting is used to convert integer type value to character type value. If type casting is not used then it will return the ASCII code of upper case letter.
-------------------------------------------------------------------------------------------------------------------------------------
   String Functions

The string functions can analyze and transform null terminated strings.  In order to manipulate null terminated strings header file <cstring> is included in the program. This header file provides the same functionality as string.h in C. Some of the commonly used string functions are: -

  • strcat(s1, s2) - It concatenates two strings. It concatenates s2 at the end of s1.
  • strcmp (s1, s2) – It is used to compare strings. It returns 0 if they are equal and less than 0 if s1<s2 and greater than 0 if s1>s2.
  • strlen(s1) – It returns the length of the string s1.
  • strcpy(s1, s2) - It copies s2 into s1.
  • strncat(s1, s2, n) -   It appends substring to the string. It takes first n characters of string s2 and appends s1.
  • strncmp(s1,s2,n) – It compares first n characters of string s1 with first n characters of string s2.
  • strchr(s1, ch) – Finds character ch in string s1.  It returns the pointer at the first occurrence of ch.
  • strstr(s1, s2) – Finds substring s2 in s1. It returns a pointer at the first occurrence of s1.

Here is a program which illustrates the working of string functions.

#include<iostream>
#include<cstring>
using namespace std;

int main ()
{
      int l;
      char name[40]=" Tom is a good boy";
      char name1[40]="Mary is a good girl";
      char stri[40];
      l=strlen(name);
      cout << "The lenght of the string 1 is : " << l <<  endl;
      if(strstr(name,"good"))
      {
                  cout << "Substring good appears in string 1 " << endl;
      }
      if(strchr(name1,'M'))
      {
                  cout << "Character M appears in sting 1 " <<  endl;
      }
      if(strcmp(name,name1)>0)
      {
                  cout << "String 2 appears after string" << endl;
      }
      strcpy(stri,name1);
      cout << "The copied string  : " << stri << endl;
      strncat(stri,name,4);
      cout << " The modified string : " << stri << endl;
      if(strncmp(stri,name1,3)==0)
      {
                  cout << "First 3 characters of two strings are equal" << endl;
      }
      strcat(name,"  ");
      strcat(name,name1);
      cout << name << endl;
      return(0);
     
}

The result of the program is:-

program output

The statement

#include<cstring>

includes a header file <cstring> into the program. The statement

       l=strlen(name);

computes the length of the string name. The function strlen(name)  returns the length of the string name. The length of the string is 18. The statement

      if(strstr(name,"good"))

checks whether substring “good” appears in the string name. The function strstr(name,”good”) returns true as “good” appears in string name. The statement
     
      if(strchr(name1,'M'))

checks whether character ‘M’ appears in string name1. The function strchr(name1,’M’) returns true as character ‘M’ appears in string name1. The statement

                        if(strcmp(name,name1)>0)

compares two strings name and name1. It returns false as string name< string name1.
The statement

      strcpy(stri,name1);

copies content of string name1 into string stri. The statement

            strncat(stri,name,4);

concatenates first 4 letters of string name to string stri. The statement

            if(strncmp(stri,name1,3)==0)
     
compares first  3 characters of string name1 with first 3 characters of string stri. It   returns true as first 3 characters of name1 and stri are same. The statement

      strcat(name,"  ");

concatenates whitespace at the end of the string name. The statement

            strcat(name,name1);

concatenates content of string name1 at the end of  string name.
-------------------------------------------------------------------------------------------------------------------------------------
   Math Functions

The mathematical functions provide the functionality of automatically computing some of the functions such as trigonometric functionshyperbolic functionsexponential and logarithmic functions and other miscellaneous functions. In order to use these functions header file <cmath> is included into the program. Some of the commonly used functions are:-

  • abs() – The function abs() returns the absolute value of integer parameter.

  • acos()  -The function acos() returns the arc cosine of the argument. The range of the argument is from -1 to 1. Any argument outside this range will result in error.

  • asin()- The function asin() returns the arc sine of the argument. The range of the argument is from -1 to 1. Any argument outside the range will result in error.

  • atan()- The function atan() returns the arc tangent of the argument.

  • atan2()- The function atan2()  returns the arc tangent of y/x. It accepts two arguments.

  • ceil()- The function ceil() returns the smallest integer which is not less than the argument.

  • cos() – The function cos() returns the cosine of the argument. The value of the argument must be in radians.

  • cosh() –The function cosh() returns the hyperbolic cosine of the argument.

  • exp()- The function exp() returns the exponential of the argument.

  • fabs()- The function fabs() returns the absolute value of floating point parameter.

  •  floor()- The function floor() returns the largest integer which is not greater than the argument.

  • fmod()- The function fmod() returns the remainder of floating point division of the two arguments.

  • log() – The function log() returns the natural logarithm of the argument. An error is encountered if the argument is negative or zero.

  • log10()- The function log10() returns base 10 logarithm of the argument. An error occurs if the argument is negative or zero.

  • pow()- The function pow() returns the base raised to the power.

  • sin()- The function sin() returns the sine of the argument. The value of the argument must be in radians.

  •  sinh()- The function sinh() returns hyperbolic sine of the argument.

  • sqrt()- The function sqrt() the square root of the argument. An error occurs if the value of the argument is negative.

  •   tan()- The function tan() returns the tangent of the argument. The value of the argument must be in radians.

  • tanh()- The function returns the hyperbolic tangent of the argument.

 Here is a program which illustrates the working of the math functions.

#include<iostream>
#include<cmath>
using namespace std;

int main()
{
      double a=-0.707;
      double a1=(45.0*3.14)/180;
      double a2=2;
      double b=0.0;
      b=acos(a);
      cout << "The arc cosine of " << a << ": " << b << endl;
      b=asin(a);
      cout << "The arc sin of" << a << ": " << b << endl;
      b=atan(a);
      cout << "The arc tangent of  " << a << " : " << b << endl;
      b=ceil(a);
      cout << "The ceiling of " << a << " : " << b << endl;
      cout << "The floor of  " << a << " : " << floor(a) << endl;
      cout << "The cosine of " << a1 << " : " << cos(a1) << endl;
      cout << "The exponential of " << a2 << " : " << exp(a1) << endl;
      cout << "The log of " << a2 << " : " << log(a2) << endl;
      cout << "The base " << a2 << " raised to the power " << b << " : "  << pow(a2,b) << endl;
      cout << "The square root of " << a2 << "  :  " << sqrt(a2) << endl;
      return(0);
}

     

The result of the program is:-

program output

The statement

      #include<cmath>

includes a header file <cmath> into the file. The statement

      b=acos(a);

returns the arc cosine of argument a. The arc cosine of -0.707 is 2.35604. The statement

            b=asin(a);

returns the arc sine of argument  a. The arc sin of a -0.707 is -0.785247. The statement

            b=atan(a);

returns the arc tangent of argument a. The arc tangent of -0.707 is -0.615409. The statement

       b=ceil(a);

returns the ceiling of argument a. The ceiling of -0.707 is 0. The statement

            cout << "The floor of  " << a << " : " << floor(a) << endl;

displays the floor of argument a. The floor of -0.707 is -1. The statement

             cout << "The cosine of " << a1 << " : " << cos(a1) << endl;

displays the cosine of the argument a1. The cosine of 45 degrees is 0.707. The argument a1 contains the radian value of 45 degrees. The statement

            cout << "The exponential of " << a2 << " : " << exp(a1) << endl;

displays the exponential of argument of a2. The exponential of 2 is 2.19241. The statement
           
      cout << "The log of " << a2 << " : " << log(a2) << endl;

displays the logarithm of argument a2. The logarithm of 2.0 is 0.69. The statement

            cout << "The base " << a2 << " raised to the power " << b << " : "  << pow(a2,b);

displays the base a2 raised to the argument b. The base 2.0 raised to the power 0 is 1. The statement

            cout << "The square root of " << a2 << "  :  " << sqrt(a2) << endl;

displays the square root of the argument a2. The square root of 2.0 is 1.414.
-------------------------------------------------------------------------------------------------------------------------------------
Random Function

There are functions which are used to generate pseudo random numbers. In order to use these function header file <cstdlib> is included into the program. There are mainly two random functions in C++ such as rand() and  srand().

  • rand () -  The function rand() generates the sequence of pseudo random numbers. It generates the random number between 0 and RAND_MAX.  RAND_MAX is a constant defined in header file <ctdlib>. A series of non related numbers are generated each time the function is called.

  • srand() - The function srand()  uses the seed parameter  to set the starting point for the sequence of random numbers generated by the function rand().The parameter seed is unsigned integer. It is used to generate different sequences of pseudo random numbers by specifying different seed each time when the program is run. If the seed is not changed then the same sequence will be generated as pervious sequence when the program is run.

Here is a program which illustrates the working of random functions.

#include<iostream>
#include<cstdlib>
using namespace std;

int main()
{
            int a,b,c,d;
            cout << "Enter the starting number" << endl;
            cin >> a;
            srand(a);
            b=rand()%RAND_MAX;
            c=rand()%200;
            d=rand()%10+200;
            cout << "The number between 0 and " << RAND_MAX  << " is : " << b << endl;
            cout << "The number between 0 and 10 is : " << c << endl;
            cout << "The number between 200 and 210 is : " << d  << endl;
            return(0);
}

The result of the program is:-

program output
The statement

            #include<cstdlib>
I
includes  a header file <cstdlib> into the program. The statement

            srand(a);

sets the starting point of the sequence of random numbers to the value of the variable a. The value entered by the user is 12. The statement

            b=rand()%RAND_MAX

returns the number between 0 and RAND_MAX. The statement

            c=rand()%200;

returns the random number between 0 and 200. The random number returned is 28. The statement

            d=rand()%10+200;

returns the random number between 200 and 210. The number returned is 202. The statement

            cout << "The number between 0 and " << RAND_MAX  << " is : " << b << endl;

displays the value of RAND_MAX and random number between 0 and RAND_MAX which is 77. . The value of RAND_MAX is 32767.
-------------------------------------------------------------------------------------------------------------------------------------
Date and Time Functions

There are several functions that deal with time and date.  In order to perform these functions header file <ctime> is included into the program. The header file defines time related types such as clock_t, time_t and structure tm. The clock_t and time_t represent system time and date in the form of integer. The structure tm has data and time broken into elements. Some of the functions are:-

  • asctime() - The function asctime() returns the pointer to the string containing the date and time in readable format.

  • clock() - The function clock() returns the no of ticks since the calling program has been running. In order to convert no of ticks into seconds divide it by macro CLOCKS_PER_SEC which is defines in the header file <ctime>.

  • ctime() - The function ctime() converts the value of time_t to string.

  • difftime()-The function difftime() returns the difference in seconds between two times. It takes two arguments.

  • gmtime() - The function gmtime() returns a pointer to the broken down form of the time which is in UTC(Coordinated Universal Time) format. It converts time_t to tm structure as UTC time. If the system does not support UTC a null value is returned.

  • localtime()- The function localtime() returns a pointer to the broken down form of time_t into the form of tm structure as local time.

  • mktime() - The function mktime() converts tm structure to time_t.

  • time() - The function time() returns the current time. The function can be called using a NULL pointer or pointer to a variable of type time_t.

Here is a program which illustrates the working of time and date functions.

 #include<iostream>
#include<ctime>
using namespace std;

int main()
{
            time_t time1;
            time_t start1,end1,start2;
            struct tm * currenttime;
            time(&start1);
            currenttime=localtime(&start1);
            time1=time(NULL);
            float a=(clock());
            time(&start2);
            cout << "The no of hours since January 1 2006 : " << (time1/3600) << endl;
            cout << "The current time : " << ctime(&time1) << endl;
            cout << "The date and time : " << asctime(currenttime) << endl;
            cout << "The no of ticks since the program has been called : " << (clock()) << endl;
            time(&end1);
            cout << "The time lapse between two times : " << difftime(end1,start2) << endl;
            return(0);
}

The result of the program is:-

program output

The statement

            #include<ctime>

includes a header file <ctime>  into the program. The statements

            time_t time1;
            time_t start1,end1,start2;

declares variables time1,start1,end1 and start2 of type time_2. The statement

            struct tm * currenttime;

declares a pointer to the variable currentime of type tm structure. The statement

            time(&start1);

returns the current time of the system. The statement

            currenttime=localtime(&start1);

returns the localtime of the start1 into the form of tm structure. The statement

            time1=time(NULL);

returns the current time of the system. The statement

            cout << "The no of hours since January 1 2006 : " << (time1/3600) << endl;

displays the no of hours since January 1. The time1 is divided no of seconds in an hour. The statement

            cout << "The current time : " << ctime(&time1) << endl;

displays the string format of the current time. The statement

            cout << "The date and time : " << asctime(currenttime) << endl;

displays the current time and date in readable format. The statement

            cout << "The no of ticks since the program has been called : " << (clock()) << endl;

prints the no of ticks since the program has been called. The statement

            cout << "The time lapse between two times : " << difftime(end1,start2) << endl;

prints the time difference between end1 and start2.
-------------------------------------------------------------------------------------------------------------------------------------
   OOP Features

Classes and objects and Methods and properties

A class is a user defined data type like a structure or a union. A class consists of data variables and functions. These variables and functions are called members of the class.  The variables are called data members and functions are called member functions. The member functions are also called methods. The data members are called properties of the class. An object is the instance of the class. An object is like a compound variable of the user defined type. It links both code and data. Within the object, members of the class can be public or private to the object. The declaration of a class is syntactically same as structure. The class is declared using keyword class. The general form of the declaration of the class is:-

class class_name
{
             
            access_specifier:
                        data functions
            access_specifier:
                        data functions

} object_list;

The object_list is optional. The object_list is used to declare objects of the class. The class_name is the name of the class.  The access_specifier can either public, private or protected. The members of the class by default are private to the class. If the access_specifier is private then members of the class are not accessible outside the class. If the access_specifier is public then members of the class can be accessed from outside the class. The protected access_specifier is needed at the time of inheritance. The members can be accessed using an object’s name, a dot operator and name of the member. Here is a program which shows how classes and objects are created.

#include<iostream>
using namespace std;

class cube
{
            public:
                        double side;
                        double volume()
                        {
                                    return(side*side*side);
                        }
};
                       
int main()
{
            double volume1=0;
            cube c1,c2;
            cout << "Enter the lenght of the cube" << endl;
            cin >> c1.side;
            cout << "The volume of the cube is : " << c1.volume() << endl;
            c2.side=c1.side +2;
            cout << "The volume of the second cube is : " << c2.volume() << endl;
            return(0);
}

The result of the program is:-

class

The program consists of a class cube which has data member side of type double and member function which calculates the volume of the cube. The statement

            class cube

declares a class cube. The statements

            public:
                        double side;
                        double volume()
                        {
                                    return(side*side*side);
                        }

declare that access_specifier is public for data member side and member function volume. These members can be accessed from the other parts of the program. The statement

            cube c1,c2;

declares two objects c1 and c2 of type cube. The statement

            cin >> c1.side;

access the data member of the cube. The member is accessed by specifying the name of the object as c1 then dot operator and then name of the variable side. The length entered by the user is stored in c1.side. In the statement

            cout << "The volume of the cube is : " << c1.volume() << endl;

c1.volume() calls the member function volume which returns the volume of the cube of side whose length is entered by the user. The statement

            c2.side=c1.side +2;

equates the side of object c2 to side of object c1 increased by 2.  The objects c2 and c1 are different. The statement

            cout << "The volume of the second cube is : " << c2.volume() << endl;

displays the volume of second object c2.

Constructor and Destructor

Constructors are used in order to initialize the objects. A constructor is a special kind of a function which is the member of the class. The name of the constructor is same as name of the class. A constructor is automatically called when object is created. A constructor does not have a return type.

A default constructor is a constructor with no parameters. If no constructor is defined by the user then compiler supplies the default constructor. Once the constructor is defined by the user then compiler does not supply default constructor and then user is responsible for defining default constructor. 

A destructor is the complement of the constructor. It is used to destroy the objects. The objects are destroyed in order to deallocate the memory occupied by them. The name of the destructor is same as the name of the constructor as is preceded by a tilt operator ‘~’. A destructor for objects is executed in the reverse order of the constructor functions.

Here is a program which shows how constructors and destructors are used.

#include<iostream>
using namespace std;

class cube
{
            public:
                        double side;
                        double volume()
                        {
                                    return(side*side*side);
                        }
                        cube(double side1)
                        {
                                    cout << "A constructor is called" << endl;
                                    side=side1;
                        }
                        cube()
                        {
                                    cout << "A default constructor is called " << endl;
                        }
                        ~cube()
                        {
                                    cout << "Destructing " << side << endl;
                        }
};
                       
int main()
{
            cube c1(2.34);
            cube c2;
            cout << "The side of the cube is: " << c1.side << endl;
            cout << "The volume of the first cube is : " << c1.volume() << endl;
            cout << "Enter the length of the second cube : " ;
            cin >> c2.side;
            cout << "The volume of second cube is : " << c2.volume() << endl;
            return(0);
}

The result of the program is:-

constructor

The statement
                       
            cube(double side1)
            {         
                                    cout << "A constructor is called" << endl;
                                    side=side1;
            }
declares the constructor of the class cube. The name of the constructor is same as the name of the class. There is no return type in the constructor. It will initialize the value of data member side. The statement

                       
cube()
                        {
                                    cout << "A default constructor is called " << endl;
                        }

declares a default constructor. The statement

                         ~cube()
                        {
                                    cout << "Destructing " << side << endl;
                        }

declares a destructor to deallocate the objects. The statement

            cube c1(2.34);

creates an object c1 of type cube. A constructor is automatically called and initializes the data member side with value 2.34. The statement

                        cube c2;

creates an object of type c2. When object c2 is created a default constructor is called and the message will be printed. The statements

            cout << "The side of the cube is: " << c1.side << endl;
            cout << "The volume of the first cube is : " << c1.volume() << endl;

displays the side and volume of the cube where side has value 2.34. The statement

            cin >> c2.side;

will set the value of the side of the object c2 as entered by the user. At the end of the program objects are deallocated in the reverse order in which constructors are called. First object c2 is deallocated whose side is 2.5 and then object c1 is deallocated whose side is 2.34.

Advantage of the classes:-

It provides protection to the data. The members of the class are by default private to the class while the members of the structure are public. OOP features allow programmer to easily handle complex problems and multi file projects. They help in modeling real world objects such as bank accounts and their related transactions.
------------------------------------------------------------------------------------------------------------------------------------
Encapsulation, private public. Sections

The packaging of data values and member functions within one object is called an encapsulation. For example an object of class cube contains data member as side of the cube and member function volume of the cube. It is also called data hiding which helps to maintain the integrity of the object. It saves the data from misuse and outside interference. The data cannot be accessed directly but access controls can be specified in order to obtain the information. The data or object can be made public or private depending on the needs. The data which is private is not accessible outside the scope of the object. When the data is public it can be accessed by the other parts of the program.

Here is a program which shows how private and public members are accessed. The program consists of a class rectangle which has two data members such as length and breadth and the member functions area() and len(). The private data member length cannot be accessed directly. It is accessed using a function len() which is public and which returns the private data member length.

#include<iostream>
using namespace std;

class rectangle
{
            private:
                        double length;

            public:
                        double breadth;
                        double area()
                        {
                                    return(length*breadth);
                        }
                        double len()
                        {
                                    return(length);
                        }
                        rectangle(double lenght1,double breadth1)
                        {
                                    length=lenght1;
                                    breadth=breadth1;
                        }
};

int main()
{
            rectangle r1(3.5,4.6);
            double a=r1.len();
            double b=r1.breadth;
            cout << "The lenght is : " << a <<  endl;
            cout << "The breadth is : " << b << endl;
            cout << "The area is : " << r1.area() << endl;
            return(0);
}

The result of the program is:-

encapsulation

The statement

            private:
                        double length;

declares that data member length of type double which has access specifier as private. It cannot be accessed directly. The statements

            public:
                        double breadth;
                        double area()
                        {
                                    return(length*breadth);
                        }
                        double len()
                        {
                                    return(length);
                        }
                       
declares that data member breadth and member functions len() and area() are public. The member function len() is used to return the data member length which cannot be accessed directly. The statement

            rectangle r1(3.5,4.6);

declares an object r1 of rectangle. The constructor initializes the length and breadth of the object as soon as it is created. The statement

            double a=r1.len();

returns the length of the object. The data member length cannot be accessed directly as it is declared private therefore member function len() is used to return the value of length. The statement double a=r1.length in main() function is invalid as data member length is inaccessible. The statement

            double b=r1.breadth;

equates the value of b to the value of breadth of object r1. The statement

            cout << "The area is : " << r1.area() << endl;

displays the area of the rectangle.
-------------------------------------------------------------------------------------------------------------------------------------
Inheritance, Samples of using inheritance

Inheritance is the property by which one object can inherit the properties of the other object. A general class can be inherited by the other classes.  A class that is inherited is called a base class. A class which is inheriting another class is called a derived class. When a class inherits another class, members of the base class become the members of the derived class. The general form of inheritance is:-

class derived_name : access_specifier base_name
{
};

The derived_name is the name of the derived class. The base_name is the name of the base class. The access_specifier can be private, public or protected. If the access_specifier is public then all public members of the base class become public members of the derived class and protected members of the base class become the protected members of the derived class. If the access_specifier is private then all public and protected members of the base class will become private members of the derived class. If the access_specifier is protected then the public and protected members of the base class become the protected members of the derived class. Whether access_specifier is public, private or protected, private members of the base class will not be accessed by the members of the derived class.

The access_specifier protected provides more flexibility in terms of inheritance. The private members of the base class cannot be accessed by the members of the derived class. The protected members of the base class remain private to their class but can be accessed and inherited by the derived class. The protected members of the base class will remain private to the other elements of the program.

A derived class can inherit one or more base classes. A constructor of the base is executed first and then the constructor of derived class is executed. A destructor of derived class is called before the destructor of base class. The arguments to the base class constructor can be passed as follows:-

            derived_constructor (argument list): base1 (arg_list)
                                                                       base2(arg_list1)

                                                                        baseN(arg_list)

The derived_constructor is the name of the derived class. The argument list is list of the data members of the derived class. The base1 is name of the base class. The arg_list is the list of the members of the base class. Here is a program which illustrates the features of inheritance.

#include<iostream>
using namespace std;

class shape
{

            private :
                        double length;
           
            protected:
                        double breadth;

            public :

                        double len()
                        {
                                    return(length);
                        }
            shape(double length1,double breadth1)
            {
                        length=length1;
                        breadth=breadth1;
            }
            //shape()           {          }
};

class shape1
{
            public:
                        double height;
           
            shape1(double height1)
            {
                        height=height1;
            }
            //shape1()         {          }
};

class cuboid : public shape, private shape1
{
            public:

                        cuboid(double length1,double breadth1,double height1):shape(length1,breadth1),shape1(height1)
                        {
                                    cout << " A constructor is called " << endl;
                        }
                       
                        double volume()
                        {
                                    return(height*breadth*len());
                        }
                        double bre()
                        {
                                    return(breadth);
                        }
                        double ht()
                        {
                                    return(height);
                        }
};

int main()
{
            cuboid c1(2.4,3.5,6.7);
            cout << "The length of the cuboid is : " << c1.len() << endl;
            cout << "The breadth of the cuboid is : " << c1.bre() << endl;
            cout << "The height of the cuboid is : " << c1.ht() << endl;
            cout << "The volume of the cuboid is : " << c1.volume() << endl;
            return(0);
}

The result of the program is:-

inheritance

The program has two base classes shape and shape1 and one derived class called cuboid which inherits shape as public and shape1 as private. The public and protected members of shape become pubic and protected members of derived class cuboid. The private members of shape remain private to the class shape. The members of shape1 class become the private members of the derived class cuboid.

The statement

            class cuboid : public shape, private shape1

states that class cuboid inherits class shape as public and class shape1 as private. The statement

            cuboid(double length1,double breadth1,double height1):shape(length1,breadth1),shape1(height1)
                        {
                                    cout << " A constructor is called " << endl;
                        }

declares the constructor of the class cuboid. When constructor of class cuboid is called first constructor of shape is executed and then constructor of shape1 is executed and after that the constructor of cuboid is executed.   The statements

            double volume()
                        {
                                    return(height*breadth*len());
                        }

calculate the volume of the cuboid. The class cuboid cannot access the private data member length of the shape class. It access the length by calling the function len() which returns the private data member length. The data member breadth becomes the protected member of the class cuboid. The height which is public member of shape1 class becomes the private member of the class cuboid as it inherits the shape 1 class as private. The statements

                        double bre()
                        {
                                    return(breadth);
                        }

returns the breadth of the cuboid as data member breadth cannot be accessed outside the class as it is protected member of cuboid. The statement

            double ht()
                        {
                                    return(height);
                        }

returns the height of the cuboid as data member height cannot be accessed outside the class as height is the private data member of the class cuboid. The statement

            cuboid c1(2.4,3.5,6.7);

creates an object c1 of type cuboid. The constructor is called to initialize the values of the cuboid. The constructor of shape is executed and then constructor of shape1 is executed and then finally constructor of cuboid is executed. The statement

            cout << "The length of the cuboid is : " << c1.len() << endl;

displays the length of the cuboid as c1.len() calls the len() function of class shape which is also the public member function of cuboid. The statement

            cout << "The breadth of the cuboid is : " << c1.bre() << endl;

displays the breadth of the cuboid. As the data member breadth cannot be accessed directly as it is protected member of the class cuboid so the function bre() returns the breadth of the cuboid. The statement
                       
            cout << "The height of the cuboid is : " << c1.ht() << endl;

displays the height of the cuboid. The data member height cannot be accessed directly as it is private member of class cuboid so it is accessed through the function ht() which returns height.
------------------------------------------------------------------------------------------------------------------------------------
Polymorphism and Virtual functions

Polymorphism is defined as one interface to control access to a general class of actions. There are two types of polymorphism one is compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is functions and operators overloading. Runtime time polymorphism is done using inheritance and virtual functions.

Function Overloading

Polymorphism means that functions assume different forms at different times. In case of compile time it is called function overloading. For example, a program can consist of two functions where one can perform integer addition and other can perform addition of floating point numbers but the name of the functions can be same such as add. The function add() is said to be overloaded. Two or more functions can have same name but their parameter list should be different either in terms of parameters or their data types. The functions which differ only in their return types cannot be overloaded. The compiler will select the right function depending on the type of parameters passed.  In cases of classes constructors could be overloaded as there can be both initialized and unintialized objects. Here is a program which illustrates the working of compile time function overloading and constructor overloading.

#include<iostream>
using namespace std;

class employee
{
            public:
                        int week;
                        int year;
                        double calculate(double salary)
                        {
                                    return(salary*week);
                        }
                        int calculate(int salary)
                        {
                                    return(salary*week*year);
                        }
                        employee(int week1)
                        {
                                    week=week1;
                        }
                        employee(int week1,int year1)
                        {
                                    week=week1;
                                    year=year1;
                        }
};


int main()
{
            int sal;
            double sal2;
            employee emp1(10);
            employee emp2(10,3);
            cout << "Enter the no years for first employee" << endl;
            cin >> emp1.year;
            cout << endl << "Enter the salary per week for first employee" << endl;
            cin >> sal;
            cout << "The total salary of first employee is : " << emp1.calculate(sal) << endl;
            cout << endl << "Enter the salary per week for second employee is : " << endl;
            cin >> sal2;
cout << "The total salary of second employee is for one year: " << emp2.calculate(sal2) << endl;
            return(0);
}
The result of the program is:-
polymorphism

In the program function calculate() and constructor of class employee are overloaded. The function calculate() is declared two times but with different parameter type and same with constructor employee which is also declared two times but with different parameter types. The following statements

                        double calculate(double salary)
                        {
                                    return(salary*week);
                        }
                        int calculate(int salary)
                        {
                                    return(salary*week*year);
                        }

declare functions with same name calculate but one has parameter type integer and other has parameter type double. The function calculate() is overloaded. The statements

                        employee(int week1)
                        {
                                    week=week1;
                        }          
                        employee(int week1,int year1)
                        {
                                    week=week1;
                                    year=year1;
                        }

declare two constructors of class employee where one constructor’s parameter list is different from other constructor’s parameter list. The constructor is overloaded. The statement

            employee emp1(10);

declares an object emp1 of type employee. When object is created first constructor is called since the argument list matches with parameter list of the constructor. The constructor initializes the data member week of the object emp1. The statement

            employee emp2(10,3);

declares an object emp2 of type employee. The second constructor is called since the argument list matches with the parameter list of the constructor. The constructor initializes the data members week and year of the object emp2. In the statement

            cout << "The total salary of first employee is : " << emp1.calculate(sal) << endl;

emp1.calculate(sal) calls the first function calculate as the data type of sal matches with the parameter of the function calculate. It displays the total salary which is salary*week*year. In the following statement

 cout << "The total salary of second employee is for one year: " << emp2.calculate(sal2) << endl;

emp2.calculate(sal2) calls the second function calculate as the data type of sal2 which is double matches with the data type of parameter of function calculate and hence second function is called. It displays the total salary which is salary*week.
           
Operator Overloading

In polymorphism operators can also be overloaded. Operators can be overloaded in order to perform special functions with respect to the class. With the help of operator overloading standard operations such as + , - , * , etc can be applied on the objects of the class. Operators are overloaded by creating operator functions. The keyword operator is used to define operator function. Operator overloading doesn’t allow creating new operators. The general form of operator function is:-

            return_type operator #(arg_list)
            {
            }

return_type is the data type of the value returned from the function. The arg_list is the list of the arguments to the function. The operator comes after the keyword operator. Instead of # there will be an operator. Here is a program to show operator overloading.

#include<iostream>
using namespace std;

class rectangle
{
            public:
                        int length;
                        int breadth;
           
                        rectangle(int length1,int breadth1)
                        {
                                    length=length1;
                                    breadth=breadth1;
                        }

                        int operator+(rectangle r1)
                        {
                                    return(r1.length+length);
                        }
};

int main ()
{
            rectangle r1(10,20);
            rectangle r2(40,60);
            int len;
            len=r1+r2;
            cout << "The total length of the two rectangles is : " << len << endl;
            return(0);
}

The result of the program is:-

operator overloading
           
The program consists of operator +  function  which is overloaded. The + operator is used to perform addition of the length of the objects. The statements

                        int operator+(rectangle r1)
                        {
                                    return(r1.length+length);
                        }

define the operator function whose return type is integer. The operator + is overloaded. The function is used to add the lengths of the two objects. The parameter list consists of one object of type rectangle. The operator()+ takes only one parameter as the operand on the left side of the operator + is passed implicitly to the function through the this operator.  The statement

            len=r1+r2;
calls the operator()+ function to calculate the length of the two objects. The return type is of integer. The variable len will contain the total of length of the objects.

Virtual Functions

A virtual function is a member function of the base class and which is redefined by the derived class. When a derived class inherits the class containing the virtual function, it has ability to redefine the virtual functions. A virtual function has a different functionality in the derived class. The virtual function within the base class provides the form of the interface to the function. Virtual function implements the philosophy of one interface and multiple methods. The virtual functions are resolved at the run time.  This is called dynamic binding. The functions which are not virtual are resolved at compile time which is called static binding. A virtual function is created using the keyword virtual which precedes the name of the function.

Virtual functions are accessed using a base class pointer. A pointer to the base class can be created. A base class pointer can contain the address of the derived object as the derived object contains the subset of base class object. Every derived class is also a base class. When a base class pointer contains the address of the derived class object, at runtime it is decided which version of virtual function is called depending on the type of object contained by the pointer. Here is a program which illustrates the working of virtual functions.

include<iostream>
using namespace std;

class shape
{
            public:
                        int side;
                       
                        virtual int volume()
                        {
                                    cout << endl <<"Virtual function of base class " << endl;
                                    return(0);
                        }
};

class cube: public shape
{
            public:

                        int volume()
                        {
                                    cout << endl << "Volume function of cube " << endl;
                                    return(side*side*side);
                        }
};

class cuboid:public shape
{
            public:
                        int breadth;
                        int height;
                        int volume()
                        {
                                    cout << endl << "Volume function of cuboid " << endl;
                                    return(side*breadth*height);
                        }
};

int main()
{
            shape *s,s1;
            cube c1;
            cuboid c2;
            cout << "Enter the side of the cube" << endl;
            cin >> c1.side;
            cout << endl << "Enter the side of the cuboid " << endl;
            cin >> c2.side;
            cout << endl << "Enter the breadth of the cuboid" << endl;
            cin >> c2.breadth;
            cout << endl << "Enter the height of the cuboid" << endl;
            cin >> c2.height;
            s=&s1;
            s->volume();
            s=&c1;
            cout << endl << "The volume of the cube " << s->volume() << endl;
            s=&c2;
            cout << endl << "The volume of the cuboid " << s->volume() << endl;
            return(0);
}

The result of the program is:-

virtual funcions

The program has base class shape and class cube and cuboid which inherits base class. The base class has virtual function volume. The statements

                        virtual int volume()
                        {
                                    cout << endl <<"Virtual function of base class " << endl;
                                    return(0);
                        }

define the member function volume() of base class. The function is virtual. The keyword virtual precedes the function return type. In the following statements

                        int volume()
                        {
                                    cout << endl << "Volume function of cube " << endl;
                                    return(side*side*side);
                        }

the derived class cube which inherits base class shape, redefines the function volume() which is virtual. In the following statements

                        int volume()
                        {
                                    cout << endl << "Volume function of cuboid " << endl;
                                    return(side*breadth*height);
                        }


the derived class cuboid which inherits the base class shape, redefines the function volume(). The statement

            shape *s,s1;

declares a pointer to the base class shape. The statement

            s=&s1;

pointer s contains the address of the base class object s1. The statement

            s->volume();

calls the function volume of the base class shape as the pointer contains the address of the base class object. The statement

            s=&c1;

pointer s now contains the address of the derived class object c1. The statement

             cout << endl << "The volume of the cube " << s->volume() << endl;

displays the volume of the cube as s->volume() calls the function volume of the derived class cube. The pointer s contains the address of the object of derived class cube. In the statement

            s=&c2;

pointer s now contains the address of the derived class object c2. The statement

            cout << endl << "The volume of the cuboid " << s->volume() << endl;

displays the volume of the cuboid as s->volume() calls the function volume of the derived class cuboid. The pointer s now contains the address of the object of derived class cuboid.

When a virtual function is not defined by the derived class, the version of the virtual function defined by the base class is called. When a derived class which contains the virtual function is inherited by another class, virtual function can be overloaded for the new derived class. This means that virtual function can be inherited.

A pure virtual function is a function which contains no definition in the base class. The general form of virtual function is:-

            virtual return_type function_name(para_list)=0;

The return_type is the type of the value returned. The function_name is the name of the function and para_list is the parameter list. 

Each derived class should contain the definition of virtual functions. If the derived class does not define virtual function then compiler will generate an error. A class which contains one or more pure virtual function is called abstract class. Objects of abstract class cannot be created as it does not contain definition of one or more functions. The pointers of abstract class can be created and the references to the abstract class can be made. Here is a same program which shows how pure virtual function is defined.

 #include<iostream>
using namespace std;

class shape
{
            public:
                        int side;
                        virtual int volume()=0;
                       
};

class cube: public shape
{
            public:

                        int volume()
                        {
                                    cout << endl << "Volume function of cube " << endl;
                                    return(side*side*side);
                        }
};

class cuboid:public shape
{
            public:
                        int breadth;
                        int height;
                        int volume()
                        {
                                    cout << endl << "Volume function of cuboid " << endl;
                                    return(side*breadth*height);
                        }
};

int main()
{
            shape *s;
            cube c1;
            cuboid c2;
            cout << "Enter the side of the cube" << endl;
            cin >> c1.side;
            cout << endl << "Enter the side of the cuboid " << endl;
            cin >> c2.side;
            cout << endl << "Enter the breadth of the cuboid" << endl;
            cin >> c2.breadth;
            cout << endl << "Enter the height of the cuboid" << endl;
            cin >> c2.height;
            s=&c1;
            cout << endl << "The volume of the cube " << s->volume() << endl;
            s=&c2;
            cout << endl << "The volume of the cuboid " << s->volume() << endl;
            return(0);
}
           
The result of the program is:-

virtual function 2

The statement

            virtual int volume()=0;

declares pure virtual function volume() which has no definition. The class shape is now abstract class and objects of type shape cannot be created.
---------------------------------------------------------------------------------------------------------------------------------

  cout

The cout is built in stream for standard output on the screen. It inserts the sequence of characters into the standard output stream. The cout is defined in the header file iostream within the std namespace. The header file iostream contains the definition of cout. The compiler will give error if header file is not included in the program if cout is used. The objects are written to cout using insertion operator. The insertion operator is <<. It is also called output operator. For example,

            cout << “All work and no play makes Jack a dull boy” << endl;

will display message “All work and no play makes Jack a dull boy” on the screen. Let us consider another example which displays the value of expression.

#include<iostream>
using namespace std;

int main()
{
            int x=5;
            int y=6;
            cout << "The addition of two numbers" << endl;
            cout << x+y << endl;
            return(0);
}

The result is:-

program output

The statement
           
            cout << "The addition of two numbers" << endl;

displays the message “The addition of two number” on the screen. The keyword endl is used so that next characters are displayed from new line. The statement

              cout << x+y << endl;

displays the addition of two numbers 5 and 6 and result 11 is displayed on the screen. The expression is evaluated and result is displayed on the screen.
------------------------------------------------------------------------------------------------------------------------------------
 ifstream

The ifstream is a file stream class used for file handling. To use ifstream header file fstream is used. It is used for reading input from the file. In order to read from a file an object of type ifstream is created. The general form of how object is created is:-

ifstream object_name(“filename”);

The object_name is the name of the object created. The filename is the name of the file. For example,

            ifstream  userstream(“file1.txt”);

The userstream is the name of the object and file1.txt is the name of the file. When the object is created file is automatically open. There is no need of explicitly opening the file. An error might occur while opening the file such as the file may not be found. The status of the file can be checked using ‘!’ operator along with ifstream object or using is_open() which returns true if file is open. The data can be read from the file using the insertion operator ‘>>’. The end of file can be checked using eof() function. It returns true when end of file is encountered. Here is a program which illustrates the working of ifstream.

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
            ifstream stream1("D:\\file1.txt");
            char a[80];
            if(!stream1)
            {
                        cout << "While opening a file an error is encountered" << endl;
            }
            else
            {
                        cout << "File is successfully opened" << endl;
            }
            while(!stream1.eof())
            {
                        stream1 >> a;
                        cout << a << endl;
            }
            return(0);
}

The result of the program is:

program output

The statement

            #include<fstream>

includes a header file fstream for using ifstream class. The statement

            ifstream stream1("D:\\file1.txt");

creates an object stream1 of type ifstream. The file is file1.txt which is located in D directory. During the creating of this object file is open. The statement
           
            if(!stream1)

checks whether an error is encountered while opening a file. If a file is successfully open then it returns true and prints the message “File is successfully opened”. The statement

             while(!stream1.eof())

checks the whether the end of file is encountered. The while loop is terminated when end of file comes. The statement

            stream1 >> a;

uses an insertion operator to read text from file stream. The string a will contain the text. 
-----------------------------------------------------------------------------------------------------------------------------------
 ofstream

The ofstream is a file stream class. It is used for handling files. The ofstream is used to write data to different files at different times. To use ofstream header file fstream is included.  The insertion operator used to write data to a file. In order to write to a file an object of type ofstream is created. The general form of how object is created is:

            ifstream object_name(“filename”);

The object_name is the name of the object created. The filename is the name of file to which data is to be written. The filename can contain the path where the file is stored. If no path is specified then current directory is considered. If the file does not exist then new file is created when object is created. The contents of the existing file are discarded when object is created. The file can be closed usingclose() function. Here is a program which illustrates the working of ofstream.

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
            char name[50];
            int age;
            ofstream outfile("D:\\outfile1.txt");
            cout << "Enter your name" << endl;
            cin >> name;
            outfile << name << endl;
            cout << "Enter your age" << endl;
            cin >> age;
            outfile << age << endl;
            outfile.close();
            return(0);
}

The result of the program is:-

program output



The statement

            #include<fstream>

includes a header file fstream in the program. The statement

            ofstream outfile("D:\\outfile1.txt");

creates an object outfile of type ofstream. The name of the file is outfile1.txt and its location is in D directory. The user enters his name and age. The statement
           
            outfile << name << endl;

writes the name of the user to the file. The statement

            outfile << age << endl;

writes the age of the user to the current file. 
-----------------------------------------------------------------------------------------------------------------------------------
   String

There are mainly two types of handling strings such as using null terminated character arrays and using object of type string. The main drawback of null terminated strings is that most of the C++ operators cannot be applied on them. In order to overcome this drawback standard string class is used. If a string class is used normal operations can be performed on them like any other data type. When null terminated character arrays are declared memory space is wasted because you define the length of the array more than actually it is used. The use of string class does not waste memory space. In order to use string class header file <string> is included in the program. The general form of how string object is created is:-

            string object_name;

The object_name is the name of the object. For example,

            string name;

name is the object of type string. The operators which can be applied on object of string type are:-

            Operator                                              Meaning

                =                                                      Assignment
                +                                                      Concatenation
                +=                                                    Concatenation Assignment
                ==                                                    Equality
                !=                                                     Inequality
                <                                                      Less than
>                                                      Greater than
<=                                                    Less than or equal
>=                                                    Greater than or equal
[]                                                      Subscripting
<<                                                    Output
>>                                                    Input

Assignment

A string object can be assigned to another string object or another string. For example,

            string    name;
            string name1=”Peeyush”;
            name=name1;
                                   
objects name and name 1 will contain same string.

Concatenation

The two strings can be concatenated using ‘+’ operator. For example,

            string firstname=”Peeyush”;
            string lastname=”Taori”
            string fullname;
            fullname= firstname + “  “ + lastname;

The string objects firstname, whitespace and lastname are concatenated and assigned to string object fullname.

Equality

The equality operator ‘==’ checks whether the two strings are equal or not.

            string name1=”Peter”;
            string name2=”Peter”;
            if(name1==name2)
            {         
            }
The operator will return true because both string objects have same value.

Inequality

The inequality operator ‘!=’ returns true if two string objects are not equal. For example,

            string name1=”peter”;
            string name2=”Tom”;
            if(name1!=name2)
            {
            }
The operator will return true because name1 is not equal to name 2.

Less than

The less than operator checks whether the string objects come before another string object. It returns true if one string object in alphabetical order comes before another string object. For example,

            string name1=”cat”;
            string name2=”dog”;
            if(name1<name2)
            {         
                        cout << “cat comes before dog” << endl;
            }
The message “cat comes before dog” will be displayed as in alphabetical order word cat will appear before word dog.

Greater than

The greater than operator ‘>’ checks whether one string object comes after another string object. It returns true if one string object in alphabetical order comes after another string object. For example,

            string name1=”cat”;
            string name2=”dog”;
            if(name2>name1)
            {         
                        cout << “dog comes after cat” << endl;
            }

The message “dog comes after cat” will be displayed as alphabetically word dog comes after word cat.

Subscripting

The subscript operator ‘[]’ is used to access a character of the string just like null terminated character arrays. The subscript returns a char value. For example,

            string name1=”cat”;
            char ch=name1[1];
            name1[0]=’d’;

The character ch will contain letter ‘c’. The name1 will become will change to “dat”.

Input and Output
             
The insertion operator ‘<<’ writes the value of object to the output stream. The extraction operator ‘>>’ reads the character string from the input stream and assigns it to the string object. For example,
                       
string name;
                        cin >> name;
                        cout << name << endl;

The user will enter the name and the same name will be displayed on the screen.

Here is a program which shows the working of string class.

#include<iostream>
#include<string>
using namespace std;

int main()
{
            char a,b;
            string name1,name2,name3;
            cout << "Enter your first name" << endl;
            cin >> name1;
            cout << "Enter your last name" << endl;
            cin >> name2;
            name3=name1 + "  " + name2;
            if(name1<name2)
            {         
                        cout << "First name alphabetically comes before last name" << endl;
            }
            if(name1>name2)
            {
                        cout << "Last name alphabetically comes before first name" << endl;
            }
            if(name1==name2)
            {
                        cout << "First name and last name are same" <<  endl;
            }
            cout << "Your full name is : " << name3 << endl;
            a=name1[0];
            b=name2[0];
            cout << "The initals of the name are " << a << "." << b << "." << endl;
            return(0);
}

The result of the program is:-

program output

The statement
           
            #include<string>

includes a header file string into the program. The statement
                       
            name3=name1 + "  " + name2;

concatenate two string objects and whitespace. The statement

                        if(name1<name2)

checks whether name1 alphabetically comes before name2. The statement

                        if(name1>name2)

checks whether name1 alphabetically comes after name2. The statement

                        if(name1==name2)

checks whether two string objects are equal or not. The statements

                        a=name1[0];
                        b=name2[0];

assign character a and b the first letter of name1 and name2 respectively.
----------------------------------------------------------------------------------------------------------------------------------
    Vector

A vector is a dynamic array. Vector is the most efficient way of implementing arrays. The functionality of vector is same as normal arrays used. The vectors automate the task of managing the size and capacity of the arrays. The new elements can be inserted easily. The elements can be erased with much less effort. In order to define vectors a header file vector is included in the program. The general form of a vector declaration is:-

vector<type>  variable_name;   or    vector<type> variable_name(size);

The type is the data type of the vector. The variable_name is the name of the variable. For example,

vector<int> a(10);

creates a vector a of integer type whose size is 10. Some of the functions of vector are:-

  • Size- The function size() returns the size of the vector.
  • Begin – The function begin() returns the iterator at the beginning of the vector.
  • End – The function end()  returns the iterator at the end of the vector.
  • Push Back- The function push_back() inserts an element at the end of the vector.
  • Insert- The function insert() inserts an element in the middle of the vector.
  • Erase- the function erase() remove the elements from the vector.
  • Empty- The function empty() checks whether vector is empty or not. It returns true if vector is empty.
  • Pop Back- The function pop_back() removes the last element from the vector.
  • Resize – The function resize() resets the size of the vector.

Here is a program which illustrates the working of functions of vector.

#include<iostream>
#include<vector>
using namespace std;

int main ()
{
            int i,num,num1=0 ;
            vector<int> a(2);
            vector<int>::iterator p;
            if(a.empty())
            {
                        cout << "Vector is now empty" << endl;
            }
            cout << "The size of the vector is : " << a.size() << endl;
            for(i=0;i<2;i++)
            {
                        cout << "enter the integer in the vector" << endl;
                        cin >> a[i];
            }
            cout << "enter another number to insert at the end of the vector" << endl;
            cin >> num;
            a.push_back(num);
            cout << "Now the size of the vector is : " << a.size() << endl;
            a.pop_back();
            cout << "Now the size after removing last element is : "  << a.size() << endl;
            cout << "Enter a number to insert at second position" << endl;
            cin >> num1;
            a.insert(a.begin()+1,num1);
            p=a.begin();
            a.erase(p,p+1);
            cout << "The number in the vector are" << endl;
            for(i=0;i<a.size();i++)
            {
                        cout << a[i] << endl;
            }
            return(0);
}

The result of the program is:

program output

The statement

            #include<vector>

includes a header file <vector> into the program. The statement

            vector<int> a(2);

creates  a vector a of integer type of size 2. The statement

            vector<int>::iterator p;

creates a iterator p for the vector.  The statement

            if(a.empty)

checks whether the vector is empty. It returns false as the vector a is initialized with size 2. The statement

            cout << "The size of the vector is : " << a.size() << endl;

displays the size of the vector. The function a.size() calculates the size of the vector which is currently 2.  The statement

            a.push_back(num);

inserts the element num entered by the user at the end of the vector 3. The statement

            cout << "Now the size of the vector is : " << a.size() << endl;

displays the current size of the vector which is 3 now after inserting element at the end of the vector. The statement

            a.pop_back();

erases the last element from the vector a. The statement

            cout << "Now the size after removing last element is : "  << a.size() << endl

displays the current size of the vector which is 2 after removing the last element from the vector. The statement

            a.insert(a.begin()+1,num1);

inserts the element num1 entered at the second position of the vector. The function a.begin() places the iterator at the beginning of the vector. The function a.begin()+1 denotes the second position of the vector.  The statement

            p=a.begin();

places the iterator p at the beginning of the vector. The statement

            a.erase(p,p+1);

erases the first element from the vector. Now the vector size will be reduce by 1 and elements will shift to the one position before. In the end elements of the current vector are displayed.
------------------------------------------------------------------------------------------------------------------------------------
 Queue

A queue can be automatically created using queue class in C++. A single ended queue is created. The members of the queue are accessed in first in and first out manner.  A header file <queue> is included in the program in order to implement the functionality. The constructor queue() can  create a empty queue. The general form of how variable of type queue is declared is:

queue<type> q;

It creates a queue q of type integer. For example,

            queue<int> q;

creates a queue of type integer. Some of the functions of queue are:-

  •  Back- The function back() places the reference to the last element in the queue.
  •  Empty – The function empty() returns true if queue is empty.
  •  Front- The function front() returns a reference to the first element of the queue.
  •  Pop- The function pop() removes the first element of the queue.
  •  Push – The function push() adds the element at then end of the queue.
  •  Size- The function size() returns the size of the queue.

Here is a program which illustrates the working of functions of queue.

#include<iostream>
#include<queue>
using namespace std;

int main ()
{
            int i=0,num=0,num1=0;
            queue<int> q;
            if(q.empty())
            {
                        cout << "The queue q is empty" << endl;

            }
            for(i=0;i<3;i++)
            {
                        cout << "Enter the number" << endl;
                        cin >> num;
                        q.push(num);
            }
            cout << "The size of the queue is : " << q.size() << endl;
            cout << "The first element is : " << q.front() << endl;
            cout << "The last element is : " << q.back() << endl;
            q.pop();
            cout << "The size of the queue is : " << q.size() << endl;
            cout << "The first element is : " << q.front() << endl;
            return(0);
}

The result of the program is:-

program output

The statement

            #include<queue>

includes a header file <queue> into the program. The statement   

            queue<int> q;

creates a queue q of integer type. The statement

            if(q.empty())

checks  whether queue is empty or not. It returns true because queue is empty. The statement

            q.push(num);

inserts an element num entered by the user at the end of the queue. The statement

            cout << "The size of the queue is : " << q.size() << endl;

prints the size of the queue which is 3 after pushing 3 elements in the queue. The statement

            cout << "The first element is : " << q.front() << endl;
prints the first element of the queue. The function q.front() returns the first element of the queue. The statement

            cout << "The last element is : " << q.back() << endl;

prints the last element of the queue. The function q.back() returns the last element of the queue. The statement

             q.pop();

removes the front element of the queue. It reduces the size of the queue by 1. Now the first element will change and second element will become first element and so on.
-----------------------------------------------------------------------------------------------------------------------------------
   iomanip

The iomanip is a parameterized input output manipulator. In order to access manipulators that take parameters the header file <iomanip> is included in the program. Some of the manipulators are:-

  • setioflags- It sets the flags controlling the input output stream.

  • resetiosflags -  It resets the flags controlling the input output stream.

  • setbase(int n) – It sets the output representation of the number to octal, decimal or hexadecimal corresponding to the argument n which is 8 in case of octal, 10 for decimal and 16 for hexadecimal. Any other value will not change the base.

  • setfill ( char c) – It sets the fill character to be the value of character c. The fill character is used in output stream for padding.

  • setprecision(int n) – It sets the precision of floating point number to n digits.

  • setw(int n) – It sets the width of the field of the next output to n characters. If the length of the output stream is less than n then spaces are padded. The no of spaces padded is the difference between n and length of the output stream. If the length of the output stream is less than n there will be no effect on output stream.

Here is a program which illustrates the working of input output manipulators.

#include<iostream>
#include<iomanip>
using namespace std;

int main ()
{
            int i=10;
            double a=78.121113;
            char c[50];
            char c1='p';
            cout << "Enter your name " << endl;
            cin >> c;
            cout << setw(10) <<  c << endl;
            cout << setw(15) << c << endl;
            cout << setprecision(5) << a << endl;
            cout << setprecision(7) << a << endl;
            cout << "Hexedecimal number : "  << setbase(16) << i << endl;
            cout << "Octal number : " << setbase(8) << i << endl;
            cout << setfill(c1) << setw(12) << c << endl;
            cout << setfill(c1) << setw(2) << c << endl;

            return(0);
}

The result of the program is:-

program output

The statement
           
            #include<iomanip>

includes a header file iomanip into the program. The user enters then name ‘Tom’.  The statement

            cout << setw(10) <<  c << endl;

sets the width of the string c as 10. Since the length of the name ‘Tom’ is 3 extra spaces are added to set the width to be 10. No of spaces added are 7.  The statement

            cout << setw(15) << c << endl;

sets the width of string c as 15 . This time more no of spaces are added. The statement
           
            cout << setprecision(5) << a << endl;

sets the precision of the floating point number a to be 5 digits. The output is 78.121 where actual floating point number is   78.121113. The statement

            cout << setprecision(7) << a << endl;

sets the precision of the floating point number to be 7 digits. The output is 78.12111 where actual floating point number is   78.121113. The statement

            cout << "Hexedecimal number : "  << setbase(16) << i << endl;

sets the base of the number i as hexadecimal. The value of the variable i is 10. The hexadecimal format of 10 is a. Therefore output is a. The statement

cout << "Octal number : " << setbase(8) << i << endl

sets the base of the number 10 as octal. The octal format of 10 is 12 therefore it displays 12. The statement

            cout << setfill(c1) << setw(12) << c << endl;  

sets the fill character to be c1. The value of c1 is ‘p’. The statement performs the same function of setw but instead of spaces character ‘p’ is padded. The length of string ‘Tom’ is 3 therefore 9 ps are padded to set the width to be 12. The statement

            cout << setfill(c1) << setw(2) << c << endl;

sets the fill character to be c1. Since the width of the output stream is less than the length of the string ‘Tom’ therefore there is no effect on output. 
------------------------------------------------------------------------------------------------------------------------------------