Wednesday, 11 June 2014

Programming in C++



1.0    Introduction

C++ has borrowed many features from other programming language particularly from C. Programmers argue that C++ is an extension of C, providing more and powerful programming techniques. It introduces Object Oriented concepts over C programming language. Structured programming concepts found in C are found in a more powerful form in C++. Such features include: function overloading, single line comment and function template. Generally, Programming in C++ improves productivity of the programmer.


1.1   Moving from C to C++

In C Programming language, the standard library function printf() statement sends the output to the standard output device, the console. The function body consists of statements for creating data storage called local variables and executable statements. Note that local variables in main() are not visible by any other function. Recall the traditional C programme called Hello World, in example 1.1.

Example 1.1


/* Hello.c: printing Hello World message */
#include<stdio.h>
main( )
{
  printf(“Hello World”);
}

Running the program it outputs the statement:

Hello World

However, the program could be rewritten using C++ streams.  The C++ equivalent of the Hello World program is given in example 1.2 in the program hello.cpp.

Example 1.2


// hello.cpp: printing Hello World message
#include <ostream.h>
main()
   {

      cout << “Hello World”;
   }

Running the program it outputs the statement:

Hello World
The header file iostream.h supports streams programming features by including predefined stream objects.

The character  “<<” is called the C++ stream insertion operator. It sends the message “Hello World” to the predefined console object  cout, which in turn prints on the console.  The Hello World program in example 1.2 is again shown below for the purpose of discussion.


1. // hello.cpp: printing Hello World message             comment

2. #include <iostrem.h>                              preprocessor directive
3. main()                                                                function declarator.
4.         {                                                                    beginning of the program
5.              cout << “Hello World”;              body of the function main
6.         }                                                                    end of the program


Various components of the program hello.cpp, shown above, are interpreted as follows:
                                   
First Line: Comment Line

The statement which starts with symbols “//” (i.e, two slash characters one after another without a space) is treated as a comment.  Hence, the compiler ignores the complete line starting from the // character pair.


The file name extension  .cpp,in the program hello.cpp, is an acronym for C PlusPlus (C++).  The compiler will recognize a program as a C++ program only when it has an extension .cpp.

Second Line: Preprocessor Directive


The second line is a preprocessor directive.  The preprocessor directive #include<iostream.h> includes all the statements of the header file iostream.h. It contains instructions and predefined constants that will be used in the program.  It plays a role similar to that of the header file stdio.h of C. 


Third Line: Function Declarator

The third line in the program is
     main() 

Similar to a C program, the C++ program also consists of a set of functions.  Every C++ program must have one function with name main, from where the execution of the program begins.  The name mainis a special word (not a reserved word) but must not be invoked anywhere by the user.  The names of the functions (except main) are given by the programmer.  The function name is followed by a pair of parentheses which may or may not contain arguments.  In this case, there are no arguments, but still the parentheses pair is mandatory.  Every function is supposed to return a value, but the function in the example does not return any value.  In other compilers, such function names must be preceded by the reserved word void.

Fourth Line: Function Begin

The function body in a C/C++ program is enclosed between two flower brackets.  The opening flower bracket ({) marks the beginning of a function.  All the statements in a function, which are listed after this brace can either be executable or non-executable statements.

Fifth Line:  Body of a Function 

The function body contains a statement to display the message Hello World.  The output statement coutis pronounced as C-out (meaning Console Output).  It plays a role similar to that of the printf() in C. 

cout << “Hello World”;

prints the message “Hello World” on the standard console output device i.e. Video Display Unit (VDU) by default).  It plays the role of the statement.

printf(“Hello World”);

as in the hello. c program.


Sixth Line:  Function End

Just like it is in C, the end of a function body in a C++ program is marked by the closing flower bracket (}). When the compiler encounters this bracket, it knows it has reached the end of the program and transfers control to a caller.  In this program, the last line actually marks the end of program and control is transferred to the operating system on termination of the program.

Compilation Process

The C++ program hello.cpp can be entered into the system using any available text editor.  The program coded by the programmer is called the source code.  This source code is supplied to the compiler for converting it into the machine code.

C++ programs make use of libraries.  A library contains the object code of standard functions.  The object code of all functions used in the program have to be combined with the program written by the programmer.  In addition, some start-up code is required to produce an executable  version of the program.  This process of combining all the required object codes and the start-up code is called linking and the final product is called the executable code.



1.2   Streams Based I/O

C++ supports a rich set of functions for performing input and output operations.  The syntax of using these I/Ofunctions is totally consistent, irrespective of the device with which I/Ooperations are performed.  C++’s new features for handling I/O operations are called streams.  Streams are abstractions that refer to data flow.  Streams in C++ are classified into

·   Output Streams
·   Input Streams.



Output Streams

The output streams allow to perform write operations on output devices such as screen, disk, etc.  Output on the standard stream is performed using the cout object.  .  The syntax for the standard output stream operation is as follows:

cout << variable;

the word cout is followed by the symbol <<, called the insertion or put-to operator, and then with the items (variables/constants/expressions) that are to be output.  Variables can be of any basic data type.

