36
C++ M.MANOJ KUMAR M.Tech (cs) Page 1 UNIT I Object Oriented Programming Object oriented programming (oops) 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 function that operate on it, and protect it form modification from outside functions. oops allows decomposition of a problem into a number of entities called objects and then builds data and functions around those objects. The organization of data and functions in object oriented program is shown as Data Data Functions Functions Functions Data Some of the features of oops are. 1) Emphasis is on data rather than procedure. 2) Programs are divided into what are known as objects. 3) Data structures are designed such that they characterize the objects. 4) Functions that operate on the data of an object are tied together in the data structure. 5) Data is hidden and cannot be accessed by external functions.

oops 1 2 3 units

Embed Size (px)

DESCRIPTION

c++

Citation preview

C++

M.MANOJ KUMAR M.Tech (cs) Page 1

UNIT I Object Oriented Programming

Object oriented programming (oops) 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 function that operate on it, and protect it form modification from outside functions. oops allows decomposition of a problem into a number of entities called objects and then builds data and functions around those objects. The organization of data and functions in object oriented program is shown as

Data Data

Functions Functions

Functions

Data

Some of the features of oops are. 1) Emphasis is on data rather than procedure. 2) Programs are divided into what are known as objects. 3) Data structures are designed such that they characterize the objects. 4) Functions that operate on the data of an object are tied together in the data structure. 5) Data is hidden and cannot be accessed by external functions.

C++

M.MANOJ KUMAR M.Tech (cs) Page 2

6) Objects may communicate with each other through functions.

7) New data and functions can be easily added wherever necessary.

8) Follows bottom up approach in program design.

BENEFITS OF OOPs:-

OOP offers several benefits to both the program designer and the user. The principal advantages are. i) Through inheritance, we can eliminate redundant code and extend the use of existing classes ii) We can build program from the standard working module that communicate with one another, rather than having to start writing the code from scratch. This leads to saving of development time and higher productivity. iii) The principal of data hiding helps the programmer to build secure programs that cannot be invaded by code in other part of the program. iv) It is possible to have multiple instance of an object to co-exist without any interference v) It is easy to partition the work in a project, based on objects. vi) Object oriented systems can be easily upgraded from small to large systems. vii) Message passing techniques for communication between objects makes the interface description with external systems much simpler. viii) Software complexity can be easily managed

BASIC CONCEPT IN OOPS:-.

Some important concept in oops are Objects. Classes Data abstraction & Encapsulation. Inheritance Dynamic binding. Message passing.

C++

M.MANOJ KUMAR M.Tech (cs) Page 3

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 that the program has to handle. Programming problem is analyzed in terms of objects and the nature of

munication between them. Objects take up space in the memory & have an associated address like

structure in c. When a program executes, the object interacts by sending messages to one

another. Ex. If there are two objects .customer. and .account. Then the customer object may send a message to account object requesting for the bank balance. Thus each object contains data, and code to manipulate the

data. Object – Student

Data - Name Roll No. Marks

Functions: Total average Display

Classes:- 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 actually variable of the type class. Once a class has been defined, we can create any number of objects

belonging to that class. Thus a class is collection of objects of similar type. Classes are user defined data types and behaves like the built in type of a

programming language. The syntax for defining class is

class class-name { ---------------- ---------------- }

C++

M.MANOJ KUMAR M.Tech (cs) Page 4

Data abstraction and Encapsulation:- The wrapping up of data and functions 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. These functions provide the interface between the objects data and the

program. This insulation of the data from direct access by the program is called data hiding or information hiding.

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 coast, and functions to operate on these attributes.

Inheritance:- Inheritance is the process by which object of one class acquire the

properties of objects of another class. In OOPs, 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 a new class from the existing one.The new class will have combined features of both the classes.

Types of inheritance: Inheritance is classified into the following forms based on

the level of inheritance and the relationship among the classes involved in the

inheritance process.

1. Single Inheritance

2. Multiple Inheritance

3. Hierarchical Inheritance

