Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

object oriented programming with c++, Exams of Object Oriented Programming

It is very useful to learn in few seconds .

Typology: Exams

2017/2018

Uploaded on 10/21/2018

music-world-1
music-world-1 🇮🇳

4 documents

Partial preview of the text

Download object oriented programming with c++ and more Exams Object Oriented Programming in PDF only on Docsity!

tOBJECT ORIENTED PROGRAMMING USING C++

1.1 The Evolution of C++:

Computer languages have come a long way since the 1940’s. Back then, scientists punched instructions in to mammoth, room-sized computer systems. These instructions were long series of zeroes and ones. These machine language instructions are called the first generation of computer languages. The 1950’s saw the emergence of the second generation computer languages- assembly language- easier to write than machine language but still extremely complicated for a lay person. However, the computer could still understand only machine language. Therefore, the assembler software was developed to translate the code written in assembly language into machine language. In 1967, Martin Richard developed a language called BPCL for writing operating systems. An operating system is a set of programs that manages the resources of a computer and its interactions with users. The era of the third generation of computer languages had arrived. In 1970’s Ken Thompson modified BPCL to create a new language called B. working for Bell Laboratories, Thompson teamed up with Dennis Ritchie and wrote an early version of the Unix operating system for a DEC PDP-7 computer. Dennis Ritchie was working on a project to further develop the Unix operating system. He wanted a low-language, like the assembly language, the could control hardware efficiently. At the same time, he wanted the language to provide the features of a high level language, that is, it should be able to run on different types of hardware. B had performance drawbacks, so in 1972, he rewrote B and called in C. Therefore, C is categorized as both a second and third generation language. Thompson and Ritchie rewrote the Unix operating system in C. In the years that followed, C was widely accepted and used over different hardware platforms. In 1989, the American National Standards Institute( ANSI), along with the International Standards Organization (ISO), approved a machine independent and standard version of C. In the early 1980’s , Bjarne Stroustrup working for Bell Labs developed the C++ language. In his own words , “ C++ was designed primal so that my friends an I would not have to program in assembly, C, or various modern high-level languages. Its main purpose was to make writing food programs easier and more pleasant for the individual programmer”. (Bjarne Stroustup The C++ Programming Language, Third Edition. Reading, MA: Addition Wesley Publishing Company 1997). C++ was originally known as ‘C with classes’ as two languages contributed to its design. C which provided low-level features, and simula67, which provided the class concept. The C++ language is a superset of C. Like the C language, C++ is compact and can be used for system programming. It can use existing C software libraries. (Libraries are collections of programs that you can reuse in your program.) C++ has object-oriented programming (OOP) capabilities similar to an earlier computer language called Simula67. C++ is called a hybrid language because it can be used both as a procedural language like C and as an object-oriented language like Simula67, other object-oriented languages include Smalltalk and Ada. In 1990’s, the ANSI/ISO committee began working on a standard version of the C++ language. By June 1998,the committee had approved the Final Draft International Standard for C++. It was released in the form of a document. It extended the language to include exceptions, templates, and the Standard Template Library ( STL).

Object oriented programming

Software Evolution: The software evolution has had distinct phases or “layers” of growth. These layers were built up one by one over the last five decades as shown in figure. Each layer representing an improvement over the previous one. Fig. Layers of computer software Object-Oriented Programming (OOP) is an approach program organization and development that attributes to eliminate some of pitfalls of conventional programming methods by incorporating the best of structured programming features with several powerful new concepts. 1.2 Procedure – Oriented Programming: The high level languages such as COBOL, FORTRAN and C are commonly known as procedure- oriented programming (POP). In the procedure-oriented approach, the problem is viewed as a sequence of things and a number functions are written to accomplish these tasks. The primary focus is on functions. Procedural Programming Model : Each problem is divided into smaller problems and solved using specified modules that act on data. Fig – Structure of procedural-oriented programs

Procedure-oriented

Assembly language

Machine language

1, 0

Main Program Function - (^1) Function - 2 Function - 4 Function - 3 Function - 5 Function - 6 Function - 7 Function - 8

In a multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. Fig shows the relationship of data and functions in a procedure-oriented program. Fig- Relationship of data and functions in procedural programming Global data are more vulnerable to an inadvertent change by a function. In a large program it is very difficult to identify what data is used by which function. Another serious drawback with the procedural approach is that it does not model real world problems very well. This is because functions are action-oriented and do not really corresponding to the elements of the problem. Some characteristics exhibited by procedure-oriented programming are:  Emphasis is on doing things (algorithms).Large programs are divided into smaller programs known as functions.Most of the functions share global data.Data move openly around the system from function to function.Functions transform data from one form to another.Employs top-down approach in program design. 1.3 Object-Oriented Programming Paradigm: The major motivating factor in the invention of object-oriented approach is to remove some of the flaws encountered in the procedural approach. OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it, and protects it from accidental modification from outside functions. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. The organization of data and functions in object-oriented program is shown in figure. Object A Object B Object C Figure - Organization of data and functions in OOP Global data Global data Function- 1 Local data Function- 2 Local data Function- 3 Local data Data Functions Data Functions Data Functions

