Thursday 16 May 2013

Lexical IN C++


Introduces the fundamental elements of a C++ program as they are meaningful to the compiler are used to construct statements, definitions, declarations, and so on, which are used to construct complete programs.
The fundamental elements of a C++ program are called “lexical elements” or “tokens” to construct statements, definitions, declarations, and so on, which are used to construct complete programs. The following lexical elements are discussed here:
1.    Tokens
A token is the smallest element of a C++ program that is meaningful to the compiler. The C++ parser recognizes these kinds of tokens: Identifiers, Keywords, Literals, Operators, Punctuators, and Other Separators. A stream of these tokens makes up a translation unit.
2.    Comments
A comment is text that the compiler ignores but that is useful for programmers. Comments are normally used to annotate code for future reference.
A C++ comment is written in one of the following ways:

The /* (slash, asterisk) characters, followed by any sequence of characters (including new lines), followed by the */ characters.

The // (two slashes) characters, followed by any sequence of characters. A new line not immediately preceded by a backslash terminates this form of comment. Therefore, it is commonly called a “single-line comment.”
/*This is an example of
  comments in a program */
FileName = String( "hello.dat" );   // Initialize file string 

3.    Identifiers
An identifier is a sequence of characters used to denote one of the following:
   
Object or variable name
   
Class, structure, or union name
   
Enumerated type name

 Member of a class, structure, union, or enumeration

 Function or class-member function
   typedef name
   Label name
The first character of an identifier must be an alphabetic character, either uppercase or lowercase, or an underscore ( _ ). Because C++ identifiers are case sensitive, fileName is different from FileName.

4.    C++ keywords
Keywords are predefined reserved identifiers that have special meanings. They cannot be used as identifiers in your program. The following keywords are reserved for C++:
asm
auto
bad_cast
bad_typeid
bool
break
case
catch
char
class
const
const_cast
continue
default
delete
do
double
dynamic_cast
else
enum
except
explicit
extern
false
finally
float
for
friend
goto
if
inline
int
long
mutable
namespace
new
operator
private
protected
public
register
reinterpret_cast
return
short
signed
sizeof
static
static_cast
struct
switch
template
this
throw
true
try
type_info
typedef
typeid
typename
union
unsigned
using
virtual
void
Volatile
while



5.    Punctuators
Punctuators in C++ have syntactic and semantic meaning to the compiler but do not, of themselves, specify an operation that yields a value. Some punctuators, either alone or in combination, can also be C++ operators or be significant to the preprocessor.  The punctuators are
! % ^ & * ( ) + = { } | ~
[ ] \ ; ' : " < > ? , . / #
The punctuators [ ], ( ), and { } must appear in pairs

6.    Operators

Operators in C++


Operator is a symbol that causes specific mathematical or logical manipulations to be performed. A combination of constants and variable together with the operators is called an expression .An expression that involves only constant is called constant expression .An expression that involves only arithmetic operators are called arithmetic expressions.

Eight types of operators :-

1.Arithematic Operators:
             +         Addition
-                      Subtraction
*           Multiplication
/           Division
%         Modulo Divison.

2. Relational operators:- used to make comparisons
           <     less than
>    greater than
<=  Less than or equal to
>= greater than or equal to
= = Equal to
!=   not equal to
  1. Logical operators:-logical operators && and || are used when more than one conditon are to be tested to make decision
&&             AND
||                OR
!                 NOT
  1. Assignment operators
=    equal to
C supports a set of shorthand assignment operators .Eg:+=, -=, *=, /= etc.
A=A+1 equals A+=1
S=S*(k+p)  equals S*=(k+p)
5.     Increment or Decrement Operators
     ++   increment
--    Decrement
Prefix operator à First adds one to the operand and stores the result to the variable on the left. Suffix operator à First assigns value to the variableon the left and the increments in the operand.
6.  Conditional Operator:-
A ternary operator “?:” is available in C to construct conditional expression s of the form
exp1? exp2:exp3;
7.    Bitwise operators:
&    Bitwise and
|     Bitwise or
^    Bitwise Ex-Or
<<  Shift Left
>>  Shift Right
~    Complement
8.    Special Operators:
C supports some special operators such as comma(,) ,size-of operator(Determines the length of  arrays and structures), pointer operator ( *) and member selection operators( . and -> )
Comma operators:-     Are used  to link the related expressions together .A comma linked list of expressions are evaluated left to right. The value of the rightmost expression is the value of the combined expression.
      Eg:- value=(x=10,y=5,x+y); 