The following are examples of stream output operations:

cout << “Hello World”;
int age;
cout << age;
float weight;
cout << weight;
double area;
cout << area;
char letter;
cout << letter;

More than one item can be displayed using a single coutoutput stream object.  Such output operations in C++ are called cascaded output operations.  For example, output of the age of a person along with some message can be performed by cout as follows:

cout << “Age = “ << age;

The cout object will display all the items from left to right.  Hence, in the above case, it prints the massage string “Age =” first, and then prints the value of the variable age.  C++ does not enforce any restrictions on the maximum number of items to output.  The complete syntax of the standard output streams operation is as follows:

cout << variable << variable2 << .. << variableN;

The object cout must be associated with at least one argument.  Like printf( ), a  constant value can also be sent as an argument to the cout object.  Following are some valid output statements:

cout << ‘H’
cout << “Hello”;
cout << 420;
cout << 90.25,
cout << 1234567;
cout << “ ”;       // will display blank
cout << “\n”;      // prints new line
cout << x << “ “ << y;

The last output statement prints the value of the variable x followed by a blank character, and then the value of the variable y.

The program output.cpp in example 1.3, demonstrates the various methods of using cout for performing output operation.

 

Example 1.3


// Output.cpp: display contents of variables of different data types

#include <iostream.h>
 main()
{
  char sex;
  char *msg = “C++ cout object”;
  int age;
  float number;
  sex = ‘M’;
  age = 24;
  number = 420.5;
  cout << sex;
  cout << “  “ << age << “  “ << number;
  cout << “ \n” << msg << endl;
  cout << number +1;
     cout << “\n” << 99.99;
}

Runing the program the output will be:
M  24  420.5
C++  cout  object
421.5
99.99

The item endl in the statement:

cout << “\n” << msg << endl;

serves the same purpose as “\n” (linefeed and carriage return) and is known as a manipulator.  It may be noticed that there is no mention of the data types in the I/O statements as in C. Hence, I/O statements of C++ are easier to code and use.  C++, as a superset of C, supports all functions of C, however, they are not used in the above C++ program.


Input Streams

The input streams allow to perform read operation with input devices such as keyboard, disk, etc.  input from the standard stream is performed using the cinobject. The syntax for the standard input stream operation is as follows:

cin >> variable;

The word cin is followed by the symbol >> (extraction operator) and then with the variable, into which the input data is to be stored.  The use of cin in performing input operation is shown in example 1.4 below.

Example  1.4


int age;
cin >> age;
cin >> weight;
double area;
cin >> area;
char code;
cin >> code;
char name[20];
cin >> name;

Similarly, input of more than one item can also be performed using the cin input stream object.  Such input operations in C++ are called cascaded input operations.  For example, reading the name of a person followed by the age, can be performed by the cin as follows:

cin >> name >> age;

C++ does not impose any restrictions on the number of items to be read.  The complete syntax of the standard input streams operation is as follows:

cin >> variable1 >> variable2 >> .. >> variableN;

The object cin must be associated with at least one argument.  Like scanf(), constant values cannot be sent as an argument to the cin object.  Following are some valid input statements: 

cin >> i >> j >> k;
cin >> name >> age >> address;

The program read.cpp in example 1.5, demonstrates the various methods of using cinfor performing input operation.                   

Example 1.5

// read.cpp: data input through cin object

 #include <iostream.h>
 void main()
  {
char name[25];
int age;
char address[25];

// read data
cout << “Enter Name: ”;
cin >> name;
cout << “Enter age: “;
cin >> age;
cout << “Enter Address: “;
cin >> address;

//Output data
cout << “The data entered are:” << endl;
cout << “Name is  “ << name << endl;
cout << “Age is  “ << age << endl; 
cout << “Address is “ << address;
  }

Running this program the output will be:

Enter Name: Emmanuel
Enter Ange:  24
Enter Address: TEKU Box  691MBEYA

The data entered are:
Name is  Emmanuel
Age is   24
Address is  TEKU Box 691 MBEYA

Performing I/O operations through the coutand cin are analogous to the printf() and scanf() functions of the C language.  But with different syntax specifications.  Two important points to be noted about the stream operations.

(i)     Streams do not require explicit data types specification in I/O statement.
(ii)   Streams do not require explicit address operator prior to the variable in the input statement.


Format-free input and output are special features of C++, which make I/O operations easier for beginners.  Furthermore, the input stream cin accepts both numbers and characters, when the variables are given in the normal form. 

In C++, operators can be overloaded, i.e. the same operator can perform different activities depending on the context (types of data-items with which they are associated).  The cout is a predefined object in C++ which corresponds to the output stream, and cin is an object in the input stream.  Example 1.6 illustrates the use of cin and cout streams.


 Example  1.6


// a program illustrating the use of cin and cout streams
#include <iostream.h>
main()
{
       int x, y, z;
       cout << “Please enter an integer: “;
       cin >> x;
       cout << endl << “Please enter a second number: “;
       cin >> y;
       z = x + y;
       cout << “Total is “ << z << endl;
     }

No comments:

Post a Comment