The data of an object can be accessed only by the functions associated with the object. However, functions of one object can access the functions of other objects. Some of the striking features of object-oriented programming are:  Emphasis is on data rather than procedurePrograms are divided into what are known as objectData structures are designed such that they characterize the object.Functions that operate on the data of on object are tied together in the data structure.Data is hidden and cannot be accessed by external functions.New data and functions can be easily added whenever necessary.Follows bottom-up approach in program design. “Object-oriented programming as an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as template for creating copies of such modules on demand”. Memory partitions are independent; the objects can be used in a variety of different programs without modifications. Object oriented programming model: It perceived the entire software system as a collections of objects which contain attributes and behaviors. BASICS CONCEPTS OF OBJECT – ORIENTED PROGRAMMING Some of the concepts used extensively in object-oriented programming. These include:  Objects  Classes  Data abstraction and encapsulation  Inheritance  Polymorphism  Dynamic binding  Message passing Object:Object is a triangle of entity that may be exhibiting some well-defined behavior. (Or) Object is an instance of Class (or) Everything is an object Objects are the basic run-time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item the program has to handle. They may be represents user- defined data such as vectors, time and lists. When a program executed, the object interact by sending messages to one another. Each object contain data, and code to manipulate the data. Fig shows two notations that are popularly used in object- oriented analysis and design. Fig – Two ways of representing an object Classes:Class is a set of attributes and behavior shared by similar objects (or) in simple way collection of objects of similar type is called a Class. The entire set of data and code of an object can be made a user-defined data type with the help of a class. Objects are variable of the type class. Once a class has been defined, we can create any number of objects belonging to that class.

Object : STUDENT

DATA

Name

Date-of-Birth

Marks

FUNCTIONS

STUDENT

Total Average Display

If fruit has been defined as a class , then the statement.

fruit apple;

will create an object apple belonging to the class fruit. Data Abstraction and Encapsulation:Abstraction focuses on the essential characteristics of objects  Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and functions to operate on these attributes.  Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT).  The attributes are sometimes called data members because they hold information. The functions that operate on these data are sometimes called methods or member functions.  Encapsulation: The wrapping up of data and function into a single unit (called class) is known as encapsulation****. The data is not accessible to the outside world, and only those functions which are wrapped in the class can access it.  This instruction of the data from direct access by the program is called data hiding or information hiding. Inheritance:Inheritance is the process by which object of one class acquire the properties of objects of another class. Create a new class derived from the old class.  It supports the concept of hierarchical classification. For example, the bird ‘robin’ is a part of the class ‘flying bird’ which is again a part of the class ‘bird’. The principle behind this sort of division is that each derived class shares common characteristics with the class from which it is derived as illustrated in fig. Fig- property inheritance  In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it.  This is possible by deriving new class from the existing one. The new class will have the combined features of both the class. Bird Attribute Features Lay eggs Robin Attribute ………… ………… Flying Bird Attribute ………… ………… Swallow Attribute ………… ………… Penguin Attribute ………… ………… Kiwi Attribute ………… ………… Non-Flying Bird Attribute …………

Polymorphism:Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to take more than one form. An operation may exhibit different behaviors in different instances.  The behavior depends upon the types of data used in the operation.  For example, consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are string, then the operation would produce a third string by concatenation.  This process of making an operator to exhibit different behaviors in different instances is known as operator overloading****.  Using a single function name to perform different types of tasks is known as function overloading. Figure illustrates that a single function name can be used to handle different number and different types of arguments. Fig. – Polymorphism Polymorphism plays an important role in allowing object having different internal structures to share the same external interface. This means that a general class of operation may accessed in the same manner even though specific actions associated with each operation may differ. Polymorphism is extensively used in implementing inheritance. Dynamic Binding:  Binding refers to the linking of a procedure call to the code to be executed in response to the call.  Dynamic Binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.  A function call associated with a polymorphic reference depends on the dynamic type of that reference. Consider the procedure “draw” in above figure by inheritance; every object will have this procedure. Its algorithms are, however, unique to each object and so the draw procedure will be redefined in each class that defines the object. Message Passing:  An object-oriented program consists of a set of objects that communicate with each other. The process of programming in an object-oriented language, therefore, involves the following basic steps: i. Creating classes that define objects and their behavior. ii. Creating objects from class definitions, and iii. Establishing communication among objects.  A message for an object is a request for execution of a procedure, and therefore will invoke a function (procedure) in the receiving object that generates the desired result. Shape Draw Circle object Draw (circle) Box object Draw (box) Triangle object Draw (triangle)