OOPs:Object oriented programming


Object oriented programming is known as OOPs.
OOP is a method of implementation in which programs are organized as co-operative collections of objects, each of which represents an instance of some class and whose classes are all members of a hierarchy of classes united through the property called inheritance.
Three important concepts about OOP are objects, classes and inheritance.
Structured Programming views the two core elements -Data & Functions as two separate entities.  Object oriented programming views them as a single entity. OOP is a new way of solving problems with computers.  OOP languages provide the programmer the ability to create class hierarchies, instantiate co-operative objects collectively working on a problem to produce the solution and send messages between objects to process themselves.
The fundamental features of the OOPs are the following:
§  Encapsulation
§  Data Abstraction
§  Inheritance
§  Polymorphism
§  Message Passing
Encapsulation:  A mechanism that associates the code and the data it manipulates into a single unit and keeps them safe from external interference and misuse.
Data Abstraction:  The technique of creating new data types that is well suited to an application to be programmed. It provides the ability to create user-defined data types, for modeling a real world object, having the properties of built in data types and a set of permitted operators.
Inheritance:   It allows the extension and reuse of existing code without having to rewrite the code from scratch. Inheritance involves the creation of new classes (derived classes) from the existing ones (base classes), thus enabling the creation of a hierarchy of classes that stimulate the class and subclass concept of the real world. The new derived class inherits the members of the base class and also adds its own.
Polymorphism:  It allows a single name/operator to be associated with different operations depending on the type of data passed to it. In C++ it is achieved by function over loading,operator over loading and dynamic binding(virtual functions).
Message Passing: The process of invoking an operation on an object. In response to a message, the corresponding method (function) is executed in the object.

OBJECTS
            An object can be a person, a place or a thing with which the computer must deal. Some objects may correspond to real-world entities such as students, employees, bank accounts inventory items etc.  Every object will have data structures called attributes and behaviour called operations.
            Consider the object having the attributes: Account Number, Account type, Name, Balance and Operations: Deposit, Withdraw, Enquire.

CLASSES
            The objects with the same data structure(attributes) and behavior (operations) are grouped into a class.  All those objects possessing similar properties are grouped into the same unit.
            Every object is associated with data and functions which define meaningful operations on that object. 

ACCESS SPECIFIERS IN C++

 public:

The most open level of data hiding, anything that is public is available to all derived classes of a base class, and the public variables and data for each object of both the base and derived class is accessible by code outside the class. Functions marked public are generally those the class uses to give information to and take information from the outside world; they are typically the interface with the class. The rest of the class should be hidden from the user (This hidden nature and the highly focused nature of classes is known collectively as encapsulation). The syntax for public is:
public:
Everything following is public until the end of the class or another data hiding keyword is used.

protected:

Variables and functions marked protected are inherited by derived classes; however, these derived classes hide the data from code outside of any instance of the object. Keep in mind, even if you have another object of the same type as your first object, the second object cannot access a protected variable in the first object. Instead, the second object will have its own variable with the same name - but not necessarily the same data. Protected is a useful level of protection for important aspects to a class that must be passed on without allowing it to be accessed. The syntax is the same as that of public. specifically,
 protected: 

private:

Private is the highest level of data-hiding. Not only are the functions and variables marked private not accessible by code outside the specific object in which that data appears, but private variables and functions are not inherited. The level of data protection afforded by protected is generally more flexible than that of the private level. Of course, there is a certain joy in protecting your data with the keyword private. The syntax remains the same.
private: 

THE ORIGIN OF C++

The C programming language was developed at AT&T for the purpose of writing the operating system for the PDP-11 series of computers which ultimately became the UNIX operating system. C was developed with the primary goal of operating efficiency. Bjarne Stroustrup, also of AT&T, developed C++ in order to add object oriented constructs to the C language. Because object oriented technology was new at the time and all existing implementations of object oriented languages were very slow and inefficient, the primary goal of C++ was to maintain the efficiency of C.