4. Multi Level Inheritance

5. Multi Path Inheritance

6. Hybrid Inheritance

C++

M.MANOJ KUMAR M.Tech (cs) Page 5

1. Single Inheritance: Derivation of a class from only one base class is called

single inheritance. The following shows the single inheritance.

2. Multiple inheritance: Derivation of a class from several (one more) base classes is called multiple inheritance. The following diagram shows the multiple inheritance

3. Multiple inheritances: Derivation of a several classes from a single class is

known as hierarchical inheritance. The following diagram shows the hierarchical

inheritance. A BASE CLASS

B C D DERIVED CLASS

A B

C

BASE CLASS

DERIVED CLASS

A

B

PARENT CLASS

CHILD CLASS

C++

M.MANOJ KUMAR M.Tech (cs) Page 6

4. Multi level Inheritance: Derivation of a class from another derived class is called Multi level inheritance. The following diagram shows the multi level inheritance A SUPER BASE CLASS

B BASE CLASS

C DERIVED CLASS

5. Multi path Inheritance: Derivation of a class from another derived classes

which are derived from the same base class is called multi path inheritance. The

following diagram shows the process of multi path inheritance.

A BASE CLASS

B C

D DERIVED CLASS

6. Hybrid Inheritance: Derivation of a class involving more than one form of

inheritance is known as hybrid inheritance. The following diagram shows the

hybrid inheritance. A B C BASE CLASS

D DERIVED CLASS

C++

M.MANOJ KUMAR M.Tech (cs) Page 7

Polymorphism:- Polymorphism is important oops concept. It means ability to take more than

one form. In polymorphism an operations may shows different behavior in different

instances. The behavior depends upon the type of data used in the operation. For Ex- Operation of addition for two numbers, will generate a sum. If the operands are strings, then the operation would produce a third string by

Concatenation. The process of making an operator to show different behavior in different

instance is called as operator overloading. C++support operator overloading Shape Draw ()

Circle Box Triangle Draw (Circle) Draw (Box) Draw (Triangle) The above figure shows concept of function overloading. Function overloading means using a single function name to perform different types of tasks. Dynamic Binding:- Binding referes to the linking of a procedure call to the code to be executed

in response to the call. Dynamic binding means that the code associated with a given procedure call

is not known until the time of the call at run time. Message Passing:- OOPs consist of a set of objects that communicate with each other. Message passing involves following steps

i) Creating classes that define objects and their behavior ii) Creating objects from class definitions and

A message for an object is a request for execution of a procedure & therefore will invoke a function in the receiving object that generates the desired result.

Message passing involves specifying the name of the object, the name of the function i.e. message and the information to be sent. Ex customer.balance (account no) object message information

C++

M.MANOJ KUMAR M.Tech (cs) Page 8

Meaning of Object:-

Object is a representation of some information Name Values or properties

– Data members Ability to react to requests (messages)!!

– Member functions When an object receives a message, one of two actions are

performed Object is directed to perform an action Object changes one of its properties

Fundamental C++ Objects

C++ has a large number of fundamental or built-in object types The fundamental object types fall into one of three categories Integers objects Floating-point objects Character objects

Z, 5, 1, P, 1.28345, 3.14 Integer Object Types

The basic integer object type is int The size of an int depends on the machine and the compiler

– On PCs it is normally 16 or 32 bits Other integers object types

Short: typically uses less bits Long: typically uses more bits

Different types allow programmers to use resources more efficiently

Standard arithmetic and relational operations are available for these types

Floating-point objects Floating-point object types represent real numbers Integer part Fractional part The number 108.1517 breaks down into the following parts

C++

M.MANOJ KUMAR M.Tech (cs) Page 9

108 - integer part 1517 - fractional part C++ provides three floating-point object types Float Double Long double

Character Object Types Character type char is related to the integer types Characters are encoded using a scheme where an integer

represents a particular character ASCII is the dominant encoding scheme Examples