Message passing involves specifying the name of the object, the name of the function (message) and the information to be sent. Example: Employee.salary (name); Object information Message Objects have a life cycle. They can be created and destroyed. Communication with an object is feasible as long as it is alive. Benefits of OOPs: OOP offers several benefits to both the program designer and user.  Through inheritance, we can eliminate redundant code and extend the use of existing classes.The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code on other parts of the program.It is possible to have multiple instances of on object to co-exist without any interference.It is possible to map objects in the problem domain to those objects in the program.It is easy to partition the work in a project based on objects.Object-oriented systems can be easily upgraded from small to large systems.Message passing techniques for communication between objects makes the interface descriptions with external systems much simpler.Software complexity can be easily managed. Applications of OOP: Applications of OOP are beginning to gain importance in many areas. The most popular application of object-oriented programming, up to now, has been in the area of user interface design such as windows. Windows are developed using OOP techniques. OOP is simplifying the complex problem. The other areas for application of OOP includes:  Real-time systemsSimulation and modelingObject-oriented databasesHypertext, hypermedia and expertextAI and expert systemsNeural networks and parallel programmingDecision support and office automation systemsCIM/CAM/CAD systems. Object-Oriented Languages: Object-oriented programming is not the right of any particular language. Like structured programming, OOP concepts can be implemented using languages such as C and Pascal. A language that is specially designed to support the OOP concepts makes it easier to implement them. The languages should support several of the OOP concepts to claim that they are object-oriented. Depending upon the features they support, they can be classified into the following two categories:  Object-based programming Languages  Object-oriented programming Languages.  Object-based programming is the style of programming that primarily supports encapsulation and object identity. Major features that are required for object-base programming are:  Data encapsulation  Data hiding and access mechanisms  Automatic initialization and clear-up of objects  Operator overloading

Languages that support programming with objects are said to be object-based programming languages. They do not support inheritance and dynamic binding. Ada is a typical object-based programming language.  Object-oriented programming incorporates all of object-based programming features along with two additional features, namely, inheritance and dynamic binding. It’s simply Object-based features + inheritance + dynamic binding. Languages that support these features include C++ , Smalltalk and object Pascal and java. There are a large number of object-based and object-oriented programming languages. C++ STREAMS A stream is a sequence of bytes. The source stream that provides data to the program is called the input stream and the destination stream that receives output from the program is called the output stream. A program extracts the bytes from and input stream and inserts bytes into an output stream. C++ STREAM CLASSES The C++ I/O system contains a hierarchy of classes that are used to define various streams to deal with both the console and disk files. These classes are called stream classes. Fig. Stream classes for console I/O operations Class name Contents ios : Contains basic facilities that are used by all other input and output classes istream : Declares input functions. Inherits the properties of ios ostream : Declares output functions. Inherits the properties of ios iostream : Contains all the input and output functions. Inherits ios, istream and ostream classes. streambuf : Provides an interface to physical devices through buffers. Input Device Output Device Program Input Stream Output Stream Extraction from input stream Insertion into output stream Fig. Data Streams pointer istream get( ) tellg( ) read( ) overload>> ios streambuf ostream put( ) tellp( ) write( ) overload<< istream_with assign iostream iostream_with assign ostream_with assign input output

UNFORMATTED I/O OPERATIONS:

The following functions are used to implement the unformatted console I/O operations. They are the member functions of the istream and ostream classes. So, we should use the cin and cout objects with the functions. Input functions (istream class) Output functions (ostream class) overload operator >>, overload operator <<, get( ), put( ), getline( ) write( ) Overload operator>> : Used to get input from the keyboard. Syntax : cin >> var1 >> var2 >> …>> varn; Example : cin >> x >> y >> z; get( ) : This function is used to get input from the keyboard. We can use this function in two ways.

1. get(char) 2. get(void) Syntax : cin.get(var_name); Syntax : var_name = cin.get( ); Example : char c; Example : char c; cin.get(c); c = cin.get( ); getline( ) : This function is used to get a line of text as input. Syntax : cin.getline(var_name, size); Example : char name[10]; cin.getline(name, 10); Overload operator <<: This function is used to display the output on VDU. Syntax : cout << var1<< var2<< … << varn; Example : cout<< x<< y<<”Thank you”; put( ) : This function is used to display a single character as output on VDU. Syntax : cout.put(var_name); Example : char c = ‘z’; cout.put(c); write( ) : This function is used to display a line of text as output on the screen. Syntax : cout.write(var_name, size); Example : char name[10] = “Thank You”; cout.write(name, 10); FORMATTED CONSOLE I/O OPERATIONS Formatted console I/O operations are used to format the output of a program. These functions are the member functions of ios class. So, we should use the cout object for using these functions. i. width( ) ii. prescision( ) iii. fill( ) iv. setf( ) v. unsetf( ) width( ): Used to specify the required field size for displaying an output value. Syntax : cout.width(size); Example : int a = 25; cout.width(4); cout<<a; precision( ) : Used to specify the number of digits to be displayed after the decimal point of a float value. Syntax : cout.precision( size); Example : int a = 4522.123456; cout.precision( 2 ); cout<<a;

fill( ) : Used to specify a character that is used to fill the unused portion of a field. Syntax : cout.fill( arg ); Example : int a = 750 ; cout.width( 5 ); cout.fill(‘’); cout<<a; setf( ) :* Used to specify format flags that can control the form of output display (such as left-justification and right-justification) Format required Flag (arg1) Bit-field (arg2) Left-justified output Right-justified output Padding after sign or base ios::left ios::right ios::internal ios::adjustfield ios::adjustfield ios::adjustfield Scientific notation Fixed point notation ios::scientific ios::fixed ios::floatfield ios::floatfield Decimal base Octal base Hexadecimal base ios::doc ios::oct ios::hex ios::basefield ios::basefield ios::basefield Syntax : cout.setf( arg1, arg2 ); Example : char a[7] = “PRGC++”; cout.setf(ios::left, ios::adjustfield); cout.width( 10 ); cout<<a; unsetf( ) : This function is used unset the flags and bit field groups using setf( ) function. Flags that do not have bit fields : The setf( ) function can be used with the following flags as a single arguments to achieve the required output. Flag Meaning ios::showbase ios::showpos ios::showpoint ios::uppercase Use base indicator on output Print + before positive numbers Show trailing decimal point and zeroes Use uppercase letters for hex output ios::skipus Skip white space on input ios::unitbuf ios::stdio ios::Flush all streams after insertion ios::Flush stdout and stderr after insertion Example : cout.setf(ios::showpoint); Output cout.setf(ios::showpos); cout.precision(3); cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::internal, ios::adjustfield); cout.width(10); cout << 275.5 << “\n”;