C++ can be viewed as a traditional procedural language with some additional constructs. Beginning with C, some constructs are added for object oriented programming and some for improved procedural syntax. A well written C++ program will reflect elements of both object oriented programming style and classic procedural programming. C++ is actually an extendible language since we can define new types in such a way that they act just like the predefined types which are part of the standard language. C++ is designed for large scale software development.
C++ syntax
By definition, syntax is the rules governing the formation of statements in a programming language. In other words, it is the specific language (code) you use to turn algorithms into programs and specific rules you have to follow when programming with C++. As you will find out, if you make one small mistake when writing code, the compiler will notify you of the syntax error when you try to run it. C++, like all languages, is very picky when it comes to syntax. Let's look at a simple example program written in C++.
// BEGIN PROGRAM
// Program to calculate the average of 4 integers

#include <iostream.h>            // header file for input/output stream
#include <conio.h>                 // header file for standard input/output

int main( )
{
    int number1, number2, number3,number4;    // declaration of variables
    float average;
    clrscr();                                            // Clear the output screen
    cout << endl << endl;
    cout << "Enter first integer: ";
    cin >> number1;
    cout << "Enter second integer: ";
    cin >> number2;
    cout << "Enter third integer: ";
    cin >> number3;
    cout << "Enter third integer: ";
    cin >> number4;

    average = (number1 + number2 + number3+number4) / 3.0;           // calculates the average
    cout << "The average of the three integers is: " << average << endl;

    getch();                                            // Wait for a character expression from keyboard
    return 0;
}    // end main( )
For now, notice how each executable statement in the program is ended with a semi-colon. Every executable statement must always be terminated with a semi-colon, which signals that it is the end of the statement. Any code placed after // will not affect the code; // is used for comments and documentation. Also notice that text is always enclosed in parentheses. Let's dig deep into the code to find out why you need to use certain code statements.
  • cout - console output - It is simply letting the compiler know that something is being sent into the output stream (normally the screen)
  • << - insertion operator - cout and the insertion operator go hand and hand; you must use it whenever you issue a cout command
  • cin - console input - It is simply letting the compiler know that something is being sent into the input stream (normally into the memory of a computer)
  • >> - extraction operator - cin and the extraction operator go hand and hand; you must use it whenver you issue a cin command
  • endl - end line - basically the same as pressing the return key in a text editor; returns down to the next line 

DATA TYPES IN C++


C++ supports three kinds of object types:
Fundamental types are built into the language (such as int, float, or double). Instances of these fundamental types are often called “variables” .
Derived types are new types derived from built-in types. 
Class types are new types created by combining existing types.
Fundamental Types of the C++ Language
Category
Type
Contents
Integral
char
Type char is an integral type that usually contains members of the execution character set — in Microsoft C++, this is ASCII.


The C++ compiler treats variables of type char, signed char, and unsigned char as having different types. Variables of type char are promoted to int as if they are type signed char by default, unless the /J compilation option is used. In this case they are treated as type unsigned char and are promoted to int without sign extension.

short
Type short int (or simply short) is an integral type that is larger than or equal to the size of type char, and shorter than or equal to the size of type int.


Objects of type short can be declared as signed short or unsigned short. Signed short is a synonym for short.

int
Type int is an integral type that is larger than or equal to the size of type short int, and shorter than or equal to the size of type long.


Objects of type int can be declared as signed int or unsigned int. Signed int is a synonym for int.

Long
Type long (or long int) is an integral type that is larger than or equal to the size of type int.


Objects of type long can be declared as signed long or unsigned long. Signed long is a synonym for long.
Floating
float
Type float is the smallest floating type.

double
Type double is a floating type that is larger than or equal to type float, but shorter than or equal to the size of type long double.

long double
Type long double is a floating type that is equal to type double.
Sizes of Fundamental Types
Type
Size
char, unsigned char, signed char
1 byte
short, unsigned short
2 bytes
int, unsigned int
4 bytes
long, unsigned long
4 bytes
float
4 bytes
double
8 bytes
long double
8 bytes