– ' 'encoded as 32 – '+' encoded as 43 – 'A' encoded as 65 – 'Z' encoded as 90 – 'a' encoded as 97 – 'z' encoded as 122 Meaning class:- Class: A class is a user defined data type which binds data and its associated functions together. It allows the data and functions to be hidden, if necessary from external use. Generally, a class specification has two parts. i) Class declaration: it describes the type & scope of its members. ii) Class function definitions: It describes how the class functions are implemented.

Class declaration. The general form of a class is class class-name { Private: Variable declaration; Function declaration; public: Variable declaration; Function declaration; } ; 1) The class keyword specifies that what follows is an abstract data of type class name. The body of a class is enclosed within braces &terminated by semicolon.

C++

M.MANOJ KUMAR M.Tech (cs) Page 10

2) The class body consists of declaration of variables & functions which are called as members & they are grouped under two sections i.e.private & public. 3) Private and public are known as visibility labels, where private canbe accessed only from within the class where public members can be accessed from outside the class also. By default, members of aclass are private. 4) The variable declared inside the class are known as data members& functions are known as member functions. Only the member function can have access to the private data members & private functions. However the public members can be accessed from outside the class. Simple class example

Class item { Int number; variable Float cost; declaration Public: Void getdata (int a, float b); function Void putdata (void); declaration } In above class class-name is item. These class data members are private by default while both the functions are public by declaration. The function getdata () can be used to assign values to the member variable number &cost, and putdata () for displaying their values. These functions provide theonly access to data members of the class. Polymorphism:-

Polymorphism is important oops concept. It means ability to take more than one form.

In polymorphism an operations may shows different behavior in different instances. The behavior depends upon the type of data used in the operation. Polymorphism classified in to two types

Compile time polymorphism Runtime polymorphism

C++

M.MANOJ KUMAR M.Tech (cs) Page 11

Polymorphism Compile time polymorphism Runtime polymorphism

Function Overloading Operator Overloading Virtual function

Compile time polymorphism Action can be performed at compile time is called compile time polymorphism Compile time polymorphism classified in to two types Function Overloading Operator Overloading Function Overloading:- In function overloading function name is same, number of arguments and type of arguments are different Operator Overloading:- An operator overloading is a compiler time polymorphism, operator overloading defind as provided exiable operations on user defined data types an operator overloading represents as Syntax:-return type operator symbol of operator { --- --- } Run time polymorphism:- An action can be performed at run time is called run time polymorphism or dynamic polymorphism Run time polymorphism is classified in to Virtual function. Method overriding (or) Function overriding:- A method overriding defined as base class and derived class are having same method name, when we are creating object for derived class, every time derived class method hidden base class method. Virtual function:- It is run time polymorphism concept base class and derived class having same method.(or)member function when we are creating object for derived class compile does not identified which method is executed. This is known as ambiguity [two same names]. This is over come by virtual functions. Virtual functions can be

C++

M.MANOJ KUMAR M.Tech (cs) Page 12

declared by using virtual keyword, virtual key word reprojected basic class member function. Syntax:- virtual return type member function name( ) { --- --- } Defining a Function:

The general form of a C++ function definition is as follows:

return_type function_name( parameter list ) { body of the function }

A C++ function definition consists of a function header and a function body. Here are all the parts of a function:

Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.

Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

Function Body: The function body contains a collection of statements that define what the function does.

Calling a Function:

While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.

When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is

C++

M.MANOJ KUMAR M.Tech (cs) Page 13

executed or when its function-ending closing brace is reached, it returns program control back to the main program.

To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example:

Function Arguments:

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways that arguments can be passed to a function:

Call Type Description

Call by value

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

Call by pointer

This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

Call by reference

This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

C++

M.MANOJ KUMAR M.Tech (cs) Page 14

By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.

Default Values for Parameters:

When you define a function, you can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function.

This is done by using the assignment operator and assigning values for the arguments in the function definition. If a value for that parameter is not passed when the function is called, the default given value is used, but if a value is specified, this default value is ignored and the passed value is used instead.