Manipulators and User Defined Manipulators:

Manipulators are used to format the output. C++ has provided some predefined and user defined manipulators. There are number of predefined manipulators present in the header file ‘iomanip.h’. Two or more manipulators can be used as a chain in one statement as shown below: cout << manip1 << manip2 << manip3 << item; cout << manip1 << item1 << manip2 << item2;

* * 7 5 0

P R G C + +

Manipulators and their meanings setw () manipulator:-  Takes integer type of variable as its parameter. The parameter specifies the width of the column. Example: 1. cout<< 123<<endl; Output:

  1. cout<< setw (3) << 10; 123 10 setprecision () manipulator:  C++ displays values of float and double type with six digits by default after decimal point.  By using the setprecision () manipulator we can pass number of digits we want to display after decimal point. Example: 1. cout<<setprecision(3); Output:
  2. cout<< sqrt (3) << endl; 1.732 (the value of √3 is 1.7320508075689) setfill () manipulator:  The main task of setfill () manipulator is to fill the extra spaces left in the output of setw() manipulator with characters. Example: 1. cout<<setfill(‘*’) Output:
  3. cout<<setw (5) << 10; *10
  4. cout<<setw (5) << 257<<endl; setiosflags () manipulator:  There are two important parameter setiosflags () takes. They are ios::showpos and ios::showpoint.  When ios::showpos is passed as parameter to setiosflags () than a positive sign is prefixed to the output. Example : 1. cout<<setiosflags(ios::showpos) << 20; Output: +  When ios::showpoint is passed as a parameter than it follows the setprecision parameter (). Example : 1. cout<< setprecision(3); Output:
  5. cout<<1.7 <<endl; 1.
  6. cout<<setiosflags (ios::showpoint) 1.
  7. cout<<1.7<<endl; resetiosflags () manipulator:  This manipulator cancels the setiosflags parameter. This manipulator resets again to setiosflags () manipulator. Example: 1. cout<< setprecision (3)<<1.7<<setiosflags(ios::showpoint)<<1.7<<endl;
  8. cout<<resetiosflags(ios::showpoint)<<1.7<<endl; Output: 1.

User defined manipulators:

 The manipulators defined by the users are called as user defined manipulators.

Syntax : ostream & manipulator(ostream & output)

{

//statements//

return output;

}

Calling the user defined manipulators :

cout << name of the manipulator << list to print;

Example: ostream & unit (ostream & output)

{

output << “inches”;

return output;

}

Calling: cout << 36 << unit;

Output: 36 inches.

Example Program using setw and endl manipulators

#include

#include // for setw

int main()

{

int basic = 950, allowance=95, total=1045;

cout<<setw(10)<<”Basic”<<setw(10)<<basic<<endl;

cout<<setw(10)<<”Allowance”<<setw(10)<<allowance<<endl;

cout<<setw(10)<<”Total”<<setw(10)<<total<<endl;

return 0;

}

Output of this program is given below.

Basic 950

Allowance 95

Total 1045

UNIT - II

INTRODUCTION TO C++

C++ is an object-oriented programming language. Initially named ‘C with classes’, C++ was developed by Bjarne Stroustrup at AT& T Bell Laboratories in Murray Hill, New Jersey, USA, in the early eighties. In 1983, the name(“C with classes”) was changed to C++. The idea of C++ comes from the C increment operator ++, thereby suggesting that C++ is an incremented version of C. C++ is a superset of C. The three most important facilities that C++ adds on to C are classes, inheritance, function overloading, and operator overloading. These features enable us to create abstract data types, inherit properties from existing data types and support polymorphism, thus making C++ a truly object- oriented language. The addition of new features has transformed C from a language that to one that provides bottom-up, object-oriented design. Applications of C++: C++ is a versatile language for handling very large programs. It is suitable for virtually any programming task including development of editors, compilers, databases, communication systems and any complex real-life application systems.  Since C++ allows us to create hierarchy-related objects, we can build special object oriented libraries which can be used later by many programmers.  While C++ is able to map the real-world problem properly, the C part of C++ gives the language the ability to get close to the machine-level details.  C++ programs are easily maintainable and expandable. When a new feature needs to be implemented, it is very easy to add to the existing structure of an object. Simple C++ Program: Program Features: Like C, the C++ program is a collection of functions. The above example contains only one function, main(). Execution begin at main(). Every C++ program must have a main(). C++ is a free-form language, the C++ statements terminate with semicolons. Comments: C++ introduces a new comment symbol // (double slash). A comment may start anywhere in the line, and whatever follows till the end of the line is ignored. There is no closing symbol. The double slash comment is basically a single line comment. Multi line comments can be written follows: // this is an example file // C++ program to illustrate // some of it’s feature The C comment symbol /*, / are still valid are more suitable for multi line comments. The following command is allowed. / this is an example of C++ program to illustrates Some of it’s features */