There may be a situation, when you need to execute a block of code several number of times. In general statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated execution paths.

Loop characteristics:-

A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages:

C++

M.MANOJ KUMAR M.Tech (cs) Page 15

C++ programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.

Loop Type Description

while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

for loop Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

do...while loop Like a while statement, except that it tests the condition at the end of the loop body

nested loops You can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements:

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

C++ supports the following control statements. Click the following links to check their detail.

Control Statement Description

break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

goto statement Transfers control to the labeled statement. Though it is

C++

M.MANOJ KUMAR M.Tech (cs) Page 16

not advised to use goto statement in your program.

The Infinite Loop:

A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Software reusability:-

Reuse of existing software components increase the quality and productivity in software development and maintenance. Software reuse reduces the amount of software that needs to be produced from scratch and hence less testing time for new software C++ templates are used to support the concept of reusability in object-oriented programming. An object-oriented software system is a collection of classes which are abstract data types and templates are a way of making classes more abstract without actually knowing what data type will be handled by the operations of the class. The ability to have a single class that can handle several different data types means the code is easier to maintain, and it makes classes more reusable. This raises questions about how generic programming included in the form of templates in the code can be measured to identify effectiveness of this reuse strategy. The measurement of reuse would help developers to monitor current levels of reuse and provide insight in developing software that is easily reused

C++

M.MANOJ KUMAR M.Tech (cs) Page 17

Creation of new data type:- In c++ has added two new data types to enhance the range of data types available in C++. They are bool and wchar_t. The bool data type :- The data type bool has added to hold a Boolean value, true or flase. The values true and false have been added as keywords to the C++ language.the bool type variables can be declared as follows Bool b1; //declare b1 as bool type B1=true; //assign true value to it Bool b2 =false //declare and initialize The default numeric value of true is 1 and false is 0.it is possible to convert implicitly the data types pointers, integers or floating point values to bool type. The Wchar_t data type: The character type wchar_t has been defined in C++ to hold 16-bit wide characters. The 16-bit characters are used to represent the character set of languages that have more than 255 characters, such as Japanese. This is important if we are writing programs for international distribution. C++ also introduces a new character literal known as wide_character literal which uses two bytes of memory. Wide_character literals begin with the letter L, as follows: L’xy’//wide_character literal.

C++ is an object oriented programming language developed by Biarne stroustrup at & T Bell laboratories.

C++ is an extension of c with a major addition of the class constructfeature. # include<iostream.h> int main() { cout<<.Hello Wold.; return 0; }

C++ program is a collection of functions. Every C++ program must have a main() function.

The iostream file:- The header file iostream should be included at the beginning of all programs that uses one output statement.

C++

M.MANOJ KUMAR M.Tech (cs) Page 18

Input / Output operator 1. Input Operator cin: - The identifier cin is a predefined object in c++ that corresponds to the standard input stream. Here this streamrepresents keyboard. Syntax:- cin>>variable; The operator >> is known as extraction or get from operator &assigns it to the variable on its right. 2. Output operator cout:-The identifier cout is predefined object that represents the standard output stream in c++. Here standard output stream represents the screen. Syntax:- cout<<string; The operator << is called the insertion or put to operator. It inserts the contents of the variable on its right to the object on its left. 3. Return type of main():- In C++, main returns an integer type value to the operating system. So return type for main() is explicitly specified as int. Therefore every main() in c++ should end with a return 0 statement.

C++

M.MANOJ KUMAR M.Tech (cs) Page 1

UNIT II C Versus C++

C++, as the name suggests, is a superset of C. As a matter of fact, C++ can run most of C code while C cannot run C++ code. Here are the 10 major differences between C++ & C.

Basic Introduction:

C++ is derived from C Language. It is a Superset of C. Earlier C++ was known as C with classes. In C++, the major change was the addition of classes and a mechanism for

inheriting class objects into other classes. Most C Programs can be compiled in C++ compiler. C++ expressions are the same as C expressions. All C operators are valid in C++.

Following are the differences Between C and C++:

C C++

1. C is Procedural Language. 1. C++ is non Procedural i.e. Object oriented Language.

2. No virtual Functions are present in C

2. The concept of virtual Functions are used in C++.

3. In C, Polymorphism is not possible. 3. The concept of polymorphism is used inC++.Polymorphismisthe most Important Feature of OOPS.

4. Operator overloading is not possible in C.

4. Operator overloading is one of the greatest Feature of C++.

5. Top down approach is used in 5. Bottom up approach adopted in

C++

M.MANOJ KUMAR M.Tech (cs) Page 2

Program Design. Program Design.

6. No namespace Feature is present in C Language.

6. Namespace Feature is present in C++ for avoiding Name collision.

7. Multiple Declaration of global variables are allowed.

7. Multiple Declaration of global variables are not allowed.

8. In C

Scanf () Function used for Input.

Printf () Function used for output.

/* hello.c */ #include <stdio.h> int main(){ printf("Hello world\n"); return 0;

}

8. In C++

Cin>> Function used for Input. Cout<< Function used for output.

// hello.cc #include <iostream> using namespace std; int main(){ cout << "Hello world" << endl; return 0; }

9. Mapping between Data and Function is difficult and complicated.

9. Mapping between Data and Function can be used using "Objects"

10. In C, we can call main() Function through other Functions

10. In C++, we cannot call main () Function through other functions.

11. C requires all the variables to be defined at the starting of a scope.

11. C++ allows the declaration of variable anywhere in the scope i.e at time of its First use.

12. No inheritance is possible in C. 12. Inheritance is possible in C++

C++

M.MANOJ KUMAR M.Tech (cs) Page 3

13. In C, malloc () and calloc () Functions are used for Memory Allocation and free () function for memory Deallocating.

13.In C++, new and delete operators are used for Memory Allocating and Deallocating.

14. It supports built-in and primitive data types.

14. It support both built-in and user define data types.

15. In C, Exception Handling is not present.

15. In C++, Exception Handling is done with Try and Catch block

BASIC DATA TYPES IN C++

C++ Data Types User defined type Built in type Derived type Structure Array array Union Function function Class Pointer pointer Enumeration reference Integral Type void Floating type int char Float double

Data Type– A set of valid data values along with the operations that may be performed on those values. The C++ data types we will use in this class are as follows Char- One alphanumeric character enclosed in single quotes. ‘a’ ‘!’ ‘C’ ‘$’ ‘x’ ‘*’

C++

M.MANOJ KUMAR M.Tech (cs) Page 4

Int- Positive or negative integers with or without a sign (commas are not allowed) 23 -5 6 -100 0 etc. Float- Positive or negative numbers containing an integer part and a fractional part with a decimal point in between. 9.5 4. 37895.75 .8 0.5 etc. Type Keyword Boolean bool Character char Integer int Floating point Float Double floating point double

Valueless void Wide character Wchar t

Several of the basic types can be modified using one or more of these type modifiers:

signed unsigned short long

Type Typical Bit Width Typical Range

char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

C++

M.MANOJ KUMAR M.Tech (cs) Page 5

short int 2bytes -32768 to 32767

unsigned short int Range 0 to 65,535

signed short int Range -32768 to 32767

long int 4bytes -2,147,483,647 to 2,147,483,647

signed long int 4bytes same as long int

unsigned long int 4bytes 0 to 4,294,967,295

float 4bytes +/- 3.4e +/- 38 (~7 digits)

double 8bytes +/- 1.7e +/- 308 (~15 digits)

long double 8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t 2 or 4 bytes 1 wide character

Input statements

The extraction operator >> is used for general input of variable values. The

extraction operator is defined for all the built-in basic C++ types. It is possible to

input values for multiple variables in the same statement by chaining them together

with the extraction operator. For each occurrence of >> you must supply the name

of the variable where you want the input value assigned (a statement can’t end with

>>).

cin >> value1 >> value2; is the same as cin >> value1; cin >> value2; Rules for how C++ reads different types of values:

int

Skip any leading spaces or blank lines, read digits until encountering a character that is not valid in an integer value, like a blank space or a special character, or a decimal point, or a letter, or the end

C++

M.MANOJ KUMAR M.Tech (cs) Page 6

of the line (result of pressing Enter)

double

Skip any leading spaces or blank lines, read digits until encountering a character that is not valid in a floating-point value, like a blank space or a special character other than a decimal point, or a letter, or the end of the line.

char

Skip any leading spaces or blank lines and read the first non-blank character encountered.

string

Skip any leading spaces or blank lines and read characters until encountering a blank space or the end of the line.

When you’re reading from the keyboard, you should precede your input statements with output statements explaining what it is that your program is expecting the user of the program to enter – these are called prompting messages. Otherwise, the cursor will be blinking on the output screen, but the user of the program has no way of knowing what the program is waiting for. Prompting messages should be brief because people tend not to read instructions very well. Sometimes it helps to give the user an example of the input the program expects rather than to try and write out a long detailed description .Some knowledge about the anticipated users of your program may give you an idea of the amount of detail that would be necessary or desirable in your instructions. You can input the values your program needs in any order you want and in any combination you want (one at a time, two at a time, etc.). I strongly recommend reading only one value at a time because it greatly simplifies the instructions and possibly helps to prevent errors by the user while keying the input values. If you expect the user to enter multiple values

C++

M.MANOJ KUMAR M.Tech (cs) Page 7

without additional instructions in between values, then you probably need to explain about the spacing required. If you’re only asking for one value at a time, spacing isn’t a problem.

Output statement

The insertion operator << is used for general output. It has been defined to

Output values in a default format for all of the built-in basic C++ types. Each

occurrence of << must be followed by a value to be printed or a manipulator

that affects the state of the output stream (a statement can’t end with <<).

It is possible to output multiple values in the same statement by chaining them

together with the << (insertion) operator:

Cout << value1 << value2; is the same as cout << value1;cout << value2;

Where the variables (or constants or expressions) may be of any of the built-in

Basic types.

The insertion operator converts values to text form. By default, values are displayed in a width equal to their size and formatted as follows:

char

A type char value, if it represents a printable character, is displayed as a character in a field one character wide.

int

Numeric integer values are displayed as decimal integers in a field just wide enough to hold the number and, if the value is negative, a leading minus sign.

double

The exact format of floating-point output varies by

C++

M.MANOJ KUMAR M.Tech (cs) Page 8

compiler. Typically, values with a non-zero fractional part are displayed with 6 digits to the right of the decimal. Trailing fractional zeros aren't displayed. If there are no significant digits to the right of the decimal point, printing of the decimal point is suppressed along with the trailing zeros. Depending on the compiler, the final fractional digit printed may be rounded or the excess digits simply truncated. The number may be displayed in E-notation, depending upon the value of the number (which depends on the compiler being used). Again, the field is just wide enough to hold the number and, for a negative value, a leading minus sign.

string

Strings are displayed in a field width equal in width to the length of the string.

OPERATORS IN C++

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provides the following types of operators:

Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Arithmetic Operators:

There are following arithmetic operators supported by C++ language

C++

M.MANOJ KUMAR M.Tech (cs) Page 9

Operator Description Example + Adds two operands A + B will give 30 - Subtracts second operand from the first A - B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by de-numerator B / A will give 2 % Modulus Operator and remainder of after an B % A will give 0 Integer division ++ Increment operator, increases integer value by one A++ -- Decrement operator, decreases integer value by one A--

Relational Operators: There are following relational operators supported by C++ language

Operator Description Example == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not, if values are not equal then condition (A != B) is true. becomes true. > Checks if the value of left operand is greater than the value of rig ht operand, if yes then (A > B) is not true. condition becomes true. < Checks if the value of left operand is less than the value of rig ht operand, if yes then condition (A < B) is true. becomes true. >= Checks if the value of left operand is greater than or equal to the value of rig ht operand, if (A >= B) is not true. yes then condition becomes true. <= Checks if the value of left operand is less than