include // include header file

int main() { cout<<” C++ is better than C.\n”; // C++ statement return 0; } // end of example

Output Operator:

The output statement  cout << “C++ is better than C.”; causes the string in quotation marks to be displayed on the screen. This statement introduces two new C++ features, cout and <<. The identifier cout(pronounced as ‘C out’) is a predefined object that represents the standard output stream in C++. The operator << is called the insertion or put to operator. It inserts (or sends) the content of the variable on it’s to the rights of the object on it’s left (figure). Object insertion operator variable Figure: Output using insertion operator The operator << is the bit-wise left-shift operator and it can still be used for this purpose. This is an example of how one operator can be used for different purposes, depending on the context. This concept is known as operator overloading.

Input operator:

The statement  cin >> number1; The operator >> is known as extraction or get from operator. It extracts (or takes) the value form the keyboard and assign it to the variable on it’s right(figure). Object Extraction Operator Variable Keyboard Figure. Input using Extraction operator

Cascading of I/O operators:

The statement  cout <<”Sum = “<<sum<<”\n”; first send the strings “Sum=” to cout and then sends the value of sum. Finally, it sends the new line character so that the next output will be in the new line. The multiple use of << in one statement is called cascading.

The iostream file:

The following #include directive in the program # include This directive causes the preprocessor to add the contents of the iostream file to the program. It contains declarations for the identifier cout and the operator <<. Some old versions of C++ use a header file called iostream.h. The header file iostream should be included at the beginning of all programs that use input/output statements.

Cout <<

<

“C++”

Cin >>

<

Return type of main(): In C++ main() returns an integer type value to the operating system. Therefore, every main() in C++ should end with a return(0) statement; otherwise a warning or error might occur. Since main() returns a integer type value, return type for main() is explicitly specified as int. the default return type for all functions in C++ is int. int main() { …… …… return 0; }

Structure of C++ program:

A typical C++ program would contain four sections as shown in figure. These sections may be placed in separate code files and then compiled independently or jointly. Fig. Structure of C++ program

TOKENS

The smallest individual units in a program are known as tokens. C++ has the following tokens:  Keywords  Identifiers  Constants  Strings  Operators. A C++ program is written using these tokens, white spaces and syntax of the language.

Keywords:

The keywords implement specific C++ language features. They are explicitly reserved identifiers and cannot be used as names for the program variables or other user-defined program elements. Some Keywords are: auto break case catch char class const continue default delete do double else enum extern float for friend goto if inline int long new operator private protected public register return short signed sizeof static struct switch template this throw try typedef union unsigned virtual void volatile while

Identifiers:

Identifiers refer to the names of variables, functions, arrays, classes, etc. created by programmer. The following rules are common to both C and C++.  Only alphabet characters, digits and underscores are permitted.  The name cannot start with a digit.  Uppercase and lowercase letters are distinct.  A declared keyword cannot be used as a variable name. Include files Class declaration Class functions definitions Main function program

Variables:

Variables are locations in the memory that can hold values. Before assigning any value to a variable, it must be declared. To use the variable number storing an integer value, the variable number must be declared and it should be of the type int as follows: int number ;

Constants:

Constants refer to fixed values that do not change during the execution of a program. Like C, C++ support several kinds of literal constants. They include integers, characters, floating point numbers and string. Example: 123 // decimal integer 12.34 // floating point integer O37 // octal integer OX2 // hexadecimal integer “C++” // string constant ‘A’ // character constant

Basic Data Types:

Data types in C++ can be classified under various categories as shown in Fig. Figure- Hierarchy of C++ data types With the exception of void, the basic data types may have several modifiers preceding them to serve the needs of various situations. The modifiers signed, unsigned, long, and short may be applied to character and integer basic data types. However, the modifier long may also be applied to double. Size and Range of C++ Basic Data types Type Bytes Range Use char 1 - 128 to +127 Used to store single character unsigned char 1 0 to 255 Used to store unsigned (positive only) single character signed char 1 - 128 to +127 Used to store signed (both positive and negative) single character int 2 - 32,768 to + 32,767 (- 215 to 2^15 - 1) Used to store integer (whole numbers) values unsigned int 2 0 to 65,535 Used to store unsigned integer (positive whole numbers) values signed int 2 - 32,768 to + 32,767 (- 215 to 2^15 - 1) Used to store signed integer (whole numbers both positive and negative) values C++ Data Types Derived type array function pointer reference User-defined type structure union class enumeration Built-in type Integer Type Void Floating type int char float double

short int 2 - 32,768 to + 32,767 (- 215 to 2^15 - 1) Used to store short integer (whole numbers) values unsigned short int 2 0 to 65,535 Used to store unsigned short integer (positive whole numbers) values signed short int 2 - 32,768 to + 32,767 (- 215 to 2^15 - 1) Used to store signed short integer (whole numbers both positive and negative) values long int 4 - 2,147,483,648 to +2,147,483,647 Used to store long integer (whole numbers) values signed long int 4 - 2,147,483,648 to +2,147,483,647 Used to store unsigned long integer (positive whole numbers) values unsigned long int 4 0 to 4,294,967,295 Used to store signed long integer (whole numbers both positive and negative) values float 4 3.4E-38 to 3.4E+38 Used to store numbers with decimal point with single precision. double 8 1.7E-308 to 1.7E+308 Used to store numbers with decimal point with double precision. long double 10 3.4E-4932 to 1.1E+4932 Used to store numbers with decimal point with more than double precision. Void: The normal use of void is (1) To specify the return type of a function when it is not returning any value and (2) To indicate an empty argument list to a function. Example: void funct1(void);

User—Defined Data Types:

Structures and Classes:

  1. struct  To store structure
  2. union  To store union C++ also permits us to define another user-defined data type known as class which can be used, just like any other basic data type, to declare variables. The class variables are known as objects. Enumerated Data Type: An enumerated data type is another user-defined type which provides a way for attaching names to numbers, thereby increasing comprehensibility of the code. The enum keyword automatically enumerates a list of words by assigning them values 0,1,2 and so on. The syntax of an enum statement is similar to that of the struct statement. Ex: enum shape { circle, square, triangle }; enum color { red, green, blue, yellow }; By default, the enumerators are assigned integer values starting with 0 for the first enumerator, 1 for the second, and so on. For example, enum color{red, blue=4, green=8}; enum color{red=5, blue, green}; are valid definitions. In first case, red is 0 by default. In the second case, blue is 6 and green is 7.

Derived Data Types:

Arrays: An array is a group of like-typed variables that are referred to by a common name. The compiler will allow declaring the array size as the exact length of the string constant. Ex : char string[3]= ”xyz”; is valid in C. It assumes that the programmer to leave out the null character \0 in the definition. But in C++, the size should be one larger than the number of characters in the string. char string[4]= ”xyz”;

Functions: It is a subprogram to reduce the size of the program and to use different places in a program for more than one time. Pointers: Pointers are declared and initialized as in C. For example int *a; it is an int pointer. a = &x; it is an address of x assigned to a. C++ adds the concept of constant pointer and pointer to a constant. char *const pt=”soft”; it is an constant pointer.

Symbolic Constants:

There are two ways of creating symbolic constants in C++.  Using the qualifier const.  Defining a set of integer constants using enum keyword. Any value declared as const cannot be modified by the program in any way. It allows us to create typed constants instead of having to use #define to create constants that have no type information. As with long and short, we can use the const modifier alone, it defaults to int. For example, To declare const a=10; (it means const int a=10). Another method of naming integer constants is as follows: enum{x,y,z}; This defines x,y and z as integer constants with values 0,1,2 respectively. This is equivalent to const x=0; const y=1; const z=2; We can also assign values to x,y and z explicitly. enum{x=100,y=200,z=300};

Type Compatibility:

C++ defines int, short int, long int as three different types. They must be cast when their values are assigned to one another. Similarly, unsigned char, char, and signed char are considered as different types. To use the sizeof, sizeof(‘x’); it will be equals to sizeof(char) and print the size of character type data

Declaration of Variables:

In C, all variables must be declared they are used in executable statements. C++ allows the declaration of a variable any where in the scope. This means that a variable can be declared right at the place of its first use. Example; int main() { float x; //declaration float sum = 0; for(int i=1;i<5;i++) //declaration { cin>>x; sum=sum+x; } float average; //declaration average=sum/i; cout<<average; return 0; }

Dynamic Initialization Variables:

C++, permits initialization of the variable at run time. this is referred to as dynamic initialization. Example: Normal declaration Dynamic Declaration ……. …… ……. …… int n; int n=strlen(string); n=strlen(string); …… float area; ……. area=3.14159radrad; float area=3.14159radrad; Dynamic initialization is extensively used in object-oriented programming. We can create exactly the type of object needed, using information that is known only at the run time.

Reference Variables:

C++ introduces a new kind of variable known as the reference variable. A reference variable provides an alias (alternative name) for a previously defined variable. For example, if we make the variable sum a reference to the variable total , then sum and total can be used interchangeably to represent that variable. The reference variable created as follows: data-type & reference-name=variable-name;

C++ assigns additional meaning to the symbol &. Here, & is not an address operator. The notation float &

means reference to float. Example, int n[10]; int & x = n[10]; // x is alias for n[10] char & a =’\n’; // initialize reference to a literal the variable x is an alternative to the array element n[10]. The variable a is initialized to the newline constant. The following reference are also allowed i. int x; ii. int &n=50; int p=&x; int &m=p; the first set of declarations causes m to refer to x which is pointed to by the pointer p and the statement in ii. Creates an int object with value 50 and name n. A major application of reference variables is in passing arguments to functions. Consider the following: void f( int & x) // uses reference { x =x+10; // x is incremented; so also m } int main() { int m=10; f(m); // function call



} when the function is call f(m) is executed, the following initialization occurs: int &x = m; such function calls are known as call by reference. Since the variable x and m are aliases, when the function increments x , m is also incremented. The value of m becomes 20 after the function is executed. one location two names x int & x = m; call m 10 int m = 10 f(m)

Operators:

C++ has a rich set of operators. All operators in C are valid in C++ also.

a. Assignment Operators b. Arithmetic Operators

c. Relational Operators d. Logical Operators

d. Bit wise Operators e. Increment/Decrement operators

f. Shortcut Operators g. Conditional Operators

h. Special operators

Assignment operators: The assignment operator is used to store the constants, variables, and result of an expression and return value of a function from right side into variable placed in left side.

Operator : = Ex : a = 6; a = b; a = b+c;

Arithmetic operators: The arithmetic operators perform the basic arithmetic operations such as addition, subtraction, multiplication, division and modulus.

The operators are : +, – , , /, % Ex : x=a+b, x=a-b, x=ab, x=a/b, x=a%b

Unary operators: The operators that work with only one operand are called as unary operators. The operators used in

C++ language are : +, – , ++, – – ,!.

Increment/Decrement operators:

The Increment operators ++ increase the value of operand by one.

The Decrement operators -- decrease the value of operand by one.

Ex : i++, ++i, i--, --i. Shortcut assignment operators: When same variable is used in both left and right side of an arithmetic expression, we can use the shortcut assignment operators.

The operators are : +=, – =, =, /=, %= Ex : a += b, a – =b, a=b, a/=b, a%=b

Sizeof and Comma operators: The sizeof operator returns the memory size occupied by an operand in terms of bytes.

Ex : a = sizeof(int) ;

The comma operator ( , ) adjoins several expressions. Ex : x = (y = 3, y + 1);

Conditional operators:

The ?: are conditional operators. They do the job done by if..else control structure.

Syntax : expression1? expression2 : expression3; Ex : big = (a>b)? a : b;

Relational operators:

The operators that do relationship tests with the operands are called relational operators.

The relational operators are:

< (less than)  Ex : if(a < b)

<= (less than or equal to)  Ex : if(a <= b)

> (greater than)  Ex : if(a > b)

>= (greater than or equal to)  Ex : if(a >= b)

== (is equal to)  Ex : if(a == b)

!= (not equal to)  Ex : if(a != b)

Logical operators: Logical operators are used when more than one relationship should be considered in evaluation. It gives either True value or False value.

AND operator : &&  AND Ex: if((a>b) && (a>c)) Truth table for AND, OR:

OR operator : ||  OR Ex: if((a>b) || (a>b))

NOT operator :!  NOT Ex: if(!(a>b))

Truth table of NOT :

A B A&&B A || B

0 0 0 0

A! A

Bit-wise operators The bit wise logical operators work with those decimal numbers in its binary form. The bit wise OR, bit wise AND, bit wise XOR, bit wise <<, and bit wise >> are binary operators. The bit wise 1’s complement is a unary operator.

Bit wise OR (|) : Ex : 0101 | 1010 = 1111

Bit wise AND(&): Ex : 0101 & 0101 = 0101

Bit wise XOR (^): Ex: 0101 ^ 1010 = 1111

Bit wise Complement(~) : If a bit is 1 , then the operator converts it into 0 and vice versa.

Ex : ~ 1010 = 0101.

Bit wise Left shift (<<) : It is used to shift the bits to the left.

Ex: x = 5 << 2; 0000 0101 = 0001 0100

Bit wise Right shift (>>) : It is used to shift the bits to the right.

Ex: x = 5 >> 2; 0000 0101 = 0000 0001

**C++ introduces some new operators. They are : << ---- insertion operator (or output operator)

---- extraction operator (or input operator) :: ---- Scope resolution operator ::* ---- pointer-to-member declarator**

- > ---- pointer-to-member operator . ---- pointer-to-member operator delete ---- memory release operator endl ---- line feed operator new ---- memory allocation operator setw ---- field width operator**

Scope Resolution Operator (::)

C++ is a block structured language. Blocks and scopes can be used in constructing programs. The same variable name can be used to have different meanings in different blocks. The scope of the variable extends from the point of its declaration till the end of the block containing the declaration. A variable declared inside the block is said to be local to that block. Example 1: Example 2:



{ { int x =10; int x = 10;



} { ----- int x = 1; ----- ----- Block 2 Block 1 { ----- int x =1; }



} } The two declarations of x refers to two different memory locations containing different values. The statement second block cannot refer to the variable x declared in the first block, and vice-versa. Block2 is contained in Block1. Note that a declaration in an inner block hides a declaration of the same variable in an outer block and therefore, each declaration of x causes it to refer to a different data object. In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves

this problem by introducing a new operator :: called the scope resolution operator.

This can be used to uncover a hidden variable. It take the following form

:: variable-name

This operator allows access to the global version of variable. ::count means the global version of the variable count. Example1: #include int m =10; //global m int main() { int m =20; // m redeclared, local to main { int k = m; int m = 30; //m declared again // local to inner block cout<<” we are in inner block \n”; cout<<”k =”<<K<<”\n”; cout<<”m =”<<m<<”\n”;

cout<<”::m =”<<::m<<”\n”;

} cout<<”\n we are in outer block\n”); cout<<”m=”<<m<<”\n”};

cout<<”::m=”<<::m<<”\n”};

return 0; } Output: We are in inner block k = 20 m = 30 ::m = 10 We are in outer block m = 20

::m = 10

Member Dereferencing Operators:

::* ----- To declare a pointer to a member of a class

  • ----- To access a member using object name and a pointer to that the member
    • ----- to access a member using a pointer to the object and a pointer to that member

Memory Management Operators:

We use dynamic allocation techniques when it is not known in advance how much of memory space is needed. Although C++ support these functions, it also defines two unary operators new and delete that perform the task of allocating and freeing the memory in a better and easier work. These operators manipulate memory on free store; they are also known as free store operators. An object can be created by using new , and destroyed by using delete. The new operator can be used to create objects of any type. It take the following general form pointer-variable = new data-type; Here, pointer-variable is a pointer of type data-type. The new operator allocates sufficient memory to hold a data object of data-type and returns the address of the object. The pointer-variable holds the address of the memory space allocated. The declaration of pointer and their assignments as follows. **int p =new int; float q = new float; When a data object is no longer needed, it is destroyed to release the memory space reuse. The general form of its use is delete pointer-varaible; the pointer-variable is the pointer that points to a data object created with new. Example delete p; delete q; The new operator offers the following advantages:

  1. It automatically computes the size of the data object. We need not use the operator sizeof.
  2. It automatically returns the correct pointer type, so that there is no need to use a type cast.
  3. It is possible to initialize the object while creating the memory space.
  4. Like any other operator, new and delete can be overloaded.