or equal to the value of rig ht operand, if yes (A <= B) is true. then condition becomes true.

C++

M.MANOJ KUMAR M.Tech (cs) Page 10

Logical Operators: There are following logical operators supported by C++ language

Operator Description Example && Called Logical AND operator. If both the operands are non-zero, then condition

becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true. ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(A && B) is true.

Bitwise Operators: Bitwise operator works on bits and perform bit-by-bit operation. T he truth tables for &, |, and ^ are as follows

Operator Description & Binary AND Operator copies a bit to the result if it exists in both operands. Example (A & B) will give 12 which is 0000 110 | Binary OR Operator copies a bit if it exists in either operand. Example (A | B) will g ive 61 which is 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. Example (A ^ B) will g ive 49 which is 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of 'flipping ' bits. Example (~A ) will give -61 which is 1100 0011 in 2's complement form due to a sig ned binary number. << Binary Left Shift Operator. T he left operands

C++

M.MANOJ KUMAR M.Tech (cs) Page 11

value is moved left by the number of bits specified by the right operand. Example A << 2 will give 240 which is 1111 0000 >> Binary Rig ht Shift Operator. T he left operands value is moved rig ht by the number of bits specified by the rig ht operand. Example A >> 2 will give 15 which is 0000 1111

Assignment Operators: There are following assignment operators supported by C++ language:

Operator Description = Simple assignment operator, Assigns values from rig ht side operands to left side operand Ex: - C = A + B will assign value of A + B into C += Add AND assignment operator, It adds rig ht operand to the left operand and assign the result to left operand Ex:- C += A is equivalent to C = C + A -= Subtract AND assignment operator, It subtracts rig ht operand from the left operand and assign the result to left operand Ex:- C -= A is equivalent to C = C - A *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Ex:- C *= A is equivalent to C = C * A /= Divide AND assignment operator, It divides left operand with the rig ht operand and assign the result to left operand Ex:- C /= A is equivalent to C = C / A %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand Ex:- C %= A is equivalent to C = C % A <<= Left shift AND assignment operator C <<= 2 is same as C = C << 2 >>= Rig ht shift AND assignment operator Ex:- C >>= 2 is same as C = C >> 2

C++

M.MANOJ KUMAR M.Tech (cs) Page 12

&= Bitwise AND assignment operator Ex:- C &= 2 is same as C = C & 2 ^= bitwise exclusive OR and assignment operator Ex:- C ^= 2 is same as C = C ^ 2 |= bitwise inclusive OR and assignment operator Ex:- C |= 2 is same as C = C | 2

Misc Operators There are few other operators supported by C++ Language. Operator Description Size of size of operator returns the size of a variable. For example, sizeof(a),here a is integer, will return 4. Condition? X : Y Conditional operator. If Condition is true ? then it returns value X : otherwise value Y , Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list. . (dot) and -> (arrow) Member operators are used to reference individual members of classes, structures, and unions. Cast Casting operators convert one data type to another. For example, int(2.2000) would return 2. & Pointer operator & returns the address of an variable. For example &a; will give actual address of the variable. * Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.

C++

1 M.MANOJKUMAR M.Sc, M.Tech.

Unit IV Programming Constructs

The unary operators operate on a single operand and following are the example of Unary operators. The increment (++) and decrement (--) operators. The unary minus (-) operator. The logical not (!) operator. The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as !obj,-obj, and ++obj but sometime they can used as postfix as well obj++ or obj--. C++ allows you to specific more than one definition for a function name or an operator in the same cope, which is called function overloading and operator overloading respectively.

Constructor:-

Special Member Function used for Initialization -- Same Name as the Class Name Does NOT Return a Value Cannot be virtual and static Implicitly Invoked When Objects are Created or Copied Can Have Arguments Cannot be Explicitly Called Multiple Constructors are Allowed Default Constructor -- No Arguments -- Explicit or Implicit Copy Constructor -- Explicit or Implicit.

Prefix Notation:-

Instead of saying "A plus B", we could say "add A,B " and write

+ A B

"Multiply A,B" would be written

* A B

This is Prefix notation.

Postfix Notation:-

Another alternative is to put the operators after the operands as in

A B + and A B *

This is Postfix notation.

Increment and Decrement Operators

• Increment operator (c++) - can be used instead of

c += 1

C++

2 M.MANOJKUMAR M.Sc, M.Tech.

• Decrement operator (c--) - can be used instead of

c -= 1

• Preincrement

• When the operator is used before the variable (++c or –c)

• Variable is changed, then the expression it is in is evaluated.

• Posincrement

• When the operator is used after the variable (c++ or c--)

• Expression the variable is in executes, then the variable is changed.

Switch:-

Switch Useful when variable or expression is tested for multiple values.

Consists of a series of case labels and an optional default.

Case break is (almost always) necessary.

Switch Statement:-

The purpose of switch statement is to select single option into a multiple options. Switch (expression) { Case label 1: Statements Breaks; Case label 2: Statements; Break; …… Case label n; Statements; Break; case terminated Default; Statements;

}

C++

3 M.MANOJKUMAR M.Sc, M.Tech.

Flow chart:-

Exp1 Exp2 Exp3 default

LOOPS (Iteration statements):-

Iteration means operated process. In iteration statements depending upon given condition. Body of the loop executed continuously. This is also known as loop.

Loops can be classified into

While loop

Do-While

For loop

While loop:-

While loop is a control statement it can be executed depending upon given condition. In While loop first check the condition, if the condition is true body of the loop executed ,once again check the while condition if the condition is true body of the loop executed once. This process is continue until condition is false.

Syntax:- While (condition)

{

Body of loop;

}

SWITCH

EXPERSSION

Statement Statement Statement Statement Exit

C++

4 M.MANOJKUMAR M.Sc, M.Tech.

Flow Chart:-

False

True

Do –While:-

Do-while is a iteration statement in a Do-while first body of the loop executed and next check the condition ,if the condition is true body of the loop executed once, this process is repeated until condition is false. In Do –While first time condition is false body of the loop executed once again i.e., Do-While is a exit control loop.

Syntax:- Do

{

Body of the loop;

}

While (condition);

Flowchart:-

False True

WHILE LOOP

CONDITION

Next statement

Body of loop

Body of loop

Condition

Next statement

C++

5 M.MANOJKUMAR M.Sc, M.Tech.

For loop:-

For loop is iteration statement it depending upon given condition to executed group of statements repeatly. The For loop contains initialization part condition part and increment part.

Syntax:-

For (initialization; condition; increment) statement;

{

Statements;

}

Here statement part contains either single statement ( ) or group of statements. Statement part contains single statement braces are optional statement part contains group of statement.

Difference between While and DO-While:-

While Do-While

While is a entry control loop. Do-While is a exit control loop.

While loop is a iterative statement It is similar to while loop.

Depending upon given condition,

Body of the loop executed.

In while loop first check the condition. In Do-While first execute the body of the loop and

If the condition is true body of the loop next check the condition.

Executed repeatly.

In while loop at the first time condition in Do-While first time if the condition is false

Is true the body of the loop can executed. Once body of the loop executed.

If while condition is true body of the loop This is similar to while loop.

Executed and once again check the

Condition if the condition is true body

of the loop executed. This procedure is

repeated until condition is false.

C++

6 M.MANOJKUMAR M.Sc, M.Tech.

Syntax: Syntax:

While (condition) Do

{ {

Body of loop body of loop

} }

While (condition)

Flowchart:- Flowchart:-

While condition body of loop

True true

False Body of loop false condition

Next statement

Ex:- ex:-

While (n! =0) do

{ {

D=n%10; d=n%10;

Sum=sum+d; sum=sum+d;

N=n/10; n=n/10;

} }

The body of the loop While (n!=0) This is similar to while

Contains group of statement

It is known as compound

Statements.

Next statement