Manipulators: Manipulators are operators that are used to format the data display. The most commonly used manipulators are endl and setw. The endl manipulator, when used in an output statement, causes a linefeed to be inserted. It has the same effect as using the newline character “\n”. for example, the statement Output …….. …….. m = cout<<”m=”<<m<<endl; cout<<”n=”<<n<<endl; n = cout<<”p=”<<p<<endl; p = ……. Three lines of output, one for each variable. the values of the variable as 2597,14 and 175 respectively. The output will appear as shown below. Here, the numbers are right-justified. This form of output is possible only if we can specify common field width for all the numbers and force them to be printed right-justified. The set manipulator does this job. It is used as follows. cout<<setw(5)<<sum<<endl; The manipulator setw(5) specifies a field width 5 for printing the value of the variable sum. This value is right-justified within the field s shown below. The program illustrate the use of endl and setw. Example #include #include // for setw int main() { int basic = 950, allowance=95, total=1045; cout<<setw(10)<<”Basic”<<setw(10)<<basic<<endl; cout<<setw(10)<<”Allowance”<<setw(10)<<allowance<<endl; cout<<setw(10)<<”Total”<<setw(10)<<total<<endl; return 0; } Output of this program is given below. Basic 950 Allowance 95 Total 1045 Type Cast Operators: C++ permits explicit type conversion of variables or expression using the type cast operator. (type-name) expression //C notation type-name (expression) //C++ notation Examples: average = sum/(float) // C notation average=sum/float(i); // C++ notation For example, p=int(q); is illegal. In Such cases, we must use C type notation. p=(int)q; alterativley, we can use typedef to create an identifier of the required type and use it in the functional notation. typedef int * int_pt p=int_pt(q) 2 5 9 7 1 4 1 7 5 3 4 5

Expressions and their types:

An expression is a combination of operators, constants and variables arranged as per the rules of the language. Expressions consist of one or more operands, and zero or more operators to produce a value. Expressions may be of the following seven types:  Constant expression  Integral expression  Float expression  Pointer expression  Relational expression  Logical expression  Bitwise expression An expression may also use combinations of the above expressions. Such expressions are known as compound expressions Constant Expression: Constant expression consists of only constant values. Examples: 15 20 + 5 / 2.0 Integral Expressions: Integral expressions are those which produce integer results after implementing all the automatic and explicit type conversions. Examples: m m * n - 5 m * ’x’ 5 + int(2.0) where m and n are integer variables. Float Expressions: Float expressions are those which, after all conversions, produce floating point results. Examples: x + y x * y / 10 5 + float(10) 10.75 where x and y are floating-point variables. Pointer Expressions: Pointer expressions produce address values. examples: &m ptr ptr+1 “xyz” where m is a variable and ptr is a pointer. Relational Expressions: Relational expressions yield results of type bool which takes a value true or false. Examples: x <= y a + b == c + d m + n > 100 when arithmetic expressions are used on either side of a relational operator, they will be evaluated first and then results compared. Relational expressions are also known as Boolean Expressions. Logical Expressions: Logical expression combine two or more relational expressions and produces bool type results. Examples: a > b && x == 10; x == 10 || y == 5

Bitwise Expressions: Bitwise expressions are used to manipulate data at bit level. They are basically used for testing or shifting bits. Examples: x<<3 //shift three bit position to left y>>1 //shift one bit position to right shift operators are often used for multiplication and division by powers of two.

Special Assignment Expressions

Chained Assignment x = ( y = 10 ); or x = y = 10; First 10 assigned to y and then to x. A chained assignment cannot be used to initialize variables at the time of declaration. Embedded Assignment x = (y = 50) + 10. (y=50) is an assignment expression known as embedded assignment. Here, the value 50 is assigned to y and then the result 50 + 10 = 60 is assigned to x. Compound Assignment C++ supports compound assignment operator which is a combination of the assignment operator with a binary arithmetic operators. Example: x = x + 10 may be written as  x += 10 ; The operator += is known as compound assignment operator or short-hand assignment operator. The general form is : variable op = variable 2;

OPERATOR PRECEDENCE

Associativity defines in the case that there are several operators of the same priority level- which one must be evaluated first, the rightmost one or the leftmost one.