Sei sulla pagina 1di 140

G.R Solutions Design and Developed by Mr.

Goutam Sontakke (Software Developer)

Programming Logic:
Problem Analysis/Problem Definition:
The first step in programming is to define the problem and understand it. Only then we can identified the exact problem and develop clear logic to solve that problem. This logic can then be used to create a computer application. Therefore, it is necessary to carefully assess the problem and identify the causes of the problem for us. Problem definition requires identification of the following: 1. Tasks 2. Objects 3. Events Following figure display the input and output object of HRA automation program.

Where: calculate HRA and Exit are Action Objects.

Process Analysis:
After defining the problem clearly, the user interface will created. The user interface is almost a replica of the sketch depicted the objects shown in above figure. While designing an interface we need to ensure that the interface should be easy to understand and well structured. Case study: The diagram of the HRA automation system describes the objects of the problem as shown in figure. The figure shows that a control is needed to accept the basic salary of the employees and one control to display the HRA. And two buttons is needed to calculate HRA and Exit from application environment.

Conceptual development of solution:


Logical development for actions is one of the most important steps of programming approach. This step defines the events associated with each object and identifies the way our objects should respond to particular events. Programming used two tools that help in logic development for the action objects: Input processing/output (IPO) tables and Pseudocode Following table show input to an object, the output from an object, and the processing required for converting the input to the desired output. After creating IPO table, we can write pseudocode procedure. A Pseudocode provides the link between an IPO table and the computer code for the action objects. Psedocode will replace the English statements with the equivalent instruction in a programming language. INPUT PROCESSING OUTPUT

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Basic Salary HRA=17%*basic salary HRA Table: IPO Table void main () { int basic, hra; cin>>basic; hra=0.17*basic; cout<<basic; } After this step we first test our application under each and every condition. Debugging and testing our application. In the last create Documentation for our application.

Development Tools:
Algorithm:
Algorithm is a step by step instruction of a program. It is a finite set of step by step instructions that solve a problem. After defining the problem, we can create algorithms of our application. Ex: short paper planning of any program. Computer program is another example of an algorithm. Every computer program is a set of series in specific order, designed to perform a specific task. Ex: Algorithm for largest no out of two no: 1. Start 2. Read no x and y from user 3. Check x>y if yes go to step 4 otherwise goto step 5 4. Print X is largest. Goto step 6 5. Print y is largest 6. Stop Advantage: 1. An algorithm is generally written in spoken language and not in any programming language so hence it is easy to understand. 2. Also written an algorithm helps eliminate any error in our problem solving logic, so that when we start programming we worry only about the language specific issues. 3. Easy to understand 4. It support in writing program. Disadvantage: 1. Algorithms are only as good as the instruction given. However, and the result will be incorrect if the algorithm is not properly defined. 2. Difficult to depict complex programming steps. 3. Most of the programmers write algorithm after writing the program; which fails the purpose of algorithm.

Flowcharts:
Flowchart is a pictorial representation of the steps involved in the procedure. It also shows the logical sequence, in which the steps are performed. The flowchart is drawn by programmer to ensure the accuracy of their interpretation of the logic required in the program. Flowchart is a common type of chart that represents an algorithm or process using different boxes and their arrows. Flowcharts are used in analyzing, designing, documentation or managing a process or program in various fields.

Advantage of flowchart:
1. Clarify the program logic.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) 2. Before coding begins, the flowcharts assist the programmer in determining the type of logic control to be used in a program. 3. Serve as documentation. 4. Serve as guide for program coding or program writing. 5. The flowchart is pictorial representation that may be useful to the business person or user who whishes to examine some aspects of the logic used in the program.

Disadvantage of flowchart:
1. Flowchart is a cumbersome for the programmer to write. As a result, many programmers do not write the chart until after the program has been completed, which defect one of the main process. 2. Flowchart is no longer completely standardized tool. 3. Some time it is not easily understood by common person and businessman. Symbol Function Arrows Oval Meaning Direction of logic or flow Start/stop

Rectangle

Processing/calculation

Diamond shape

Decision

Circle

connector

Rhombus

Input/output

Pseudocode:
It is a tool used to formulate the processing steps of a program. Pseudocode uses English word to describe the processing steps of program or module. The logic control instructions within a structured design are emphasized in pseudocode. Ex: MOV is used for move, ADD is used for addition, and SUB is used for subtraction.

Advantage:
1. 2. 3. 1. 2. 3. As compared to a flowchart, converting a pseudocode into a programming language is much easier. As compared to a flowchart, it is easier to modify the pseudocode of program logic when program modifications are necessary. Writing of pseudocode involves much less time and effort than drawing an equivalent flowchart. In case of pseudocode, a graphic representation of program logic is not available. There are no standard rules to follow in writing pseudocode. Different programmer uses their own style of writing pseudocode. Hence communication problem occur due to lack of standardization. For beginner, it is difficult to follow the logic of pseudocode or write pseudocode as compared to flowcharting.

Disadvantage:

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Programming structure:
Programming structure is also called as control structure. And it is using only the following three simple logic (control) structures: 1. Sequence logic 2. Selection logic 3. Iteration (or looping) logic

Sequence logic:
In sequence logic, instructions are arrange in one after another in sequence. Thus in sequence logic, Pseudocode instruction are written in order, one after another from top to bottom.

Process 1

Process 2

(a) Flowchart
. . . Process 1 . . . Process 2

(b) Pseudocode

Selection Logic:
Selection logic also known as decision logic, used for making decision. It is used for selecting the proper path out of two or more alternative path in program logic. Selection logic is classified into: If.then Ifelse Case structure

No
If (condition)

Yes
Process 1

Process 2

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

a) Flowchart : If condition Then process 1 Else process 2 End if : b) Pseudocode

Iteration (or Looping):


Iteration means repeated one statement again and again. Hence Iteration logic is used to produce loops in program logic when one or more instructions may be executed several times depending on some condition. It Uses structure: DO.WHILE REPEAT.UNTIL FOR LOOP WHILE LOOP

no
Condition

yes
Process 1

Process n a) flowchart : Repeat Process1 Process n Until condition : : b) Pseudocode

Language Evolution:
Before discussing about Language, it is necessary for us know about what is Computer? What is computer Programming? Computer: it is an electronic machine which can solve mathematical and logical problem. But computer can not solve problem itself. It must be programmed for finding the solution of that problem. Program: A program is a set of instructions in some specific language to solve any problem. Here specific computer means any computer language that computer can understand. There are so many computer languages available for computer programming such as basic, Pascal, COBOL, c, c++, java etc.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Types of programming languages: 1) Low level language: Low level language is also called as Machine Language or binary language which is collection of very detailed instructions that control the computer internal circuits. It is machine dependent. Very few programs are written in this language because computers have their own instruction set. It is in the form of 0s and 1s. A machine language instruction normally has a two parts format. The first part is operation code that tells the computer what function to perform, and the second part is operand that tells where to find or store the data to be manipulated. OPCODE OPERAND (operation code) (address/location) (Instruction format)

Advantage:
Programs written in machine language can be executed very fast by a computer because machine instructions are understood by the computer without using any translator.

Limitation of machine language:


1) Machine dependent 2) Difficult to program 3) Error prone 4) Difficult to modify 2) Assembly language Machine languages are very difficult for programming. However assembly languages uses mnemonic for each instruction in programs. Assembly language contains simple instruction like ADD A, SUB B etc. Advantage: Easier to understand and used Easier to locate and correct errors Easier to modify No worry about addresses Easily reloadable Efficiency of machine language. Disadvantage: Machine dependent Knowledge of hardware required Machine level coding 3) High level language: Above two type of language are not easy for a programming. To make programming simpler high level languages are developed. These languages contain statements that are similar to a English language and easy to learn and remember. Pascal, COBOL, FORTRAN etc are High level languages. These are machine dependent. There are three significant advantages in high level language:a) Simplicity b) Uniformity c) Profitability (machine independent) Single instruction in high level language will be equivalent to many instructions in machine language. A high level language can generally be run on many different computers. Advantage: They are machine independent.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) They do not required programmer to know anything about internal structure of the computer on which high level programs are executed. They do not deal with machine level coding. Easier to learn and use Fewer error Lower program preparation cost Better documentation Easier to maintain Disadvantage: 1) Lower efficiency 2) Less flexibility

Translators:
As it is easier for programmer to learn any high level language and write the program using a HLL. Because it is much easier to write program and code it. As we know that computer can not understand any other language other than it own machine language (binary language) therefore, it is necessary to process a HLL program so as to make it understandable to the computer. The system programs (software) that perform this very job are language processors. These are as follows: 1) Assemblers 2) Interpreters 3) Compilers The job of all these are same i.e. to convert the source code (any HLL program code) into the object code (MLL code) but the way is different.

1) Assembler:
The translation program that translates an assembly code into the computers machine code is called Assembler. Assembly language program input output Machine language program Assembler (Source program) (Object program)

2) Interpreter
It translates a HLL program into machine language by converting and executing it line by line. If there is any error in any line, it reports it at the same time and program execution cannot resume until the error is rectified. Interpreter must always be present in the memory every time the program executed as every time the program is run, it is first interpreted and then executed. For error debugging, interpreter is very much useful as it reports the errors at the same time. But once the error are rectified unnecessary usage of memory takes pace as it always has to be present in the memory. Ex: BASIC language program are interpreted. High level language program input output Machine language program Interpreter (Source program) (Object program) 3)

Compiler

A compiler also translated an HLL program into machine language but in a different way. It translates the entire HLL program in one go, and reports all the error of the program along with line number. After all the errors are rectified, the program is recompiled, and after that the compiler is not needed in the memory as the object program is available. High level language program input output Machine language program Compiler (Source program) (Object program) Object Code (object program): translation of the source code of a program into machine code, which the computer can read and execute directly. Object code is the input to the linker.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Linker: A program that links separately compiled function together into one program. The o/p of the linker is an executable program. It combines the function in the standard C library with the code that you write.

Library: The file containing the standard functions that can be used by your program. In c header files are included. For ex
getch(), clrscr(). Hence difference in compiler and interpreter is that an interpreter read the source-code of your program one line at time but a compiler read the entire program and converts it into object code. Object code to also called binary code and Machine code.

Generation of Language:
A large number of high level languages have been developed since the first ones developed at early 1950s. After that, more than 1000 high level languages have been developed but many of them are no longer in use. But all the language is categorized into two types: 1. Procedure oriented programming language 2. Object oriented programming language

FORTRAN: FORTRAN stands for FORmula TRANslation. It is one of the oldest high-level languages. It was designed to solve scientific and engineering problems and it is currently most popular language among scientists and engineers. It was originally developed by John Backus and his team at IBM in 1957.

COBOL:
COBAL stand for common Business oriented language. It was designed for business data processing applications; today it is mostly used in business oriented applications. Business data processing application deals with storing, retrieving, and processing corporate accounting information. It was designed and developed by retired navy commodore and mathematician Grace Hopper in 1959.

BASIC:
BASIC stand for Beginners All-purpose Symbolic Instruction Code. It was developed in 1964 by John Kemeny and Thomas Kurtz in US.

Pascal:
Pascal is a language that provide programmer to write well-structured, modular programs, and overall provide good programming feature compare to previous developed language. It was developed by French mathematician Blaise Pascal in 1971.

C and C++:
C language was developed by Dennis Ritchi and Brian Karnighan in 1972 at AT & Ts bell Laboratories. C is a procedure oriented programming language. C++ is a object oriented programming language developed by Bjarne Stroustrup at bell labs in early 1980s.

Characteristics of good programming language:


Simplicity Naturalness Abstraction Efficiency Structured programming support Compactness Locality

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Extensibility Suitability to its environment

C++ Character Set C++ is case sensitive - that is, upper case letters are considered to be different from the corresponding lower case letters Basic C++ character set : 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz _${}[]#()<>%:;.?*+-/^&|~!=,\"' Tokens:- In a C++ program, the basic element recognized by the compiler is the "token." A token is source-program text that the compiler does not break down into component elements. keyword identifier constant string-literal operator punctuator The keywords, identifiers, constants, string literals, and operators described in this section are examples of tokens. Punctuation characters such as brackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) are also tokens.
Keywords:- The keyword implement specified C++ language features. They are explicitly reserved identifiers and

cannot be used as names for the program variables of other user-defined program element.
Identifiers:- in C++, we use identifiers to name user created entities which may be:
Variable Function Type e.g. a class

Every thing has some restrictions and exceptions along with many permissible things. So, does C++ by putting some restrictions on how we can name these entities. Let us see these rules in details: 1. An identifier can be combination of letters, numbers, and underscores with following restrictions: a) It should start with a letter or underscore. E.g. height, my_height,_myHeight are allowed but not 1isGod b) If it starts with a underscore then the first letter should not be capital because such names are reserved for implementation. E.g. _Height not allowed 2. It should be unique in a program taking care that C++ is case sensitive. E.g. age and Age are different variables 3. A keyword cannot be used as an identifier. 4. There is no restriction on length of the identifier. E.g. h and h_represents_my height are both valid. Besides restrictions, there are certain guidelines which you should follow: a. Use meaningful descriptive names. E.g. int Age is better than int a. - If description makes identifier name too long then put a comment before identifier and make identifier shorter b. Be consistent in your naming convention. - Use small letters for single word identifier name.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) - For multiword identifiers, either use underscore separated or interCapped notation. E.g. get_my_height() or getMyHeight() In next lesson, we will see different data types available in C++ and rules for their declaration, initialization, and assignment. Constant in c++:-It is nothing but any values or number of which value is fixed, it is also called a fixed value of constant. There are three types of Constant available in C Language Integer Constant Real Constant Character Constant 12,256,13,1500,32766 etc 12,12.0,333.23,1232.43 etc A Rahul etc

Variables in C++ :-Variable is the name of unknown value which may vary from case to case ,but in the computer it is a name of the locations in the memory to store value or constant in it. When a value is assigned to a variable, value is stored in the location of variable in the memory ,some example are area ,amount ,q, radius etc. Integer Variable Real Variable Character Variable radius=12 Radius=12.5 Name=c, grade=A etc etc etc

Strings:- In C++ strings of characters are held as an array of characters, one character held in each array element. In addition a special null character, represented by `\0', is appended to the end of the string to indicate the end of the string. Hence if a string has n characters then it requires an n+1 element array (at least) to store it. Thus the character `a' is stored in a single byte, whereas the single-character string "a" is stored in two consecutive bytes holding the character `a' and the null character. A string variable s1 could be declared as follows: char s1[10]; The string variable s1 could hold strings of length up to nine characters since space is needed for the final null character. Strings can be initialised at the time of declaration just as other variables are initialised. For example: char s1[] = "example"; char s2[20] = "another example" would store the two strings as follows: s1 |e|x|a|m|p|l|e|\0|

In the first case the array would be allocated space for eight characters, that is space for the seven characters of the string and the null character. In the second case the string is set by the declaration to be twenty characters long but only sixteen of these characters are set, i.e. the fifteen characters of the string and the null character. Note that the length of a string does not include the terminating null character. Operators The operators available in C++ programming language are:

Assignment Operator denoted by Arithmetic operators denoted by Compound assignment Operators denoted by Increment and Decrement operator denoted by Relational and equality operators denoted by Logical operators denoted by Conditional operator denoted by

= +, -, *, /, % +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |= ++, -==, !=, >, <, >=, <= !, &&, || ?

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Comma operator denoted by Bitwise Operators denoted by Explicit type casting operator

, &, |, ^, ~, <<, >>

Assignment Operator :----This is denoted by symbol =. This operator is used for assigning a value to a variable. The left of the assignation operator is known as the lvalue (left value), which must be a variable. The right of the assignation operator is known as the rvalue (right value). The rvalue can be a constant, a variable, the result of an operation or any combination of these. Example:--- x =5;

Arithmetic operators :-The operators used for arithmetic operation sin C++ are:

+ * / %

For addition For subtraction For multiplication For division For modulo

Compound assignment Operators


This operator is used when a programmer wants to update a current value by performing operation on the current value of the variable. Old = old + new Compound assignment operators function in a similar way the other operators +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |= function.

Increment and Decrement Operator


The increment operator is denoted by ++ and the decrement operator by --. The function of the increment operator is to increase the value and the decrement operator is to decrease the value. These operators may be used as either prefix or postfix. A Prefix operator is written before the variable as ++a or a. A Postfix operator is written after the variable as a++ or a--.

Prefix and Postfix Operators


In the case that the increment or decrement operator is used as a prefix ( ++a or a), then the value is respectively increased or decreased before the result of the expression is evaluated. Therefore, the increased or decreased value, respectively, is considered in the outer expression. In the case that the increment or decrement operator is used as a postfix (a++ or a--), then the value stored in a is respectively increased or decreased after being evaluated. Therefore, the value stored before the increase or decrease operation is evaluated in the outer expression.

Relational Operators
These operators are used for evaluating a comparison between two expressions. The value returned by the relational operation is a Boolean value (true or false value). The operators used for this purpose in C++ are:

== != > < >= <=

Equal to Not equal to Greater than Less than Greater than or equal to Less than or equal to

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Fundamental data types


When programming, we store the variables in our computer's memory, but the computer has to know what kind of data we want to store in them, since it is not going to occupy the same amount of memory to store a simple number than to store a single letter or a large number, and they are not going to be interpreted the same way. The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can manage in C++. A byte can store a relatively small amount of data: one single character or a small integer (generally an integer between 0 and 255). In addition, the computer can manipulate more complex data types that come from grouping several bytes, such as long numbers or non-integer numbers. Next you have a summary of the basic fundamental data types in C++, as well as the range of values that can be represented with each one:
Name char Description Character or small integer. Size* 1byte Range* signed: -128 to 127 unsigned: 0 to 255 signed: -32768 to 32767 unsigned: 0 to 65535 signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 true or false +/- 3.4e +/- 38 (~7 digits) +/- 1.7e +/- 308 (~15 digits) +/- 1.7e +/- 308 (~15 digits)

short int (short)

Short Integer.

2bytes

int

Integer.

4bytes

long int (long) bool float double

Long integer.

4bytes

Boolean value. It can take one of two values: true or false. 1byte Floating point number. Double precision floating point number. 4bytes 8bytes 8bytes

long double Long double precision floating point number. wchar_t Wide character.

2 or 4 bytes 1 wide character

* The values of the columns Size and Range depend on the system the program is compiled for. The values shown above are those found on most 32-bit systems. But for other systems, the general specification is that int has the natural size suggested by the system architecture (one "word") and the four integer types char, short, int and long must each one be at least as large as the one preceding it, with char being always one byte in size. The same applies to the floating point types float, double and long double, where each one must provide at least as much precision as the preceding one.

Data Types:--Number data types: int This int keyword is used to declare integers, whole numbers either positive or negative. Most of the compilers treat this with a size of 2 bytes. i.e.,integer of 16 bits length. The following statement shows how the variables of int type are declared. int var1; int var11 = 10;

long: This long keyword is used for declaring longer numbers. i.e, numbers of length 32 bits.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

float: This keyword float is used to declare floating point decimal numbers. A sample declaration would be, float var2; //Sample declaration for float char data types:
char: This keyword is used to declare characters. The size of each character is 8 bits. i.e., 1 byte. The characters that can be used with this data type are ASCII characters. string: This is not a basic data type with C++. Instead array of the char data type should be used for a string variable. char strvar1[200]; char strvar2[]="string can also be initialized like this for the C++ Tutorial"; Otherwise the string class provided in Standard Template Library can also be used. There are some more obscure types too. For example, date. In C++ we cannot use date type right away. This has to be converted to a string or integer for outputs etc., Also, this data type is not available with all compilers. As of now, all of the windows C++ compilers provide this type. Data Types in c++:Data types are means to identify the type of data and associated operations of handling it. C++ provides a predefined set of data types for handling the data it uses. When variables are declared of a particular data type then the variable becomes the place where the data is stored and data types is the type of value(data) stored by that variable. Data can be of may types such as character, integer, real etc. since the data to be dealt with are of may types, a programming language must provide different data types. In C++ data types are of two types:Fundamental Data Types: As the name suggests these are the atomic or the fundamental data types in C++. Earlier there was five of these (int, char, float, double and void) but later two new data types namely bool and wchar_t have been added. Int stores integer data or whole numbers such as 10, -340 etc., char stores any of the ASCII characters, float is used to store numbers having fractional part such as 10.097, double stores the same data as float but with higher range and precision, bool can only store true and false values. //Program to illustrate various fundamental data type #include<iostream.h> void main(void) { int age; float salary; char code; cout<<"Enter age, salary and code:"; cin>>age; cin>>salary; cin>>code; cout<<endl;//goto next line cout<<"DETAILS"<<endl;//short for cout<<"DETAILS";cout<<endl; cout<<"Age:"<<age<<endl; cout<<"Salary:"<<salary<<endl; cout<<"Code:"<<code<<endl;

1. Derived Data Types: These are the data types which are derived from the fundamental data types. It is further divide into two categories i)Built-In and ii)User-defined, which are discussed below as seperate topics.
Built-In Derived Data Type

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Arrays: Arrays refer to a list of finite number of same data types. The data in the array can be accessed by an index number ranging from 0 to n(where n is the number of data element it can store). Ex- if arr[3] is an array of int(egers) then the different values in the array can be accessed as shown below. arr[0], arr[1],arr[2] when we declare an array such as the one sown above then by arr[3] we mean that we want three elements in the array and hence while accessing arr[2] is the last element. //Program to illustrate arrays #include<iostream.h> void main(void) { int arr[3];//it will store 3 integer elements cout<<"enter 3 numbers:"; cin>>arr[0]>>arr[1]>>arr[2];//this statement is same as using three cin's cout<<endl;//goto next line cout<<arr[0]<<arr[1]<<arr[2]; }
Pointer: A pointer is a variable that holds the memory address of other variable. It is also of different data types, ex- char

pointer can store address of only char variables, int pointer can store address of int variables and so on.
Reference: A reference in the simplest sense is an alias or alternate name for a previously defined variable.

//Program to illustrate References #include<iostream.h> void main(void) { int var; int &refvar=var; var=10; cout<<var<<endl; refvar=100; cout<<var;

//here a reference variable to var is declared remember var was previously declared //var is given the value 10 //reference variable of var is changed //but var also gets changed

} User-Defined Derived Data Types Class: A class is a collection of variables and function under one reference name. it is the way of separating and storing similar data together. Member functions are often the means of accessing, modifying and operating the data members (i.e. variables). It is one of the most important features of C++ since OOP is usually implemented through the use of classes.

Structure: In C++ structure and class same except for some very minor differences. Union: A union is a memory location shared by two or more different variables, generally of different data types. Giving more
details here would only confuse you; Ill leave it for future articles.

Enumerations: It can be used to assign names to integer constants.


//Program to illustrate Enumerators #include<iostream.h> void main(void) { enum type{POOR,GOOD,EXCELLENT};

//this is the syntax of enumerator

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) int var; var=POOR; cout<<var<<endl; var=GOOD; cout<<var<<endl; var=EXCELLENT; cout<<var; }

//this makes programs more understandable

Data Types Modifiers


signed unsigned short long

Int, char, float, double data types can be preceded with these modifiers to alter the meaning of the base type to fit various situations properly. Every data type has a limit of the larges and smallest value that it can store known as the range. An integer (usually 4 bytes long) can store any value ranging from -2147483648 to 2147483647. Data Type modifiers usually alter the upper and lower limit of a data type. Unsigned modifier makes a variable only to store positive values. Ex- if a data type has a range from a to a then unsigned variable of that type has a range from 0 to 2a. Preceding any data type with signed is optional because every data type is signed by default. Short integers are 2 bytes long and long integers are 8 bytes long.

Variables
A variable is the name used for the quantities which are manipulated by a computer program. For example a program that reads a series of numbers and sums them will have to have a variable to represent each number as it is entered and a variable to represent the sum of the numbers. In order to distinguish between different variables, they must be given identifiers, names which distinguish them from all other variables. This is similar to elementary algebra, when one is taught to write ``Let stand for the acceleration of the body ...''. Here is an identifier for the value of the acceleration. The rules of C++ for valid identifiers state that: An identifier must: start with a letter consist only of letters, the digits 0-9, or the underscore symbol _ not be a reserved word Reserved words are otherwise valid identifiers that have special significance to C++. A full list is given below in section . For the purposes of C++ identifiers, the underscore symbol, _, is considered to be a letter. Its use as the first character in an identifier is not recommended though, because many library functions in C++ use such identifiers. Similarly, the use of two consecutive underscore symbols, __, is forbidden. The following are valid identifiers length days_in_year DataSet1 Profit95 Int _Pressure first_one first_1 although using _Pressure is not recommended. The following are invalid: days-in-year 1data int first.val throw Identifiers should be chosen to reflect the significance of the variable in the program being written. Although it may be easier to type a program consisting of single character identifiers, modifying or correcting the program becomes more and more difficult. The minor typing effort of using meaningful identifiers will repay itself many fold in the avoidance of simple programming errors when the program is modified. Type Casting:---Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast:

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) short a=2000; int b; b=a; Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.

Explicit conversion C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and clike casting: short a=2000; int b; b=(int)a; b=int(a);
The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors. For example, the following code is syntactically correct: // class type-casting #include <iostream> using namespace std; class CDummy { float i,j; }; class CAddition { int x,y; public: CAddition (int a, int b) { x=a; y=b; } int result() { return x+y; } }; int main () { CDummy d; CAddition * padd; padd = (CAddition*) &d; cout << padd->result(); return 0; }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Precedence of operators When writing complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. For example, in this expression: A=5+7%2 we may doubt if it really means: a=5+(7%2) //with a result of 6 , or a=(5+7)%2 //with a result of 0 The correct answer is the first of the two expressions, with a result of 6. There is an established order with the priority of each operator, and not only the arithmetic ones (those whose preference come from mathematics) but for all the operators which can appear in C++. From greatest to lowest priority, the priority order is as follows: Level Operator Description Grouping :: 1 scope Left-to-right () [] . -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeid postfix 2 Left-to-right ++ -- ~ ! sizeof new delete unary (prefix) *& 3 indirection and reference (pointers) Right-to-left +unary sign operator (type) 4 type casting Right-to-left .* ->* 5 pointer-to-member Left-to-right */% 6 multiplicative Left-to-right +7 additive Left-to-right << >> 8 shift Left-to-right < > <= >= 9 relational Left-to-right 10 == != equality Left-to-right 11 & bitwise AND Left-to-right 12 ^ bitwise XOR Left-to-right 13 | bitwise OR Left-to-right 14 && logical AND Left-to-right || 15 logical OR Left-to-right 16 ?: conditional Right-to-left 17 = *= /= %= += -= >>= <<= &= ^= |= assignment Right-to-left 18 , comma Left-to-right Grouping defines the precedence order in which operators are evaluated in the case that there are several operators of the same level in an expression. All these precedence levels for operators can be manipulated or become more legible by removing possible ambiguities using parentheses signs ( and ), as in this example: a=5+7%2;

might be written either as: a=5+(7%2); or a=(5+7)%2;


depending on the operation that we want to perform. So if you want to write complicated expressions and you are not completely sure of the precedence levels, always include parentheses. It will also become a code easier to read.

Explain the terms Prefix operator and Postfix operator with represent to ++ (Increment) and( Decrement) operator.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Increment operator ( ++ ) :- used to add value Ine (1) to value of its operand, which Decrement operator (- -) is used to subtract value one (1) from value of its operand. ++ and operators can be used as a Prefix(means before a operand) or Postfix(means after a operand)operators. Increment operator (++) is again classified as below Prefix Increment operator (++ operand) Postfix Increment operator (operand ++) Prefix Increment operator: In this case ,it increment the value of operand first and then pass new increment value in the expression. Suppose x=3; ++x; ++x increment value of x before its value is used :means value of x will be. x=x+1; x=3+1; x=4; Postfix increment operator :(operand ++) : In this case ,it passes first old value of operand into the expression and then increment its value of operand by one (1) Suppose x=3; x++; x++ increment a value of x means value of x will be. x=3+1; x=4; Decrement operators are working same as increment operators, but it reduce value of its operand by 1 Decrement operators (--) Prefix decrement (--operand) Postfix decrement(operand --) Control and Decision statement support in C. C has three major decision making instruction . Conditional operators :- The conditional operators ? and : are sometimes called as ternary operators since they take three arguments . Syntex :Expression1 ? expression2 : expression3; Explanation :- if expression1 is true , then the value returned will be expression2 otherwise value returned will be expression3 . Example :main() { int x,y; printf(Enter value of x); scanf(%d,&x); y=(x>5 ? 3: 4); printf(%d,y); getche(); } If user enter value of x greater than 5 then 3 gets assign to variable y , and if it is less than 4 will gets assign to y. The if-statement ,the if else statement and the switch statement. The if statement :- C used the keywords if to implement the decision control instruction . the syntax of If statement is as fallows . Syntex:If ( this condition is true ) Statement;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) The keyword if tells the compiler that what follows ,is a decision control instruction.hte keyword if is always enclosed within a pair of parentheses . if the condition is true ,then the statement is executed. If the condition is not true then the statement is not executed. Instead the program skips past it. As a general rule, we express a condition using Cs relational operators. The relational operator allow us to compare two value to see whether they are equal to each other ,unequal ,greater than or equal to ,less than or equal to , not equal to etc. Expression x==y x!=y x<y x>y X<=y x>=y Is true if X is equal to y X is not equal to y X is less than y X is greater than y X is less than or equal to y X is greater than or equal to y

Example:=Basic salary of an Employee is entered from a keyboard. Write a program to calculate and print gross salary of employee , if basic salary is greater than Rs 2000 then Provident fund is 10% of basic salary and house rent allowances is 10%. main() The if-else statement:- We execute one group of statement if the condition is true and another group of statement if the condition is false. This is what is the purpose of the else statement. Syntax: If(Condition is true) Statement; else Statement2; Nested if-else statement: if we write an entire if else construct within either the body of the if statement or the body of an else statement is called nested of if Example:Program to find whether given no is even or odd

#include<stdio.h> #include<conio.h> void main() { int n; clrscr(); printf("enter any no: "); scanf("%d",&n); if(n%2==0) printf("no is even"); else printf("no is odd"); getch(); } Example :-Any number is enter through the keyboard .w.a.p to find whether it is positive number or negative number? #include<stdio.h> #include<conio.h>

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) void main() { int number; printf(Enter any number); scang(%d,&number); if(number>0) printf(The number is Positive); else printf(The number is Negative); getche(); } Relational operators:Relational operators are as follows: <, <=, >, >=, ==, != . They are used in Boolean conditions or expression and returns true or false. it is required to compare the relationship between operands and bring out a decision and program accordingly. Logical operators :- The logical operators are often used to help create a test expression that controls program flow. This type of expression is also known as a Boolean expression because they create a Boolean answer or value when evaluated. The answers to Boolean expressions within the C programming language are a value of either 1 for true or 0 for false. There are three common logical operators that give a Boolean value by manipulating other Boolean operand(s). Operator symbols and/or names vary with different programming languages. The C programming language operators with their meanings are: C OperatorMeaning Comment Typing && Logical and two ampersands two vertical dashes or piping || Logical or symbols ! Logical not unary the exclamation point

Note:
The vertical dashes or piping symbol is found on the same key as the backslash \. You use the SHIFT key to get it. It is just above the Enter key on most keyboards. It may be a solid vertical line on some keyboards and show as a solid vertical line on some print fonts. In most languages there are strict rules for forming proper logical expressions. An example is: 6 > 4 && 2 <= 14 This expression has two relational operators and one logical operator. Using the precedence of operator rules the two relational comparisons will be done before the logical and operation. Thus: 1 && 1 or true && true The final evaluation of the expression is: 1 meaning true. We can say this in English as: It is true that six is greater than four and that two is less than or equal to fourteen. When forming logical expressions programmers often use parentheses (even when not technically needed) to make the logic of the expression very clear. Consider the above complex Boolean expression rewritten: (6 > 4) && (2 <= 14) Truth Tables:- A common way to show logical relationships is in truth tables

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) AND(&&) OR(||) NOT(!)

x T T F F

y T F T F

x && y T F F F

x T T F F

y T F T F

x || y T T T F

T F

F T

Example:Any character is entered from a keyboard w.a.p to calculate and print whether is small letter ,capital letter,digit or special character. void main() { char letter; printf(Enter any character); scanf(%c,&letter); if(letter>=48 && letter <=57) printf(You enter digits); else if (letter>=65 && letter<=90) printf(You enter capital letter); else if (letter>=97 && letter<=122) printf(You enter small letter); else printf( You enter a special character); getch(); } Example:Coordinate of any point are entered from a keyboard W.a.p. to print whether point lies on the 1st quadrant 2nd ,3rd ,or 4th quadrant void main() { int x,y; printf(Enter coordinate of x and y point); scanf(%d %d, &x, &y); if(x>0 && y>0) printf(Point is in 1st quadrant); if(x<0 && y>0) printf(Point is in 2nd quadrant); if(x<0 && y<0) printf(Point is in 3rd quadrant); if(x>0 && y<0) printf(Point is in 4th quadrant); getche(); }

Example:W.a.p to find the person is child,Teen agers,Young or Middle age. Void main() { int age; printf(Enter age of a person); scanf(%d,&age); if (age<=16)

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) printf(The person is Child); if(age>16 && age<=21) printf(The person is Teen agers); if(age>21 && age <=30) printf(The person is Young); if(age>30 && age<=45) printf(The person is Middle age); if(age>45) printf(The person is Old Age); getche(); } Example:- Enter five subject marks and find total and percentage or the student is first division , second division Third division or Failed. void main() { int m1,m2,m3,m4,m5; float total,per; printf(Enter five subject marks); scanf(%d%d%d%d%d,&m1,&m2,&m3,&m4,&m5); total=m1+m2+m3+m4+m5; per=total/5; if(per>=60) printf(The student is First division); if((per>=50) && (per<60)) printf(The student is second division); if((per>=40) && (per<50)) printf(The student is third division); if(per<40) printf(The student is Failed); getche(); } -: Control Statement :Loops:-The versatility of the computer lies in its ability to perform a set of instruction repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operations is done through a loop control structure. There are three method by ways of which we can repeat a part of a program , They are 1.) For statement 2.) While Statement. 3.) Do-while Statement. For loop:The purpose of for loop is same as while loop but writing format is different , perhaps one reason why few programmers use while is that they are too busy using the for . which is the most popular control . for allows us to specify three things about a loop in a single line. The general form of for statement is as under. Syntex :for(initialize counter ; test counter ; increment counter) { do this; and this; and this;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) } Explanation how for statement gets executed :When program control reaches to for first time is executed . Then condition is checked . The result of the condition is true then body of the loop is executed otherwise control comes outside loop .After executing body of the loop increment is executed then again condition is executed and process repeats.

Flowchart of for loop:START Declare variable Initiate F STOP for condition T Statement 1 ; Statement 2;

Increment

Example :main() { int I; for(i=1;i<=5 ;i++) { printf(%d,i); } getche(); } While loop :- The general format of While is as shown below. Syntex :Initialize loop counter; while(test loop counter using a condition) { do this; and this; increment or decrement loop counter; } START Declare variable Initiate While condition STOP

Flowchart of while loop :Increment

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Program:main() { int i=1; while(i<=10) { printf(%d,i); i++; } getch(); } Note the following point about while :a) The statement within the while loop would keep on getting execute till the condition being tested remains true . when the condition becomes false , The control passed to the first statement that follows the body of the while loop. b) The condition being tested may use relational or logical operators shown the following example i) while(i<=15) II) while(i>=15 && j<=20) III) while(j>10 && (b<15 || c<20)) The statement within the loop may be a single line or a block of line Example :While(i<10) or while(i<=10) I=i+1; { I=i+1; } do-while loop:- There is a minor difference between the working of while and do-while .This difference is the place where the condition is tested . The while tests the condition before executing any of the statement within the while loop . As against this , do while tests the condition after having executed the statement within the loop . This means that do while would execute its statement at least once . even if the condition fails for the first time itself . The while on the other hand will not execute its statement if the condition fails for the first time. The general form of do while statement is as under. Syntex :declare and initialize variable ; do { Statement ; Statement ; Increment; } while(condition) ;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Flowchart of do-while loop :START Declare variable do

Statement 1 ; Statement 2; F Increment While condition T STOP

Program :main() { int i=1; do { printf(%d,i); i++; } while(i<=10) getch(); } Switch Statement :Switch is one more decision statement like if and if-else statement but different is that , switch is the selection of particular choice from the given list of options . as we switch on the button to start particular devices from the series of button mounted on the electricity board such as one button is to start Fan , another may be to switch on TV and so on . same concepts is used in switch statement ,as per the value of an expression or choice a particular case is executed . The syntax of Switch statement is as follows. Syntax :expression ; switch(expression) { case Constant1: Statement1; .. case Constant2: Statement2; . . default : Statement3; } Here constant1 and constant2 .. are all either integer or character. Float constant are not allowed. expression in switch () gets evaluated then value of this expression is compared with constant in each case . All the statement from that satisfied case gets execute until closing brace of switch or break is encountered.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) To execute any particular case , break statement should be given at the ends of each case . Default is a special case which gets executed whenever encountered. Program :main() { iInt a; printf(Enter month from 1 to 12 ); scanf(%d,&a); switch(a) { case 1: printf(January); break; case 2: printf(Feburary); break; case 3: printf(March); break; case 4: printf(April); break; case 5: printf(May); break; case 6: printf(June); break; case 7: printf(July); break; case 8: printf(August); break; case 9: printf(September); break; case 10 : printf(Octomber); break; case 11: printf(November); break; case 12: printf(December); break; default : printf(You entered invalid number); } getch(); } The break statement :- The keyword break is encountered inside any C or C++ loop , Controls automatically passed to the first statement after the loop . A break is usually associated within an if . Example :main() { int num,i=2; printf(Enter a number); scanf(%d,&num); while(i<=num-1) { If(num%i==0) { printf(not a prime number); break; } }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) } The continue Statement :- The keyword Continue allows us to do this , when the keywords continue is encountered inside any C or C++ loop control automatically passed to the beginning of the loop . A continue is usually associated with an if . Example :main() { int I,j; for(i=1;i<=2 ;i++) { for(j=1;j<=2; j++) { if(i==j) continue; printf(%d%d,I,j); } } } The goto statement :- It is used to send control at any point in the program where label of goto statement written in the program . General form of the goto statement is as shown below . goto label; statement; statement; label statement; Whenever a goto statement is executed ,control go to on searching a label program from top to bottom , if found , executed the statement follows by label it and execution will be continued downward after the execution of statement follows by a label , till the end of a program as usual . Example :main() { int i=1; UP: I=i+1; Printf(Hello friends); if(i<=5) Goto UP; } Basic Input/Output:--Standard Output (cout) By default, the standard output of a program is the screen, and the C++ stream object defined to access it is cout. cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs).

Cout<<Output sentence; Cout<<120; Cout<<x;

//print output sentence on screen //print number 120 on screen //print the content of x on screen.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) The << operator inserts the data that follows it into the stream preceding it. In the examples above it inserted the constant string Output sentence, the numerical constant 120 and variable x into the standard output stream cout. Notice that the sentence in the first instruction is enclosed between double quotes (") because it is a constant string of characters. Whenever we want to use constant strings of characters we must enclose them between double quotes (") so that they can be clearly distinguished from variable names. For example, these two sentences have very different results: Cout<<Hello; //prints Hello Cout<<Hello; //prints the content of hello variable Standard Input (cin). The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store the data that is going to be extracted from the stream. For example: int age; cin>>age; The first statement declares a variable of type int called age, and the second one waits for an input from cin (the keyboard) in order to store it in this integer variable. cin can only process the input from the keyboard once the RETURN key has been pressed. Therefore, even if you request a single character, the extraction from cin will not process the input until the user presses RETURN after the character has been introduced. You must always consider the type of the variable that you are using as a container with cin extractions. If you request an integer you will get an integer, if you request a character you will get a character and if you request a string of characters you will get a string of characters. //Input output example #include<iostream.h> int main() { int i; cout<<Please enter an integer value; cin>>i; cout<<The value you entered is<<i; cout<<And its double is<<i*2<<\n; return 0; } Please enter an integer value 702 The value you entered is 702 and its double is 1402. The user of a program may be one of the factors that generate errors even in the simplest programs that use cin (like the one we have just seen). Since if you request an integer value and the user introduces a name (which generally is a string of characters), the result may cause your program to misoperate since it is not what we were expecting from the user. So when you use the data input provided by cin extractions you will have to trust that the user of your program will be cooperative and that he/she will not introduce his/her name or something similar when an integer value is requested. A little ahead, when we see the stringstream class we will see a possible solution for the errors that can be caused by this type of user input. You can also use cin to request more than one datum input from the user: Cin>>s>>b;

Cin>>a>>b;

is equivalent to: cin>>a;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

cin>>b;
In both cases the user must give two data, one for variable a and another one for variable b that may be separated by any valid blank separator: a space, a tab character or a newline. Manipulators Manipulators are used to change formatting parameters on streams and to insert or extract certain special characters. These manipulators are usable on both input and output streams, although many only have an effect when applied to either output or input streams.Output manipulators
endl ends flush Insert newline and flush (manipulator function) Insert null character (manipulator function) Flush stream buffer (manipulator function)

Introduction:Dividing a Program into functions is one of the major Principle of top-down structures programming. Another advantages of using function is that it is possible to reduce the size of the program by calling and using them at different places in the program. Like C++ operators , a C++ functions can be overloaded to make it perform different tasks depending on the arguments passed to it. Most of these modifications are aimed at meeting the requirements of object-oriented facilities. THE MAIN FUNCTION ANSI C does not specify any return type for the main() functions which is the starting point for the execution of a program.The definition of main() would look like this: main() { //main program statements } This is perfectly valid because the main() in ANSI C does not return any value. In C++ ,the main() return a value of type int to the operating system.C++,thereforn ,explicitly defines main() as matching one of the fillowing prototypes: Int main(); Int main(int argc, char* argv[]); The function that have a return value should use the return statement for termination. The main function in C++ is, therefore, defined as follows: int main() { return (0); } Since the return type of function is int by default ,the keyword int in the main() header is optional.

CALL BY REFERENCE:
Usually, a function call passed argument by value. The called function creates a new set of variables and copies the values of arguments into them. The function does not have access to the actual variables in the calling program and can only work on the copies of values. The mechanism is fine if the function does not need to alter the values of the original variables in the calling program . But ,there may arise situations where we would like to change the values of variables in the calling program. Provision of the reference variables in C++ permits us to pass parameters to the functions by reference .When we pass arguments by reference, the formal arguments in the called, function become aliases to the actual arguments in the calling

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) function. This means that when the function is working with its own arguments, it is actually working on the original data. Consider the following e.g. If we wish to interchange the value of two variable through a function then it should be able to alter the values of variables in the calling function , which is not possible if the cvall-by value method is used . Void swap(int &a,int &b) { Int t=a; a=b; b=t; } Now if suppose m and n are two integer variable, then the function call Swap(m,n); Will exchange the values of m and n using their aliases a and b. RETURN BY REFERENCE A function can also return a reference. Consider the following function: int &max(int &x, int &y) { if (x>y) return x; else return y; } Since the return type of max() is int &,the function return reference to x or y(and not the values). Then a function call such as max(a,b) will yields reference to either a or b depending on their values. This means that this function call can appear on the left hand side of an assignment statement.That is the statement max(a,b)= -1; Is legal and assigns -1 to a if it is larger, otherwise -1 to b What is Inline Function? Inline functions are functions where the call is made to inline functions. The actual code then gets placed in the calling program. Reason for the need of Inline Function: Normally, a function call transfers the control from the calling program to the function and after the execution of the program returns the control back to the calling program after the function call. These concepts of function saved program space and memory space are used because the function is stored only in one place and is only executed when it is called. This concept of function execution may be time consuming since the registers and other processes must be saved before the function gets called. The extra time needed and the process of saving is valid for larger functions. If the function is short, the programmer may wish to place the code of the function in the calling program in order for it to be executed. This type of function is best handled by the inline function. In this situation, the programmer may be wondering why not write the short code repeatedly inside the program wherever needed instead of going for inline function? Although this could accomplish the task, the problem lies in the loss of clarity of the program. If the programmer repeats the same code many times, there will be a loss of clarity in the program. The alternative approach is to allow inline functions to achieve the same purpose, with the concept of functions.

What happens when an inline function is written?


The inline function takes the format as a normal function but when it is compiled it is compiled as inline code. The function is placed separately as inline function, thus adding readability to the source program. When the program is compiled, the code present in function body is replaced in the place of function call. General Format of inline Function: The general format of inline function is as follows: inline datatype function_name(arguments)

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)
Example:

The concept of inline functions #include <iostream.h> int exforsys(int); void main( ) { int x; cout << \n Enter the Input Value: ; cin>>x; cout<<\n The Output is: << exforsys(x); } inline int exforsys(int x1) { return 5*x1; } The output of the above program is: EntertheInputValue:10 The Output is: 50 The output would be the same even when the inline function is written solely as a function. The concept, however, is different. When the program is compiled, the code present in the inline function exforsys( ) is replaced in the place of function call in the calling program. The concept of inline function is used in this example because the function is a small line of code.

Example:inline int average(int a, int b) { return (a + b) / 2; } int main() { int result = average(12, 14); cout << "The average of number 12, 14 is " << result << "\n"; return 0; }

Default Arguments:Default arguments are formal parameters that are given a value (the default value) to use when the caller does not supply an actual parameter value. Of course, actual parameter values, when given, override the default values. The syntax and and utility of default arguments is illustrated by the following example based on the Frame class. class Frame { private:

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) ... public: ... void Resize (int width = 100, int height = 150); ... }; In this example, the width and height arguments are both given default values. To see the effect of these default values consider the following use of the Resize method: Frame window (100, 100, 300, 400); ... window.Resize(200, 250); window.Resize(200); window.Resize(); // case 1 // case 2 // case 3

In the first case the window is resized to be 200 X 250: since both parameters are given the default values are ignored. In the second case, the Frame object is resized to be 200 X 150: the default value of 150 is used for the absent second (height) argument while the supplied 200 is used for the first (width) argument. In the third case, the window is resized to be 100 X 200 since both default values are used. Default values can also be used with constructors. For example the Frame class could be redefined as follows: class Frame { private: ... public: Frame( char *name, int initXcoord = 50, int initYcoord = 50, int initWidth = 100, int initHeight = 100 ); ... }; This single constructor can be used in any of the following ways: Frame display1("Fully Specified", 200, 200, 300, 350); Frame display2("No Height", 200, 200, 300); Frame display3("Position Only", 200, 200); Frame display4("No YCoordinate", 200) Frame display5("Name Only"); The Frame display1 is given a name and will be located at position (200,200) with a shape of 300 by 350. The Frame display2 is like display1 except that it has a default height of 100 as specified by the default value for initHeight. The Frame display3 is given a name and will be located at position (200,200) and it will have a shape of 100 by 100 as determined by the default values for initWidth and initHeight. The Frame display 4 is similar to display3 except that it has a different name and will be located at (200,50), the y coordinate of 50 being determined by the default value for the parameter initYcoord. Finally, display5 will have the name indicated and the default values will determine its position - (50,50) - and it shape - 100 by 100. Notice that as with overloaded methods, the use of default parameters give the caller of a method added flexibility in how to invoke the method. The caller need only specify those parameters that are essential and allow the default values to apply for all other parameters. Callers who need more exact control of the methods arguments can override the default values by providing their own values.

Default values can be used when:


a default value represents a commonly occurring value, a "safe" value guaranteeing that a sensible computation will result, or

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

an "unreasonable" (e.g., out of range) value that causes the method to use some algorithm to compensate for the the missing argument value.

Examples of common or safe default values are an integer "counter" whose default initial value is zero or a text value whose initial contents is blank or null. A variation of the Frame class is an example of using unreasonable default values. In this variation the default values for the x coordinate, the y coordinate, the height, and the width are -1, clearly unreasonable values. The Frame constructor when confronted with (some of) these default values uses an internal algorithm to determine what values to use for each defaulted argument. The algorithm may, for example, attempt to minimize the overlap of this window with other windows on the screen. The rule for specifying default values is that a argument without a default value can not occur after (to the right of) an argument with a default value. The following example illustrates why this rule is needed: class Cube { public: ... Resize( int height = 10, int width = 20, int depth); ... }; Notice that this violates the rule for default arguments because the argument depth has no default and occurs after width which has a default value. Consider the following code that uses the Resize method: Cube cube; ... cube.Resize(30, 50); This invocation of Resize could reasonably mean any one of three things: cube.Resize(10, 30, 50); cube.Resize(30, 20, 50); cube.Resize(30, 50); // uses height default // uses width default // ERROR - no depth argument

const argument:- The value of an argument that is declared const cannot be changed

Function overloading:
C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types. void AddAndDisplay(int x, int y) { cout<< (x+y); } void AddAndDisplay(double x, double y) { cout<< (x+y); }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) void AddAndDisplay(float x, float y) { cout<< (x+y); } Some times when these overloaded functions are called, they might cause ambiguity errors. This is because the compiler may not be able to decide what signature function should be called. If the data is type cast properly, then these errors will be resolved easily. Typically, function overloading is used wherever a different type of data is to be dealt with. For example this can be used for a function which converts farenheit to celsius and vice versa. One of the functions can deal with the integer data, other can deal float for precision etc..,

Operator overloading
allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce maintenance costs).

Classes and Objects:A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable. Classes are generally declared using the keyword class, with the following format: class class_name { access_specifier_1: member1; access_specifier_2: member2; ... } object_names; Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members, that can be either data or function declarations, and optionally access specifiers. All is very similar to the declaration on data structures, except that we can now include also functions and members, but also this new thing called access specifier. An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights that the members following them acquire: private members of a class are accessible only from within other members of the same class or from their friends. protected members are accessible from members of their same class and from their friends, but also from members of their derived classes.

public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access. For example: class CRectangle { int x, y;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) public: void set_values (int,int); int area (void); } rect; Declares a class (i.e., a type) called CRectangle and an object (i.e., a variable) of this class called rect. This class contains four members: two data members of type int (member x and member y) with private access (because private is the default access level) and two member functions with public access: set_values() and area(), of which for now we have only included their declaration, not their definition. Notice the difference between the class name and the object name: In the previous example, CRectangle was the class name (i.e., the type), whereas rect was an object of type CRectangle. It is the same relationship int and a have in the following declaration: int a; where int is the type name (the class) and a is the variable name (the object). After the previous declarations of CRectangle and rect, we can refer within the body of the program to any of the public members of the object rect as if they were normal functions or normal variables, just by putting the object's name followed by a dot (.) and then the name of the member. All very similar to what we did with plain data structures before. For example: rect.set_values (3,4); myarea = rect.area(); The only members of rect that we cannot access from the body of our program outside the class are x and y, since they have private access and they can only be referred from within other members of that same class // classes example #include <iostream> using namespace std; class CRectangle { int x, y; public: void set_values (int,int); int area () { return (x*y); } }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Example 2:#include <iostream> class CRectangle { int x, y; public: void set_values (int,int); int area () { return (x*y); } }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect, rectb; rect.set_values (3,4); rectb.set_values (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; }

Object:-Creation of Objects:
Once the class is created, one or more objects can be created from the class as objects are instance of the class. Juts as we declare a variable of data type int as: int x; Objects are also declared as: class name followed by object name; exforsys e1; This declares e1 to be an object of class exforsys. For example a complete class and object declaration is given below: class exforsys { private: int x,y; public: void sum() { } }; main() { exforsys e1;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) } The object can also be declared immediately after the class definition. In other words the object name can also be placed immediately before the closing flower brace symbol } of the class declaration. class exforsys { private: int x,y; public: void sum() { } }e1 ;

Structure:It is an another type of secondary variable which is used to store multiple constant of similar types in the memory. It is like a family having a member of different relations and sex. One structure can have different types of values, for an example , one structure can have integer, real and character variable as an elements as shown below. Format of structure. Strut <Name of struct> { Element variable; }; Struct <Name of struct<<variable>; Structure can stored almost all types of values which can represent one record having different details of a particular entity say record of an employee having details like name ,age ,date of birth,Basic salary PF and HRA and Gross salary. WHAT IS A UNION A union, is a collection of variables of different types, just like a structure. However, with unions, you can only store information in one field at any one time. You can picture a union as like a chunk of memory that is used to store variables of different types. Once a new value is assigned to a field, the existing data is wiped over with the new data. A union can also be viewed as a variable type that can contain many different variables (like a structure), but only actually holds one of them at a time (not like a structure). This can save memory if you have a group of data where only one of the types is used at a time. The size of a union is equal to the size of it's largest data member. In other words, the C compiler allocates just enough space for the largest member. This is because only one member can be used at a time, so the size of the largest, is the most you will need. Here is an example: ... union time { long simpleDate; double perciseDate; }mytime; .... The union above could be used to either store the current time (in seconds) to hold time accurate to a second. Or it could be used

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) to hold time accurate to a millisecond. Presumably there are times when you would want one or the other, but not both. This declaration should look familiar. It is the same as a struct definition, but with the keyword union instead of struct. Enumerated data type:The enumerated data type gives you an apportunity to invent your own data type and define what values the variable of this data type can take. This can help in making the program listings more readable,which can be an advantage when a program gets complicated or when more than one programmer would be working on it. Using Enumerated data type can also help you reduce programming error. The format of the enum definition is similar to that of a structure. Format:eum <Name of enum> { Element variable }; enum < Name ofenum> <variable>; Example Enum mar_status { Single,married,divorced,widowed }; enum mar_status person1,person2; Internally ,the compiler treats the enumerators as integers.Each value on the list of permissible values corresponds to an integer,starting with 0.Thus in our example,single,is stored as 0,married is stored as 1,divorced as 2 and widowed as 3 This way of assigining numbers can be overridden by the programmer by initializing the enumerators to different integer values as shown below. Enum mar_status { Single=100,married=200,divorced=300,widowed=400 }; Enum mar_status person1,person2; Example:main() { enum emp_dept { assembly,manufacturing,accounts,stores }; struct employee { char name[30]; int age; float bs; enum emp_dept department; }; struct employee e; strcpy(e.name,Naresh Sharma); e.age=30; e.bs=4454.4; e.department=manufacturing;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) printf(%s%d%f%d,e.name,e.age,e.bs.e.department); if(e.department==account) printf(\n%s is an accountant,e.name); else printf(%s is not an accountant,e.name); }

Passing structure to functions:


struct student { char name[20]; int num; float score[3]; }; void print(struct student *p) { cout<<p->num<<"\n"<<p->name<<"\n"<<p->score[0]<<"\n" <<p->score[1]<<"\n"<<p->score[2]<<"\n"; cout<<" "; } int main() { struct student stu; stu.num=12345; strcpy(stu.name,"li li"); stu.score[0]=67.5; stu.score[1]=89; stu.score[2]=78.6; print(&stu); } #include <cmath> #include <iostream> using namespace std; // define the structures struct DataStructure { float radius; double angle; }; struct ResultStructure { float area; double sine; double cosine; double tangent; }; ResultStructure compute(struct DataStructure mystruct); int main () {

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) DataStructure input; ResultStructure output; input.radius = 3; input.angle = 0.8; output = compute(input); cout << " The area is "<< output.area << "\n"; cout << " The sine of the angle is " << output.sine << "\n"; cout << " The cosine of the angle is " << output.cosine << "\n"; cout << " The tangent of the angle is " << output.tangent << "\n"; return 0; } ResultStructure compute(struct DataStructure mystruct) { ResultStructure answer; answer.area = pow(mystruct.radius,2); answer.sine = sin(mystruct.angle); answer.cosine = cos(mystruct.angle); answer.tangent = tan(mystruct.angle); return answer; };

Static data members:A data member of a class can be qualified as static. The property of a static member variable are similar to that of a C static variable. A static member variable has certain special characteristics. These are. a) It is initialized to zero when the first object of its class is created. No other initialization is permitted. b) Only one copy of that member is created for the entire class and is shared by all the objects of that class,no matter how many objects are created. c) It is visible only within the class,but its lifetime is the entire program. Static variable are normally used to maintain values common to the entire class. For example,a static data member can be used as a counter that records the occurrences of all the objects Example: Class item { static int count; int number; public: void getdata(int a) { number=a; count++; } void getdata(void) { cout<<count;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) } }; int item:: count; main() { item a,b,c; a.getcount(); //0 b.getcount(); //0 c.getcount(); //0 a.getdata(100); b.getdata(200); c.getdata(300); cout<<endl<<After reading data; a.getcount(); //3 b.getcount(); c.getcount(); return 0; }

Static member function: Like static member variable ,we can also have static member functions. A member function that is declared static has the following properties. a) A static function can have access to only other static members declared in the same class. b) A static member function can be called using the class name as follows. Class name:: function-name; Program illustrates the implementation of these characteristics. The static functions Showcount() displays the number of objects created till that moment.A count of number of objects created is maintained by the static variable count. The function Showcode() display the code number of each object. class test { int code; static int count; public: void setcode(void) { code=++count; } void showcode(void) { cout<<Objects number <<code<<\n; } static void showcount(void) { cout<<count <<count<<\n; } }; int test ::count; main() { test t1,t2;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) t1.setcode(); t2.setcode(); test::showcount(); test t3; t3.setcode(); //2 test::showcount(); //3 t1.showcode(); //1 t2.showcode(); //2 t3.showcode(); //3 return 0; }

Array within a class :The array can be used as member variable in a class. The following class definition is valid. const int size=10 // provides value for array size class array { int a[size]; public void setvalue(void); void display(void); };

The array variable a[] declared as a private member of the class array can be used in the member function ,like any other array variable .we can perform any operations on it. For instance ,in the above class definition ,the member function setval() sets the values of element of the array a[],and display() function display the values. Similarly ,we may use other member functions to perform any other operations on the array values. #include <iostream> using namespace std; int billy [] = {16, 2, 77, 40, 12071}; int n, result=0; int main () { for ( n=0 ; n<5 ; n++ ) { result += billy[n]; } cout << result; return 0; } define WIDTH 5 #define HEIGHT 3 int jimmy [HEIGHT][WIDTH]; int n,m; int main () { for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++)

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) { jimmy[n][m]=(n+1)*(m+1); } return 0; } // arrays as parameters #include <iostream> using namespace std; void printarray (int arg[], int length) { for (int n=0; n<length; n++) cout << arg[n] << " "; cout << "\n"; } int main () { int firstarray[] = {5, 10, 15}; int secondarray[] = {2, 4, 6, 8, 10}; printarray (firstarray,3); printarray (secondarray,5); return 0; }

Array of objects:We know that an array can be of any data type including struct. Similarly, we can also have array of variable that are of the type class.Such variable are called arrays of objects. Consider the following class definition. class employee { char name[30]; float age; public: void getdata(void); void putdata(void); }; The identifier employee is a user-defined data type and can be used to create objects that relate to different categories of the employee. employee manager[3]; employee foreman[15]; employee worker[75]; The array manager contains three objects(managers),namely,manager[0], manager[1],manager[2],of type employee class. Similarly the foreman array contains 15 objects and the worker array ciontains 75 objects Sonce an array of objects behave like any other array,we can use the usualarray accessing methods to access individual element ,and then the dot member operator to access the member functions. For example the statement Manager[i].putdata(); Will display the data of the ith eelement of the array manager. That is ,this statementrequired the objects manager[i] to invoked the member function putdata()

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) An array of objects is stored inside the memory in the same way as a multi-dimensional array. The array manager is represented in fig . Note that only the space for data items of the objects is created.Member function are stored separately and will be used by all the objects. Name Age Name Age Name Age Example:class employee { char name[30]; float age; public: void getdata( void); void putdata(void); }; void employee ::getdata(void) { cout<<Enter name; cin>>name; cout<<Enter age; cin>>age; } void employee ::putdata(void) { cout<<name<<age; } const int size=3; int main() { employee manager[size]; for(int i=0;i<size;i++ { manager[i].getdata(); } for(i=0;i<size;i++) { manager[i].putdata(); } return 0; } manager[0] manager[1] manager[2]

Object as function Argument:Like any other data type, an object may be used as a function argument .This can be done in two ways. a) A copy of the entire object is passed to the function. b) Only the address of the object is transferred to the function.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) The first method is called pass by value .Since a copy of the object is passed to the function, any changes made to the object inside the function do not affect the object used to call the function .The second method is called pass by-reference. When an address of the object is passed ,the called function works directly on the actual object used in the call. This means that any changes made to the object inside the function will reflect in the actual object .The pass by reference method is more efficient since it requires to pass only the address of the object and not the entire object. Example:class time { int hours,minutes; public: void gettime(int h ,int m) { hours=h; minutes=m; } void puttime(void) { cout<<endl<<hours<<minutes; } void sum(time ,time); }; void time::sum(time t1 , time t2) { minutes=t1.minutes+t2.minutes; hours=minutes/60; minutes=minutes%60; hours=hours+t1.hours+t2.hours; } main() { time T1,T2,T3; T1.getdata(2,45); T2.getdata(3,30); T3.sum(T!,T2); T1.puttime(); T2.puttime(); T3.puttime(); return 0; } Constructor: Constructor is a special member function whose task is to initialize the object of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an ibject of its associated class is created.It is called constructor because it constructs the values of data members of the class. A constructor is declared and defined as follows. //class with a constructor class integer { int m,n; public: integer(void); };

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) integer ::integer(void) { m=0; n=0; } When a class contains a constructor like the one defined above, it is guaranted that an object created by the class will be initialized automatically. For example the declaration integer obj1; Not only create the object obj1 of type integer but also initializes its data members m and n to zero .There is no need to write any statement to invoke the constructor function .If a normal member function is defined for zero initialization .we would need to invoke this function for each of the objects separately .This would be very inconvenient, if there are a large number of objects. A constructor that accepts no parameters is called the default constructor.The default constructors for class A is A::A(). If no such constructor is defined, then the compiler supplies a default constructors. Therefore a statement such as A a; Invoked the default constructors of the compiler to create the object a. The constructor functions have some special characteristics. These are. a) They should be declared in the public section. b) They are invoked automatically when the object are created. c) They do not have return types, not even void and therefore ,and they cannot return values. d) They cannot be inherited ,through a derived class can call the base class constructor e) Constructors cannot be Virtual. f) We cannot refer to their addresses. Remember ,when a constructor is declared for a class ,initialization of the class objects becomes mandatory.

Parameterized Constructors:
The constructor integer() , defined above, initialized the data members of all the objects to zero , However , in practice it may be necessary to initialize the variable data elementof different objects with different values when they are created. C++ permits us to achieve this objects by passing arguments to the constructor function when the objects are created. The constructors that can take arguments are called parameterized constructors. The constructor integer() may be modified to take arguments as shown below. Class integer { int m,n; public: integer(int x,int y) }; integer :: integer(int x,int y) { m=x;n=y; } When a constructors has been parameterized, the object declaration statement such as Integer objects; May not work.we must pass the initial values as arguments to the constructor function when an object is declared. This can be done in two ways. By calling the constructor explicitly By calling the constructor implicitly The following declaration illustrates the first methd. Integer objects=integer(0,100); //explicit call This statement created an integer object Objects and passed the values 0 and 100 to it. The second is implemented as follows. Integer objects(0,100); This method , sometimes called the shorthand method ,is used very often as it is shorter, looks better and is easy to implement. Remember, when the constructor is parameterized,we must provide appropriate argument for the constructor.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Example: class integer { int m,n; public: integer(int,int); void display(void) { cout<<endl<<m<<n; } }; integer:: integer(int x,int y) { m=x; n=y; } void main() { integer objects(0,100); integer objects2=integer(25,75); objects.display(); objects2.display(); return 0; } Multiple Constructor in a Class:We have used two kinds of constructors They are integer(); // No argument integer(int ,int); //Two argument In the first case ,the constructor itself supplies the data values and no values are passed by the calling program. In the second case, the function call passed the appropriatevalues from main(). C++ permits us to used both these constructors in the same class. Foe Examplewe could define a class as follows. class integer { int M,N; public: integer() // Constructor1 { m=0;n=0; } integer(int a,int b) //Constructor 2 { m=a; n=b; } integer(integer & i) //Constructor 3 { m=i.m; n=i.n; }; This declare three constructors for an integer object. The first constructor receivedno arguments, the second received two integer argument and the third received one integer objects as an argument. For example ,the declaration integerI1;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) would automatically invoke the first constructor and set both m and n of I1 to zero.The statement integer I2(20,40); would call the second constructor which will initialize the data members m and N of I2to 20 and 40 respectively. Finally ,the statement integer I3(I2); would invoke the third constructor which copies the values of I2 into I3. In other words,it set the value of every data element of I3 to the value of the corresponding data elementof I2. As mentioned earlier,such a constructors is called the copy constructor. Example:class Complex { float x,y; public: Complex() { } Complex(float a) { x=a;y=a; } Complex(float real,float imag) { x=real ;y=imag; }

main() { Complex A(2.7,3.5); Complex B(1.6); Complex C; }

Dynamic initialization of Objects Class objects can be initialized dynamically too. That is to say ,the initial value of an object may be provided during run time. One advantage of dynamic initialization is that we can provided various initialization formats, using overloaded constructor .This provides the flexibility of using different format of data at run time depending upon the situation. Consider the program of long term deposit. class FixedDeposite { long int P_amount; int Years; float Rate; float R_Value; public: FixedDeposite() { } FixedDeposite(long int p,int y,float r=0.12); FixedDeposite(long int p,int y,int r); void display(void); }; FixedDeposite:: FixedDeposite(long int p, int y,float r)

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) { .. } FixedDeposite::FixedDeposite(long int p,int y,int r) { . } Void FixedDeposite::display(void) { .. } main() { FixedDeposite FD1,FD2,FD3; long int p; int y; float r; int R; cout<<enter amount,period,interest,rate; cin>>p>>y>>R; FD1=FixedDeposite(p,y,R); cout<<enter amount,period,interest,rate; cin>>p>>y>>R; FD2=FixedDeposite(p,y,R); FD3.display(); return 0; } Dynamic Constructors:The constructors can also be used to allocated memory while creating objects. This will enablethe system to allocate the right amount of memory for each object when the object are not of the same size.,thus resulting in the saving of memory.Allocation of memory to objects at the time of their construction is known as dynamic construction of objects. The memory is allocated with the help of the new operator. Example class String { char*name; int length; public: string() { length=0; name=new char[length+1]; } string(char *s) { length=strlen(s); name=new char[length+1] strcpy(name,s);

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) } void display(void) { cout<<name; } void join(String &a,String &b); }; void string :: join(String &a,String &b) { length=a.length+b.length; delete name; name=new char[length+1]; strcpy(name,a.name); strcat(name,b.name); }; main() { char *first=Ganesh; string name1(first), name2(Sushil),name3(Meshram),s1,s2; s1.join(name1,name2); s2.join(s1,name3); name1.display(); name2.display(); name3.display(); s1.display(); s2.display(); return 0; } Const Objects:We may create and use constant objects using const keyword before object declaration. For example, we may create X as a constant object of the class matrix as follows. const matrix X(m,n); // object X is Constant Any attempt to modify the values of m and n will generate compile time error. Further a constant object can call only const member functions. As we know, a const member is a function prototype or function definition where the keywords const appears after the functions signatures. Whenever const objects try to invoke non-const member functions, the compiler generates error. Destructors:A destructor, as the name implies, is used to destroy the objects that have been created a constructors. Like a constructor,the destructor is a member function whose name is the same as the class name but is preceded by a tilde. For Example,the destructor for the class integer can be defined as shown below. ~integer() { } A destructor never taken any argument nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program to clear up storage that is no longer accessible. It is a good practice to declare destructor in a program since it released memory space for future use. Whenever new is used to allocate memory in the constructors, we should use delete to free the memory. For example,the destructor for the matrix class discussed above may be defined as follows. matrix :: ~matrix() { for(int i=0;i<10;i++) delete p[i]; delete p;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) } Example :class alpha { public: alpha() { . . } ~alpha() { } }; void main() { }

OPERATOR OVERLOADING
The term operator overloading means giving the C++ operators such as ( -, +, --, ++, *, /, >, <, >=, <= etc.) , additional meanings while applying on user-defined data types. For example, the statement: z=x+y; can be applied only to basic data-types such as float, int, double, long etc. But consider a case where x, y and z are objects of a user-defined class. In this case, the above statement is not legal. However, by making use of operator overloading, the above statement can be made legal. Operator overloading provides a flexibility to create new definitions for most of the C++ operators. By using classes to create new variables and operator overloading to create definitions for operators, one can create a new language of ones own design. The users cant redefine the following operators. :: ( scope resolution operator ) . ( member selection ) .* ( member selection through pointer to function ) sizeof ( size of operator ) ?: ( conditional operator )

Overloading Unary Operator:


Unary operators act on only one operand. Some commonly used unary operators are unary minus (-), increment (++) and decrement (--) operators. Let us start by overloading the unary minus operator. The unary minus operator changes the sign of an operand when applied to basic data-type ( int, float, double etc. ). The following program, demonstrates how to overload this operator so that it can be applied to an object in much the same way as is applied to an int or float type variable. Program

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) //****This program illustrates the overloading of unary munus ( - ) operator****** #include <iostream.h> class Minus { private: int a, b, c ; public: Minus( ) // Default Constructor { } Minus(int A, int B, int C) { a=A; b=B; c=C; } void display(void); //********Declaration of the operator function********** void operator - ( ); // End of the Class Definition

};

//***********Member Function Definitions************* inline void Minus :: display(void) { cout << "\t a = " << a << endl ; cout << "\t b = " << b << endl ; cout << "\t c = " << c << endl ; } //*********Definition of the operator function*********** inline void Minus :: operator - ( ) { a = -a ; b = -b ; c = -c ; } //*************Main Function Definition*************** void main(void) { Minus M(5, 10, -15) ; cout << "\n Before activating the operator - ( )\n" ; M.display( ) ; -M ; cout << "\n After activating the operator - ( )\n" ; M.display( ) ; } Output:Before activating the operator () a=5 b=10 c=-15 After activating the operator () a= -5 b=10 c=- -15

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Operator Function To overload an operator, a special function called operator function is used. The general syntax of an operator function is: return_type class_name :: operator operator_type( agruments ) { Body of the function } Here, return_type is the type of the value returned by the specified operation. The keyword operator is used to overload the specified operator operator_type is the operator which has to be overloaded. The combination of the keyword operator and the operator_type i.e. operator operator_type represents the name of the function. For example, in the above program the declarative of the operator function is given as: void operator ( ) ; This declarative tells the compiler to call this member function, whenever the operator is encountered, provided the operand is of type Minus. In the main( ) function of this program, the object M of type Minus is declared and initialized to ( 5, 10, -15 ) as: Minus M( 5, 10, -15 ) ; Before activating the operator function, the values of a, b and c are displayed as: a=5 b = 10 c = -15 After the statement -M; the operator function gets activated and the values of a, b and c are displayed as: a = -5 b = -10 c = 15 In the above program, the function operator ( ) takes no argument. This function is a member function, and the member functions can directly access the members of an object for which they have been called. Therefore, the operator function for overloading the unary minus operator ( - ) does not require any argument.

Operator Function with return value


The operator ( ) function defined in the above program has a problem. If one wants to use a statement such as: M2 = -M1 ; in the main( ), the compiler will complain! The reason is that the operator function operator ( ) has been defined to have a return type of void, while the assignment statement is being asked to return a variable of type Minus. Thus, the statements such as M2 = -M1 ; in the main( ) can be made available by following definition of the operator function: Minus operator ( ) { Minus temp ; temp.a = -a ; temp.b = -b ; temp.c = -c ; return temp ; }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Program /* This program illustrates the overloading of the unary minus (-) operator. The operator function in this program uses a return value. */ #include //******Class Definition******** class Minus { private: int a, b, c ; public: //**********Member Functions*************** Minus( ) // Default Constructor {} Minus(int A, int B, int C) {a=A;b=B;c=C;} void display(void) { cout << "\t a = " << a << endl ; cout << "\t b = " << b << endl ; cout << "\t c = " << c << endl ; } //********Operator Function Definition ******* Minus operator - (void) // Declarative with the return type Minus { Minus temp ; temp.a = -a ; temp.b = -b ; temp.c = -c ; return temp ; } } ; // End of the class definition //*******Main Functiion************ void main(void) { Minus M1(5, 10, -15); // Initialization of the object M1 of type Minus cout << "\n Before activating the operator -( ):\n" ; M1.display( ) ; Minus M2 ; // Definining the object M2 of type Minus M2 = -M1 ; // Activates the function operator -( ) and // assigns the value of -M1 to M2 cout << "\n After activating the operator -( ):\n" ; M2.display( ) ; } Output :Before activating the operator -(); A=5 B=10 C= -15 Before activating the operator -(); A= -5 B= -10 C= 15 In the above program, the operator ( ) function creates a new object, named as temp of type Minus, for returning the values.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) This type of object is known as temporary object. The values of the member data i.e. a, b and c are assigned to this temporary object temp as: temp.a = -a ; temp.b = -b ; temp.c = -c ; Finally, the function returns the object temp as: return temp ; Thus, the statement like M2 = -M1 ; can be used in the main( ) function.

Overloading the increment operator ( ++ ) #include class Increment { private: int count ; public: //*****Member Function Definitions****** Increment( ) // Default Constructor { count = 0 ; } Increment(int C) // Constructor with Argument { count = C ; } Increment operator ++ ( ) // Operator Function Definition { count++ ; return Increment(count); } void display(void) // Function for displaying the output { cout << count << endl ; } }; // End of the class definition void main(void) { Increment I1, I2(5), I3, I4 ; cout << "\n Before activating the operator ++( )\n" ; cout << " I1 = " ; I1.display( ); cout << " I2 = " ; I2.display( ); ++I1 ; // I1 and I2 are incremented I2++ ; cout << "\n After activating the operator ++( )\n" ; cout << " I1 = " ; I1.display( );

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) cout << " I2 = " ; I2.display( ) ; I3 = ++I1 ; /* Here, the objects I1 and I2 are incremented again and their I4 = I2++ ; values are assigned to the objects I3 and I4 respectively */ cout << " I3 = " ; I3.display( ) ; cout << " I4 = " ; I4.display( ) ; } Output

In the above program, when the increment operator ++ is overloaded using the function operator ++ ( ) there is no distinction between prefix and postfix notation. That is why all the statements I1++ ; ++I2 ; and I3 = I1++ ; I4 = ++I2 ; have the same effect i.e. they are incremented using the prefix notation only. In order to make both notations of the increment operator (prefix & postfix) to work, the programmer must define two separate functions as: operator ++ ( ) // For prefix operator ++ ( int ) // For postfix The operator function for overloading postfix increment operator uses a dummy argument int, which is automatically set to 0 by the postfix operator ++. This dummy argument allows the compiler to distinguish the two forms (prefix, postfix) of the increment operator. In reality it is not an argument and it does not mean an integer. It is simply a signal to the compiler to create the postfix notation of the operator. The definitions of the functions for overloading + and binary operators are given as: complex operator + ( complex c ) { complex temp ; temp.real = real + c.real ; temp.imaginary = imaginary + c.imaginary ; return temp ; } complex operator ( complex c )

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) { complex temp ; temp.real = real c.real ; temp.imaginary = imaginary c.imaginary ; return temp ; } These two operator functions add and subtract two complex numbers and return the resultant complex values respectively. Notice that both these functions receive only one value as argument. Now a question arises that from where the other value comes. Let us look at the statements that invoke the operator functions: c3 = c1 + c2 ; // Invokes operator + ( ) function c4 = c1 c2 ; // Invokes operator ( ) function It has been discussed that an object of the same class can invoke a member function. In above statement, the object c1 takes the responsibility of invoking the function and c2 plays the role of an argument that is passed to the function. The above invocation statements are equivalent to: c3 = c1.operator + ( c2 ) ; // Usual function call syntax c4 = c1.operator ( c2 ) ; Thus in the functions, operator + ( ) and operator ( ), the data members of c1 are accessed directly and the data members of c2 (that is passed as an argument) are accessed using the dot operator (.). Thus, both the objects are available for the function. For example, in the statement: temp.real = real + c.real ; real refers to the object c1 and c.real refers to the object c2. temp.real is the real part of the complex that has been created to hold the result of addition of c1 and c2. Binary operator overloading example: #include <iostream.h> class Exforsys { private: int x; int y; public: Exforsys() { x=0; y=0; }

//Constructor

void getvalue( ) //Member Function for Inputting Values { cout << \n Enter value for x: ; cin >> x; cout << \n Enter value for y: ; cin>> y; } void displayvalue( ) //Member Function for Outputting Values { cout <<value of x is: << x <<; value of y is: <<y }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Exforsys operator +(Exforsys); }; Exforsys Exforsys :: operator + (Exforsys e2) //Binary operator overloading for + operator defined { int x1 = x+ e2.x; int y1 = y+e2.y; return Exforsys(x1,y1); } void main( ) { Exforsys e1,e2,e3; //Objects e1, e2, e3 created cout<<\nEnter value for Object e1:; e1.getvalue( ); cout<<\nEnter value for Object e2:; e2.getvalue( ); e3= e1+ e2; //Binary Overloaded operator used cout<< \nValue of e1 is:<<e1.displayvalue(); cout<< \nValue of e2 is:<<e2.displayvalue(); cout<< \nValue of e3 is:<<e3.displayvalue(); }

Rules for overloading Operators: a) Only existing operators can be overloaded .New operators cannot be created. b) The overloaded operator must have at least one operand that is of user-defined type. c) We cannot change the basic meaning of an operator. That is to say, we cannot redefined the plus (+) operator to subtract one value from the other. d) Overloaded operators follow the syntax rules of the original operators. They cannot be overridden. e) There are some operators that cannot be overloaded. f) We cannot used friend function to overload certain operators. However , member functions can be used to overload them. g) Unary operators, overloaded by means of a member function, take no explicit argument and return no explicit values ,but ,those overloaded by means of a friend function ,take one reference argument. h) Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments. i) When using binary operators overloaded through a member function , the left hand operand must be an object of the relevant class. j) Binary arithmetic operators such as + , - , * , / must explicitly return a value. They must not attempt to change their own argument.

INHERITANCE
Inheritance is the process of creating new classes from the existing class or classes. Using inheritance, one can create general class that defines traits common to a set of related items. This class can then be inherited (reused) by the other classes by using the properties of the existing ones with the addition of its own unique properties. The old class is referred to as the base class and the new classes, which are inherited from the base class, are called derived classes.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

In above figure, the class B contains the three member i.e. Property1, Property2 and Property3. The second class named as D contains four members i.e. Property1, Property2, Property3 and Property4. Out of these, three members (Property1, Property2, Property3) of the class D are same as that of class B, while the one member i.e. Property4 is unique. In the class D, instead of defining all the three members again, one can reuse them from the class B. This feature is known as inheritance which saves time, space, money and increases the reliability and efficiency.

Forms of Inheritance
Single Inheritance If a class is derived from a single base class, it is called as single inheritance. Multiple Inheritance If a class is derived from more than one base class, it is known as multiple inheritance Multilevel Inheritance The classes can also be derived from the classes that are already derived. This type of inheritance is called multilevel inheritance. Hierarchical Inheritance If a number of classes are derived from a single base class, it is called as hierarchical inheritance A derived class can be defined as follows: class derived_class_name : access_specifier base_class_name { data members of the derived class ; member functions of the derived class ; }

The colon (:), indicates that the class derived_class_name is derived from the class base_class_name. The access_specifier may be public, private or protected (will be discussed further). If no access_specifier is specified, it is private by default.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) The access_specifier indicates whether the members of the base class are privately derived or publicly derived. Public inheritance When a derived class publicly inherits the base class, all the public members of the base class also become public to the derived class and the objects of the derived class can access the public members of the base class. The following program will illustrate the use of the single inheritance. This program has a base class B, from which class D is inherited publicly.
Example: #include class Rectangle { private: float length ; // This can't be inherited public: float breadth ; // The data and member functions are inheritable void Enter_lb(void) { cout << "\n Enter the length of the rectangle : "; cin >> length ; cout << "\n Enter the breadth of the rectangle : "; cin >> breadth ; } float Enter_l(void) { return length ; } }; // End of the class definition class Rectangle1 : public Rectangle { private: float area ; public: void Rec_area(void) { area = Enter_l( ) * breadth ; } // area = length * breadth ; can't be used here void Display(void) { cout << "\n Length = " << Enter_l( ) ; cout << "\n Breadth = " << breadth ; cout << "\n Area = " << area ; } }; void main(void) { Rectangle1 r1 ; r1.Enter_lb( ); r1.Rec_area( ); r1.Display( ); } Figure- Public Inheritance // End of the derived class definition D

// Object of the derived class can't // inherit the private member of the base class. Thus the member // function is used here to get the value of data member 'length'.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Private inheritance When a derived class privately inherits a base class, all the public members of the base class become private for the derived class. In this case, the public members of the base class can only be accessed by the member functions of the derived class. The objects of the derived class cannot access the public members of the base class. Note that whether the derived class is inherited publicly or privately from the base class, the private members of the base class cannot be inherited. Example: #include #include class Rectangle { int length, breadth; public: void enter() { cout << "\n Enter length: "; cin >> length; cout << "\n Enter breadth: "; cin >> breadth; } int getLength() { return length; } int getBreadth() { return breadth; } void display()

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) { cout << "\n Length= " << length; cout << "\n Breadth= " << breadth; } }; class RecArea : private Rectangle { public: void area_rec() { enter(); cout << "\n Area = " << (getLength() * getBreadth()); } }; void main() { clrscr(); RecArea r ; r.area_rec(); getch(); } Example:2 #include class Rectangle // Base class { private:
float length ; // This data member can't be inherited public: float breadth ; // This data member is inheritable void Enter_lb(void) { cout << "\n Enter the length of the rectangle: "; cin >> length ; cout << "\n Enter the breadth of the rectangle: "; cin >> bredth ; } float Enter_l(void) { return length ; } void Display_l(void) { cout << "\n Length = " << length ; } }; // End of the base class Rectangle. // Defining the derived class Rectangle1. This class has been derived from the // base class i.e. Rectangle, privately. class Rectangle1 : private Rectangle // All the public members of the base class { // Rectangle become private for the derived class Rectangle1. private: float area ; public: void Rec_area(void) { Enter_lb( ); area = Enter_l( ) * bredth ; // length can't be used directly } void Display(void) { Display_l( ); // Displays the value of length.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)
cout << "\n Bredth = " << bredth ; cout << "\n Area = " << area << endl ; } }; void main(void) { Rectangle1 r1 ; r1.Rec_area( ) ; // r.Enter_lb( ); will not work as it has become private for the derived class. r1.Display( ) ; // r.Display_l( ) will not work as it also has become private for the derived class.

} Fig: private inheritance

The protected access specifier The third access specifier provided by C++ is protected. The members declared as protected can be accessed by the member functions within their own class and any other class immediately derived from it. These members cannot be accessed by the functions outside these two classes. Therefore, the objects of the derived class cannot access protected members of the base class. When the protected members (data, functions) are inherited in public mode, they become protected in the derived class. Thus, they can be accessed by the member functions of the derived class. On other hand, if the protected members are inherited in the private mode, the members also become private in the derived class. They can also be accessed by the member functions of the derived class, but cannot be inherited further.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Overriding the member functions: The member functions can also be used in a derived class, with the same name as those in the base class. One might want to do this so that calls in the program work the same way for objects of both base and derived classes. The following program will illustrate this concept. #include const int len = 20 ; class Employee { private: char F_name[len]; int I_number ; int age ; float salary ; public: void Enter_data(void) { cout << "\n Enter cout << "\n Enter cout << "\n Enter cout << "\n Enter

the the the the

first name = " ; cin >> F_name ; identity number = " ; cin >> I_number ; age = " ; cin >> age ; salary = " ; cin >> salary ;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)
} void Display_data(void) { cout << "\n Name = " << F_name ; cout << "\n Identity Number = " << I_number ; cout << "\n Age = " << age ; cout << "\n Salary = " << salary ; } }; // End of the base class class Engineer : public Employee { private: char design[len] ; // S_Engineer, J_Engineer, Ex_Engineer etc public: void Enter_data( ) { Employee :: Enter_data( ) ; // Overriding of the member function cout << "\n Enter the designation of the Engineer: " ; cin >> design ; } void Display_data(void) { cout << "\n *******Displaying the particulars of the Engineer**** \n" ; Employee :: Display_data( ) ; // Overriding of the member function cout << "\n Designition = " << design ; } // End of the derived class

};

void main(void) { Engineer er ; er.Enter_data( ) ; er.Display_data( ); }

Hierarchical Inheritance: When two or more classes are derived from a single base class, then Inheritance is called the hierarchical inheritance. The representation of the hierarchical inheritance is shown in the following Fig.

In the above Fig., student is a base class, from which the three classes viz. arts, science and commerce have been derived. Now, let us write a program that illustrates the hierarchical inheritance, based on the above design.

Example include<iostream.h> const int len = 20 ; class student {

// Base class

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)
private: char F_name[len] , L_name[len] ; int age, int roll_no ; public: void Display_data(void) { cout << "\n\t First Name = " << F_name ; cout << "\n\t Last Name = " << L_name ; cout << "\n\t Age = " << age ; cout << "\n\t Roll Number = " << roll_no ; } }; class arts : public student { private: char asub1[len] ; char asub2[len] ; char asub3[len] ; public: void Enter_data(void) { student :: Enter_data( ); cout << "\t Enter the subject1 of the arts student: "; cin >> asub1 ; cout << "\t Enter the subject2 of the arts student: "; cin >> asub2 ; cout << "\t Enter the subject3 of the arts student: "; cin >> asub3 ; } void Display_data(void) { student :: Display_data( ); cout << "\n\t Subject1 of the arts student = " << asub1 ; cout << "\n\t Subject2 of the arts student = " << asub2 ; cout << "\n\t Subject3 of the arts student = " << asub3 ; } }; class commerce : public student { private: char csub1[len], csub2[len], csub3[len] ; public: void Enter_data(void) { student :: Enter_data( ); cout << "\t Enter the subject1 of the commerce cin >> csub1; cout << "\t Enter the subject2 of the commerce cin >> csub2 ; cout << "\t Enter the subject3 of the commerce cin >> csub3 ; } void Display_data(void) { student :: Display_data( ); cout << "\n\t Subject1 of the commerce student cout << "\n\t Subject2 of the commerce student cout << "\n\t Subject3 of the commerce student } };

student: "; student: "; student: ";

= " << csub1 ; = " << csub2 ; = " << csub3 ;

void main(void) { arts a ; cout << "\n Entering details of the arts student\n" ; a.Enter_data( ); cout << "\n Displaying the details of the arts student\n" ; a.Display_data( ); science s ; cout << "\n\n Entering details of the science student\n" ;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)
s.Enter_data( ); cout << "\n Displaying the details of the science student\n" ; s.Display_data( ); commerce c ; cout << "\n\n Entering details of the commerce student\n" ; c.Enter_data( ); cout << "\n Displaying the details of the commerce student\n"; c.Display_data( ); } Multiple Inheritance When a class is inherited from more than one base class, it is known as multiple inheritance. The syntax for defining a subclass, which is inheriting more than one classes is: class Subclass : access_specifier Baseclass1, access_specifier Baseclass2, .. access_specifier Baseclass_n { members of the derived class ; }; The following figure illustrates the use of multiple inheritance.

In the above figure, Circle and Rectangle are two base classes from which the class Cylinder is being inherited. The data members of both the base classes are declared in protected mode. Thus, the class Cylinder can access the data member radius of class Circle and data member length, breadth of the class Rectangle, but the objects of the class Cylinder cannot access these protected data members. The volume of the cylinder is equal to 22/7*(radius*radius*length). Thus, instead of defining these data again, they can be inherited from the base classes Circle and Rectangle ( radius from class Circle and length from class Rectangle ).
Example: #include class Circle // First base class { protected: float radius ; public: void Enter_r(void) { cout << "\n\t Enter the radius: "; cin >> radius ;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)
} void Display_ca(void) { cout << "\t The area = " << (22/7 * radius*radius) ; } }; class Rectangle // Second base class { protected: float length, breadth ; public: void Enter_lb(void) { cout << "\t Enter the length : "; cin >> length ; cout << \t Enter the breadth : ; cin >> breadth ; } void Display_ar(void) { cout << "\t The area = " << (length * breadth); } }; class Cylinder : public Circle, public Rectangle // Derived class, inherited { // from classes Circle & Rectangle public: void volume_cy(void) { cout << "\t The volume of the cylinder is: " << (22/7* radius*radius*length) ; } }; void main(void) { Circle c ; cout << "\n Getting the radius of the circle\n" ; c.Enter_r( ); c.Display_ca( ); Rectangle r ; cout << "\n\n Getting the length and breadth of the rectangle\n\n"; r.Enter_l( ); r.Enter_b( ); r.Display_ar( ); Cylinder cy ; // Object cy of the class cylinder which can access all the // public members of the class circle as well as of the class rectangle cout << "\n\n Getting the height and radius of the cylinder\n"; cy.Enter_r( ); cy.Enter_lb( ); cy.volume_cy( ); }

Multilevel Inheritance:
It has been discussed so far that a class can be derived from a class. C++ also provides the facility of multilevel inheritance, according to which the derived class can also be derived by an another class, which in turn can further be inherited by another and so on. The following figure will illustrate the meaning of the multilevel inheritance.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

In the above figure, class B represents the base class. The class D1 that is called first level of inheritance, inherits the class B. The derived class D1 is further inherited by the class D2, which is called second level of inheritance. Example: Multilevel Inheritance #include<iostream.h> class Base { protected: int b; public: void EnterData( ) { cout << "\n Enter the value of b: "; cin >> b; } void DisplayData( ) { cout << "\n b = " << b; } }; class Derive1 : public Base { protected: int d1; public: void EnterData( ) { Base:: EnterData( ); cout << "\n Enter the value of d1: "; cin >> d1; } void DisplayData( ) { Base::DisplayData(); cout << "\n d1 = " << d1; } }; class Derive2 : public Derive1 { private: int d2; public: void EnterData( ) {

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Derive1::EnterData( ); cout << "\n Enter the value of d2: "; cin >> d2; } void DisplayData( ) { Derive1::DisplayData( ); cout << "\n d2 = " << d2; } }; int main( ) { Derive2 objd2; objd2.EnterData( ); objd2.DisplayData( ); return 0; }

Multiple inheritance:You can derive a class from any number of base classes. Deriving a class from more than one direct base class is called multiple inheritance. In the following example, classes A, B, and C are direct base classes for the derived class X: class A { /* ... */ }; class B { /* ... */ }; class C { /* ... */ }; class X : public A, private B, public C { /* ... */ }; The following inheritance graph describes the inheritance relationships of the above example. An arrow points to the direct base class of the class at the tail of the arrow:

The order of derivation is relevant only to determine the order of default initialization by constructors and cleanup by destructors. A direct base class cannot appear in the base list of a derived class more than once: class B1 { /* ... */ }; // direct base class class D : public B1, private B1 { /* ... */ }; // error However, a derived class can inherit an indirect base class more than once, as shown in the following example:

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) class L { /* ... */ }; // indirect base class class B2 : public L { /* ... */ }; class B3 : public L { /* ... */ }; class D : public B2, public B3 { /* ... */ }; // valid

Example 1: #include <iostream> using std::ostream; using std::cout; using std::endl; class Base1 { public: Base1( int parameterValue ) { value = parameterValue; } int getData() const { return value; } protected: int value; }; class Base2 { public: Base2( char characterData ) { letter = characterData; } char getData() const { return letter; } protected: char letter; };

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) class Derived : public Base1, public Base2 { public: Derived( int integer, char character, double double1 ) : Base1( integer ), Base2( character ), real( double1 ) { } double getReal() const { return real; } void display() { cout << " Integer: " << value << "\n Character: " << letter << "\nReal number: " << real; } private: double real; };

int main() { Base1 base1( 10 ), *base1Ptr = 0; Base2 base2( 'Z' ), *base2Ptr = 0; Derived derived( 7, 'A', 3.5 ); cout << base1.getData() << base2.getData(); derived.display(); cout << derived.Base1::getData() << derived.Base2::getData() << derived.getReal() << "\n\n"; base1Ptr = &derived; cout << base1Ptr->getData() << '\n'; base2Ptr = &derived; cout << base2Ptr->getData() << endl; return 0; }

Multilevel Inheritance:It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for it's parent class and this parent class works as the child class for it's just above ( parent ) class. Multilevel inheritance can go up to any number of level. what is multi level inheritance give n example ? Example 1 :The best example is Say we have 3 class ClassA,ClassB and ClassC. ClassB is derived from ClassA and ClassC is derived ClassB this is multi level inheritance.. ClassA

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) ^ | ClassB ^ | ClassC

Example 2:A class is derive from a class which is derive from another class is known as multilevel inheritance. example-grandpa->papa->son another example: class A { protected: int x; public: void showA() { cout<<"enter a value for x:"<<endl; cin>>x; } }; class B:public A { protected: int y; public: void showB() { cout<<"enter value for y:"; cin>>y; } }; class C:public B { public: void showC() { showA(); showB(); cout<<"x*y ="<<x*y; } }; void main() { C ob1; ob1.showc(); } Example 3: #include< iostream.h> #include< conio.h>

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) class student // Base Class { protected: int rollno; char *name; public: void getdata(int b,char *n) { rollno = b; name = n; } void putdata(void) { cout< < " The Name Of Student \t: "< < name< < endl; cout< < " The Roll No. Is \t: "< < rollno< < endl; } }; class test:public student // Derieved Class 1 { protected: float m1,m2; public: void gettest(float b,float c) { m1 = b; m2 = c; } void puttest(void) { cout< < " Marks In CP Is \t: "< < m1< < endl; cout< < " Marks In Drawing Is \t: "< < m2< < endl; } }; class result:public test // Derieved Class 2 { protected: float total; public: void displayresult(void) { total = m1 + m2; putdata(); puttest(); cout< < " Total Of The Two \t: "< < total< < endl; } };

void main() {

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) clrscr(); int x; float y,z; char n[20]; cout< < "Enter Your Name:"; cin>>n; cout< < "Enter The Roll Number:"; cin>>x; result r1; r1.getdata(x,n); cout< < "ENTER COMPUTER PROGRAMMING MARKS:"; cin>>y; cout< < "ENTER DRAWING MARKS:"; cin>>z; r1.gettest(y,z); cout< < endl< < endl< < "************ RESULT **************"< < endl; r1.displayresult(); cout< < "**********************************"< < endl; getch(); } /************ OUTPUT ************ Enter Your Name:Lionel Enter The Roll Number:44 ENTER COMPUTER PROGRAMMING MARKS:95 ENTER DRAWING MARKS:90

************ RESULT ************** The Name Of Student : Lionel The Roll No. Is : 44 Marks In CP Is : 95 Marks In Drawing Is : 90 Total Of The Two : 185 ********************************** class A { int x; int y; int get(int p, int q) { x=p; y=q; return(0); } void Show() { System.out.println(x); } } class B extends A { void Showb() { System.out.println("B");

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) } } class C extends B { void display() { System.out.println("C"); } public static void main() { A a = new A(); a.get(5,6); a.Show(); } } }

Hybrid Inheritance :#include<iostream.h> class a { public: void f() { cout<<"base class\n"; } }; class b:private a //visibility mode private { public: void f1() { cout<<"inheritance\n"; } }; class c:public a //visibility mode public { public: void f2() { cout<<"hybrid\n"; } }; class d:public b,public c void main() { d w; w.f(); //giving ambiguity error }

Example 2:
#include<iostream.h> class a

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) { public: void f() { cout<<"base class\n"; } }; class b: private a //visibility mode private { public: void f1() { cout<<"inheritance\n"; } }; class c: public a //visibility mode public { public: void f2() { cout<<"hybrid\n"; } }; class d: public b,public c void main() { d w; w.f(); //giving ambiguity error } Example 3: #include< iostream.h> #include< conio.h> class student { private : int rn; char na[20]; public: void getdata() { cout< < "Enter Name And Roll No : "; cin>>na>>rn; } void putdata() { cout< < endl< < na< < "\t"< < rn< < "\t"; } }; class test : public student { protected: float m1,m2; public: void gettest() {

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) cout< < endl< < "Enter your marks In CP 1 And Cp 2 :"; cin>>m1>>m2; } void puttest() { cout< < m1< < "\t"< < m2< < "\t"; } }; class sports { protected: float score; public: void getscore() { cout< < endl< < "Enter your score :"; cin>>score; } void putscore() { cout< < score< < "\t"; } }; class results : public test , public sports { private : float total; public : void putresult() { total = m1+m2+score; cout< < total; } }; void main() { results s[5]; clrscr(); for(int i=0;i< 5;i++) { s[i].getdata(); s[i].gettest(); s[i].getscore(); } cout< < "______________________________________________"< < endl; cout< < endl< < "Name\tRollno\tCP 1\tCP 2\tScore\tTotal"< < endl; cout< < "----------------------------------------------"< < endl; for(i=0;i< 5;i++) { s[i].putdata(); s[i].puttest(); s[i].putscore(); s[i].putresult(); }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) cout< < endl< < "----------------------------------------------"; getch(); } /********** OUTPIUT ********** Enter Name And Roll No : Lionel 1 Enter your marks In CP 1 And Cp 2 :45 Enter your score :45 Enter Name And Roll No : Cyril 65 Enter your marks In CP 1 And Cp 2 :49 42 Enter your score :45 Enter Name And Roll No : Mayank 40 Enter your marks In CP 1 And Cp 2 :41 43 Enter your score :46 Enter Name And Roll No : Dylan 78 Enter your marks In CP 1 And Cp 2 :23 24 Enter your score :25 Enter Name And Roll No : Ansha 39 Enter your marks In CP 1 And Cp 2 :45 45 Enter your score :45 ______________________________________________ Name Rollno CP 1 CP 2 Score Total ---------------------------------------------Lionel 1 45 23 45 113 Cyril 65 49 42 45 136 Mayank 40 41 43 46 130 Dylan 78 23 24 25 72 Ansha 39 45 45 45 135

Virtual Base Class:Virtual base classes (C++ only)

Suppose you have two derived classes B and C that have a common base class A, and you also have another class D that inherits from B and C. You can declare the base class A as virtual to ensure that B and C share the same subobject of A. In the following example, an object of class D has two distinct subobjects of class L, one through class B1 and another through class B2. You can use the keyword virtual in front of the base class specifiers in the base lists of classes B1 and B2 to indicate that only one subobject of type L, shared by class B1 and class B2, exists. For example:

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

class L { /* ... */ }; // indirect base class class B1 : virtual public L { /* ... */ }; class B2 : virtual public L { /* ... */ }; class D : public B1, public B2 { /* ... */ }; // valid Using the keyword virtual in this example ensures that an object of class D inherits only one subobject of class L. A derived class can have both virtual and nonvirtual base classes. For example:

class V { /* ... */ }; class B1 : virtual public V { /* ... */ }; class B2 : virtual public V { /* ... */ }; class B3 : public V { /* ... */ }; class X : public B1, public B2, public B3 { /* ... */ }; In the above example, class X has two subobjects of class V, one that is shared by classes B1 and B2 and one through class B3.

Abstract Classes:An abstract class is one that is not used to create object. An abstract class is designed only to act as a base class. It is a design concept in program development and provides a base upon which other classes may be built. In the previous example ,the student class is an abstract class since it was not used to create any objects. For example: class AB { public: virtual void f() = 0; }; class D2 : public AB { void g(); }; main()

{ D2 d; }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) The compiler will not allow the declaration of object d because D2 is an abstract class; it inherited the pure virtual function f()from AB. The compiler will allow the declaration of object d if you define function D2::g().Note that you can derive an abstract class from a nonabstract class, and you can override a non-pure virtual function with a pure virtual function.

Constructor in derived class :-A constructor plays a vital role in initializing an object. An important note, while using
constructors during inheritance, is that, as long as a base class constructor does not take any arguments, the derived class need not have a constructor function. However, if a base class contains a constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructor. Remember, while applying inheritance, we usually create objects using derived class. Thus, it makes sense for the derived class to pass arguments to the base class constructor. When both the derived and base class contains constructors, the base constructor is executed first and then the constructor in the derived class is executed. In case of multiple inheritance, the base class is constructed in the same order in which they appear in the declaration of the derived class. Similarly, in a multilevel inheritance, the constructor will be executed in the order of inheritance. The derived class takes the responsibility of supplying the initial values to its base class. The constructor of the derived class receives the entire list of required values as its argument and passes them on to the base constructor in the order in which they are declared in the derived class. A base class constructor is called and executed before executing the statements in the body of the derived class. The header line of the derived-constructor function contains two parts separated by a colon (:). The first part provides the declaration of the arguments that are passed to the derived class constructor and the second part lists the function calls to the base class. Example:D (int a1, int a2, int b1, int b2, int d): A(a1, a2), B(b1, b2) { d = d1; } A(a1, a2) invokes the base constructor A() and B(b1, b2) invokes another base class constructor B(). The constructor D() supply the values i.e. a1, a2, b1, b2 (to A() and B()) and to one of its own variables d1. Hence, the assignment of the values will be as follows: When an object of D is created, D object-name(5, 12, 7, 8, 30); a1 <- 5 a2 <- 12 b1 <- 7 b2 <- 8 d1 <- 30 The constructors for a virtual base class are invoked before any non-virtual base classes. If there are multiple virtual base classes, then they are invoked in the order in which they are declared.

Example:#include <iostream> #include <cstring> using namespace std; class Shape { // private double width; double height; public: void display() { cout << "Width and height are " << width << " and " << height << "\n"; } // accessor functons double getWidth() { return width; } double getHeight() { return height; }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) void setWidth(double w) { width = w; } void setHeight(double h) { height = h; } }; // Triangle is derived from Shape. class Triangle : public Shape { char style[20]; // now private public: // Constructor for Triangle. Triangle(char *str, double w, double h) { setWidth(w); setHeight(h); strcpy(style, str); } double area() { return getWidth() * getHeight() / 2; } void showStyle() { cout << "Triangle is " << style << "\n"; } }; int main() { Triangle t1("isosceles", 4.0, 4.0); Triangle t2("right", 8.0, 12.0); t1.showStyle(); t1.display(); cout << "Area is " << t1.area() << "\n"; t2.showStyle(); t2.display(); cout << "Area is " << t2.area() << "\n"; return 0; } Ans:- Triangle is isosceles Width and Height are 4 and 4 Area is 8 Triangle is right Width and height are 8 and 12 Example 2: Class alpha { int x; public: alpha(int i) { x=I; cout<<Alpha initialize; } void show_x(void)

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) { cout<<x; } }; class beta { float y; public: beta(float j) { y=j; cout<<endl<<beta initialize; } void show_y(void) { cout<<y; } }; class gamma: public beta , public alpha { int m,n; public: gamma(int a,float b , int c , int d) : alpha(a) ,beta(b) { m=c; n=d; cout<<gamma initialize; } void show_mn(void) { cout<<m<<n; } }; main() { gamma g(5,10.75,20,30); g.show_x(); g.show_y(); g.show_mn(); return 0; }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Summer 2004 Paper II: C++ OBJECT ORIENTED PROGRAMMING


Q) What is Complier ? Explain the different phased of compilation process. Q) Write short notes on I)Compiler II)Interpreter Q) Differentiate between Complier and Interpreter.

Complier Interpreter Compiler compile the source code and translate Interpreter compile the code that is already into byte code compiled that is in the form of byte code compiler scan whole code at once so it is faster as compare with Interpreter, while interpreter compiled the byte code line by line and convert in machine code so it is slow in compare with compiler An interpreter runs directly from personal-code or an Interpreted code such as Basic or Lisp. Interpreted code only finds such errors after the Application attempts to interpret the affected code.

A compiler, in general, reads higher level language computer code and converts it to either personal-code or native machine code. Compiled code runs much faster, is more compact and has already found all of the syntax errors and many of the illegal reference errors.

Q2) Difference between Low level language and High level language. Ans:Types of programming languages: 4) Low level language(Machine level language):
Low level language is also called as Machine Language or binary language which is collection of very detailed instructions that control the computer internal circuits. It is machine dependent. Very few programs are written in this language because computers have their own instruction set. It is in the form of 0s and 1s. A machine language instruction normally has a two parts format. The first part is operation code that tells the computer what function to perform, and the second part is operand that tells where to find or store the data to be manipulated.

OPCODE (operation code)

OPERAND (address/location) (Instruction format)

Advantage: Programs written in machine language can be executed very fast by a computer because machine instructions are understood by the computer without using any translator. Limitation of machine language: Machine dependent Difficult to program Error prone Difficult to modify 5) Assembly language Machine languages are very difficult for programming. However assembly languages uses mnemonic for each instruction in programs. Assembly language contains simple instruction like ADD A, SUB B etc. Advantage:

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Easier to understand and used Easier to locate and correct errors Easier to modify No worry about addresses Easily reloadable Efficiency of machine language. Disadvantage: Machine dependent Knowledge of hardware required Machine level coding 6) High level language: Above two type of language are not easy for a programming. To make programming simpler high level languages are developed. These languages contain statements that are similar to a English language and easy to learn and remember. Pascal, COBOL, FORTRAN etc are High level languages. These are machine dependent. There are three significant advantages in high level language:d) Simplicity e) Uniformity f) Profitability (machine independent) Single instruction in high level language will be equivalent to many instructions in machine language. A high level language can generally be run on many different computers. Advantage: They are machine independent. They do not required programmer to know anything about internal structure of the computer on which high level programs are executed. They do not deal with machine level coding. Easier to learn and use Fewer error Lower program preparation cost Better documentation Easier to maintain Disadvantage: 2) Lower efficiency 2) Less flexibility Q) Explain the following terms with reference to programming structure. 1) Selection, 2) Iteration. Ans :- the proper path out of two or more alternative path in program logic. Selection logic is classified into: If.then Ifelse Case structure

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

No
If (condition)

Yes
Process 1

Process 2

c) Flowchart : If condition Then process 1 Else process 2 End if : d) Pseudocode Iteration (or Looping): Iteration means repeated one statement again and again. Hence Iteration logic is used to produce loops in program logic when one or more instructions may be executed several times depending on some condition. It Uses structure: DO.WHILE REPEAT.UNTIL FOR LOOP WHILE LOOP

no
Condition

yes
Process 1

Process n

b) flowchart : Repeat Process1 Process n Until condition :

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

: c) Pseudocode d) Q1) (d) What is an Algorithm and flowcharting ? Write an algorithm to find out whether the entire number is Positive , Negative or zero. Ans:Algorithm:-

1) It is the theory representation of any problem in any types of language like English. 2) The algorithm of any language, may be written into of its steps. 3) Every steps of an algorithm has its own instructions which is written in square bracket above the shape of algorithm. 4) These is no such restriction to write the steps in the algorithm that is Algorithm of any problem may be one or more than one steps. 5) To write the steps in an algorithm following points may be remembers. Write the steps of the algorithm by using word Start. To input the value of the variable through the key board for that use the word read. All variable name in the algorithm must be written in Upper case alpha bate only. If the value of any variable is to all ready known then that value is assign to that variable in the step initialization. We can replaced the assignment operators (=) with the help of arrow which is pointed towards the left. The output of the algorithm is to be displaced by using Word Write/Print/Display. Finish all the steps of the algorithm by using word Stop/End.

Flowchart:- It is the method in which steps involved in the program solving are shown by Drawing symbol in the sequence of their use in the program. Flowchart is an easy tools with which completed procedure can be shown. It help programmer to know steps and their sequence in the program before writing actual program which minimize changes of mistakes and time in correcting the mistake. Some flow chart symbol:- In the drawing of flow chart some specific symbol are used .which are given below. Symbol Purpose of Symbol To show START or END of program To show input and output statement

To show decision or Control statement

To show calculation statement

To show connection on next page

Example:-

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Q1(d) Write a Algorithm, flowchart and C++ program, to find out whether the entered number is Positive, Negative or Zero . Ans->Algorithm:Description: ---------------------------------------------------------------------------------------------------------------Start [Input any number] Read [ number ] [Check the number > 0 Then the number is Positive] [Check the number<0 Then the number is Negative] [ Else the number is Zero] [Display Output ] [Finished] End/Stop

Step I > Step II > Step III> Step IV> Step V> Step VI> Step VII>

Q 2(a) Explain the different characteristics of object oriented programming. Ans :The important elements of an object-oriented language are: 3) Class 4) Inheritance 5) Reusability 6) PolymorphismClass An Object in C++ is an instance of a class. For example, in the following statement: int Num1, Num2, Num3; Num1, Num2, Num3 are three variables of type int. Similarly, you can define many objects of the same class as shown in Figure

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Class and Objects of the Class Inheritance Inheritance is the process of creating a new class, called the derived class, from the existing class, called the base class. Shows the inheritance of a derived class from the base class.

Figure of Inheritance of a Derived Class From a Base Class

For example, motorcycles, cars and trucks have certain common properties-- all have wheels, engines and breaks. Therefore, they can be grouped under a class called automobiles. Apart from sharing these common features, each subclass has its own particular characteristices--cars use petrol while trucks use diesel. The derived class has its own characteristics and, in addition, inherits the properties of the base class. Reusability The concept of inheritence provides an important feature to the object-oriented lanuage-reusability. A programmer can take an existing class and, without modifyinh it, and additional features and capabilities to it. This is done by deriving a new class from an existing class. Polymorphism The word polymorphism is derived from two Latin words poly (many) and morphos (forms). The concept of using operators or functions in different ways, depending on what they are operating on, is called polymorphism.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Q)2(b) Write a program in C++ to find out the factorial of entered number. Ans:#include<stdio.h> #include<conio.h> void main() { int number ,i, fact=1; cout<<Enter any Number; cin>> number; for(i=number; i>=1; i--) { fact=fact*i; } cout<<fact; } Q2(c) What is an operator ? Explain the different types of operator supported by C++ Language. Ans :Operators are used with operands to build expressions. For example the following is an expression containing two operands and one oprator. 4+5 Operator available in C ++ Arithmetic operators:Logical Operator :Relational Operators:Unary operators:-

+, -, *, /, % &&(AND), || (OR) , ! (NOT) <, >, <=, >=, ==, != operators use for single operand is called Unary operators ++ for (Increment) , -- for(Decrement)

Conditional operators:The conditional operator ? and : are sometimes called as ternary operators ,since they take three arguments Syntax :Expression1 ? Expression 2: Expression 3; Pointer operators :- & address of operators Structure operators:- -> Bitwise operators:- ~, or <<, ->: |, * values of address operators

>>,

^.

Q2 (d) What is variables and Constant ? Explain the different rules for naming variables and constantAns :Constant in c++ :-It is nothing but any values or number of which value is fixed, it is also called a fixed value of constant. There are three types of Constant available in C Language Integer Constant 12,256,13,1500,32766 etc

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Real Constant

Character Constant Variables in C++ :- Variable is the name of unknown value which may vary from case to case ,but in the computer it is a name of the locations in the memory to store value or constant in it. When a value is assigned to a variable, value is stored in the location of variable in the memory ,some example are area ,amount ,q, radius etc. Integer Variable Real Variable Character Variable radius=12 etc Radius=12.5 etc Name=c, grade=A etc

12,12.0,333.23,1232.43 etc A Rahul etc

Q3(a ) What is user defined function ? Explain Function prototyping . Ans :User defined function :- A main() program is also a function , called as a system function which is used to write main program within its block , C and C++ compiler start execution of the program from the main function and follows instructions written in the program in the form of C and C++ statement User defined function is also a program just link a main() function consisting of different types of statements within its own block or braces . program for function is written or defined outside the block or braces. Program for function is written or defined outside the block of main program , start within its own name and name of a function is written in the main program and search a function name and if found ,execute all statement inside the block of function program from top to bottom one by one and then control return back in the main program to the point from where function with executed or called in the main program. Whenever control comes out of the main() program for execution of the function program then main program becomes idle and after the execution of the function program controls return back to the main program and function program become idle . All statements of a program can be processed in the function. It can have input assignment and output statement in the block of a function as shown below. main() { functions(); } functions() { statement; } // users functions is defined. //users functions is called

Function prototyping:- One of the most important features of C++ is the function prototypes. A function prototype tells the compiler the name of the function, the type of data returned by the function, the number of parameters the function expects to receive, the types of the parameters, and the order in which these parameters are expected. The compiler use function prototypes to validate function calls. Early versions of C did not perform this kind of checking, so it was possible to call functions improperly without the compiler detecting the errors Such calls could result in fatal execution-time errors or nonfatal fatal errors that caused, difficult to detect logic errors. Function prototypes correct this deficiency.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

The function prototype for maximum in this program is int maximum( int, int, int); // Finding the maximum of three integers #include <iostream.h> int maximum( int, int, int ); // function prototype int main() { int a, b, c; cout << "Enter three integers: "; cin >> a >> b >> c; // a, b and c below are arguments to // the maximum function call cout << "Maximum is: " << maximum( a, b, c ) << endl; return 0; } // Function maximum definition // x, y and z below are parameters to // the maximum function definition int maximum( int x, int y, int z ) { int max = x; if ( y > max ) max = y; if ( z > max ) max = z; return max; } This prototype states that maximum takes three arguments of type int, and returns a result of type int. Notice that this function prototype is the same as the header of the function definition of maximum except the names of the parameters(x, y,and z) are not included. The portion of a function prototype that includes the name of the function and the types of its arguments is called the function signature or simply the signature. The function signature does not include the return type of the function. // A function call that does not match the function prototype is a syntax error. As an example of the preceding Common Programming error, in the previous program, if the function prototype had been written void maximum( int, int, int);

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

The compiler would report an error because the void return type in the function prototype would differ from the int return type in the function header. Another important feature of function prototypes is the coercion of arguments, i.e, the forcing of arguments to the appropriate type. For example, the math library function (sqrt) can be called with an integer argument even though the function prototype in math.h speifies a double argument, and the function will still work correctly. The statement Q3(b)Explain following data member:- (I) Private (II) Public (III) Protected Ans-> Public, protected and private are three accesses specifies in C++. 1) Public data members and member functions are accessible outside the class. 2) Protected data members and member functions are only available to derived classes. 3) Private data members and member functions cant be accessed outside the class. (OR) Q3(c)What is function overloading ? Explain overloading of function by example . Ans :- Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types. void Function(int x, int y) { cout<< (x+y); } void Function(double x, double y) { cout<< (x+y); } void Function(float x, float y) { cout<< (x+y); } Some times when these overloaded functions are called, they might cause unknown errors. This is because the compiler may not be able to decide what signature function should be called. If the data is type cast properly, then these errors will be resolved easily. Typically, function overloading is used wherever a different type of data is to be dealt with. For example this can be used for a function which converts Fahrenheit to Celsius and vice versa. One of the functions can deal with the integer data, other can deal float for precision etc..,

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Q3(d) Explain with suitable example passing a parameter by value and by reference . Ans:- Call by value:- Passing only the values so that only copy of the value is sent to functions Eg: int main() { int a=10,b=20,c; c=add(a,b); cout<<c; return 0; } int add(int x,int y) // copy of values ie a,b is received here { int z; z=x+y; return x; } call by Reference: the address of the value is passed and since address is passed the original value will change since address is modified Eg: int main() { int a=10,b=20,c; c=add(&a,&b); // address is passed cout<<c; return 0; } int add(int *x,int *y) // address locatin is received { int z; z=x+y; return x; } Q4(a) What is copy constructor ? Explain why programmer needsto use copy constructor. Ans :- Copy constructor is a type of constructor which constructs an object by copying the state from another object of the same class. Whenever an object is copied, another object is created and in this process the copy constructor gets called. If the class of the object being copied is x, the copy constructors signature is usually x::x (const x&). Lets take an example to illustrate this:

class Complex { int real, img; public: Complex (int, int);

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Complex (const Complex& source); };

//copy constructor

Complex:: Complex (const Complex& source) { this.real = source.real; this.img = source.img; } main () { Complex a (2, 3); Complex b = a; // this invokes the copy constructor } A copy constructor is called whenever an object is passed by value, returned by value or explicitly copied. if you have a class , having pointer variables pointing to another class in that case if you want to new create object using existing one, and you want to use properties of existing object in to new except pointers (Otherwise both the object will point to same memory location) in that case you can use copy constructor for creating new instance from old one ! when can we use copy constructor? A copy constructor is used in 3 cases.They are listed below: a) When an object is created from another object of the same type. b) When an object is passed by value as a parameter to a function. c) When an object is returned from a pointer. Q4(b) What is operators overloading ? Write a program to overloadbinary operator + and - using friend function. Ans:Q4 ( c) Explain :- 1) Multilevel inheritance 2) Multiple inheritance Ans:- Multiple Inheritance When a class is inherited from more than one base class, it is known as multiple inheritance. The syntax for defining a subclass, which is inheriting more than one classes is: class Subclass : acc_specifier Baseclass1, acc_specifier Baseclass2, . acc_specifier Baseclass_n { members of the derived class ; };.

Example: #include class Circle // First base class { protected: float radius ; public:

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

void Enter_r(void) { cout << "\n\t Enter the radius: "; cin >> radius ; } void Display_ca(void) { cout << "\t The area = " << (22/7 * radius*radius) ; } }; class Rectangle // Second base class { protected: float length, breadth ; public: void Enter_lb(void) { cout << "\t Enter the length : "; cin >> length ; cout << \t Enter the breadth : ; cin >> breadth ; } void Display_ar(void) { cout << "\t The area = " << (length * breadth); } }; class Cylinder : public Circle, public Rectangle // Derived class, inherited { // from classes Circle & Rectangle public: void volume_cy(void) { cout << "\t The volume of the cylinder is: "<< (22/7* radius*radius*length); } }; void main(void) { Circle c ; cout << "\n Getting the radius of the circle\n" ; c.Enter_r( ); c.Display_ca( ); Rectangle r ; cout << "\n\n Getting the length and breadth of the rectangle\n\n"; r.Enter_l( ); r.Enter_b( ); r.Display_ar( ); Cylinder cy cy.Enter_r( ); cy.Enter_lb( ); cy.volume_cy( ); } Multilevel Inheritance:

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

It has been discussed so far that a class can be derived from a class. C++ also provides the facility of multilevel inheritance, according to which the derived class can also be derived by an another class, which in turn can further be inherited by another and so on. The following figure will illustrate the meaning of the multilevel inheritance.

In the above figure, class B represents the base class. The class D1 that is called first level of inheritance, inherits the class B. The derived class D1 is further inherited by the class D2, which is called second level of inheritance. Example: Multilevel Inheritance #include class Base { protected: int b; public: void EnterData( ) { cout << "\n Enter the value of b: "; cin >> b; } void DisplayData( ) { cout << "\n b = " << b; } }; class Derive1 : public Base { protected: int d1; public: void EnterData( ) { Base:: EnterData( ); cout << "\n Enter the value of d1: "; cin >> d1; } void DisplayData( ) {

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Base::DisplayData(); cout << "\n d1 = " << d1; } }; class Derive2 : public Derive1 { private: int d2; public: void EnterData( ) { Derive1::EnterData( ); cout << "\n Enter the value of d2: "; cin >> d2; } void DisplayData( ) { Derive1::DisplayData( ); cout << "\n d2 = " << d2; } }; int main( ) { Derive2 objd2; objd2.EnterData( ); objd2.DisplayData( ); return 0; } Q4 (d) What is Constructor ? Explain dynamic initialization of object. Ans :- A constructor is a special member function whose task is to initialize the object of its class .It has same name as that of class .It is invoked automatically when the object of that class is created .It is called constructor because it construct the values of data member of the class NOTE it is the only function which does not have any return type .They should be declared in the public member of the class Example :#include<iostream.h> #include<conio.h> class integer { int m,n; public: integer(int,int); //a counstructor void display() { cout<<"m="<<m; cout<<"n="<<n; } }; integer::integer(int x,int y) { m=x;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

n=y; } void main() { clrscr(); integer intg(10,20); cout<<"output is "; intg.display(); getch(); }

//a constructor is called

Q5) A] Explain friend function with suitable example . Discuss merits and demerits of using friend function. Ans:- A friend function is used for accessing the non-public members of a class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class. The friend function is written as any other normal function, except the function declaration of these functions is preceded with the keyword friend. The friend function must have the class to which it is declared as friend passed to it in argument. class ABC { private: int a,b; public: void test() { a=100; b=200; } friend int compute(ABC e1) }; int compute(ABC e1) { return int(e1.a+e2.b)-5; } main() { ABC obj; obj.test(); cout<<"The result is:"<<COMPUTE(E); }

Merits and demerits of using friends function :merits: we can able to access the other class members in our class if we use friend keyword. we CAN access the members without inheriting the class. demerits: Maximum size of the memory will occupied by objects according to the size of friend Members. we cant do any run time ploymorphism concepts in those members.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Q5 (b) What is file mode ? Explain ios:: ate and ios ::app file modes . Ans :Q5 ( c ) What is pointer ? Explain this pointer . Ans :- pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer. : Pointer declaration A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable. type * variable name Example: int *ptr; float *string; Address operator: Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example: ptr=&num; This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260. The this pointer :- Any member function can be called only through an object of that class . When a member function is called using an object the address of the object is implicitly passed to the member function . The member function collects this address in a pointer name this. When we compile a class , the compiler attaches this-> before each and every data member used in the member function . Since all data members are prefixed with this-> ,(where this contains the address of the object ) the data member of the appropriate objects gets accessed . important notes on this pointer:

this pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class. this pointer is not counted for calculating the size of the object. this pointers are not accessible for static member functions. this pointers are not modifiable.

. For example , class sample { int data1; public: int getdata() { return this->data1; }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

void setdata(int newval) { data1 = newval; } }; Q5 (d) What is command line argument ? Write a program using command line argument which initiates the DOS command TYPE. Ans :- The main functions can have arguments passed which are called as command line arguments. There are two command line arguments: Argument count denoted by argc and Argument vector denoted by argv The argc is an integer variable which denotes the number of parameters passed and argv is pointer to array of character strings. The syntax is as follows: main( int argc , char * argv[ ]) { ..... ..... } The first argument argc (known as argument counter ) represents the number of argument in the command line . The second argument argv (known as argument vector ) is an array of char type pointer that points to the command line argument . The size of this array will be equal to the value of argc. For instance , for the command line C > exam data results

The value of argc would be 3 and the argv would be an array of three pointers to string as shown below .

argv [0] ----------------->exam argv[1]-------------------->data argv[2]-------------------->results Note that argv[0] always represent the command name that invokes the program . The character pointer argv[1] and argv[2] can be used as file name in the file opening statement as shown below. . .. infile .open (argv [1]); // open data file for reading .. outfile.open(argv[2]); // open results file for writing

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Program using command line argument which initiates the DOScommand TYPE Program:test ODD EVEN 3include<iostream.h> #include<fstream.h> #include<stdlib.h> int main(int argc, char * argv[]) { int number[9]={11,22,33,44,55,66,77,88,99}; if(argc !=3) { cout<<error in argument; exit (1); }

ofstream fout1 ,fout2 ; fout1.open(argv[1]); if (fout1.fail()) { cout<<Could not open the file; exit(1); } fout2.open(argv[2]); if (fout2.fail()) { cout<<Could not open the file; exit(1); } for(int i=0 ;i<9 ;i++) { if(number[i]%2==0) fout2<<number[i]<< ; else fout1<<number[i] <<; } fout1.close(); fout2.close(); ifstream fin; char ch; for(i=1;i<argc ;i++) { fin.open(argv[i]); cout<<Contents of<<argv[i]<<\n; do

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

{ fin.get(ch); cout<<ch; } while(fin); cout<<\n\n; fin.close(); } return 0; }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Paper II : C++ OBJECT ORIENTED PROGRAMMING (Winter 2004) Q1. (a) Write the characteristics of a good programming language. Ans :-Writing a good programming required some skill that can be developed by thinking and regular practice. Before writing a program we have to do some primary work ,first of all we should understand problem completely ,break down the problem into the parts, arrange all parts sequentially ,Write a program and test it. We can divided problem solving and program writing into following general group. 1) 2) 3) 4) Analyze the problem Design the problem. Write the problem. Test the problem.

Q1. (b) What is an Algorithm and Flowchart ? Explain the different symbol used in Flowcharting. Ans :- Algorithm:1) It is the theory representation of any problem in any types of language like English. 2) The algorithm of any language, may be written into of its steps. 3) Every steps of an algorithm has its own instructions which is written in square bracket above the shape of algorithm. 4) These is no such restriction to write the steps in the algorithm that is Algorithm of any problem may be one or more than one steps. 5) To write the steps in an algorithm following points may be remembers. Write the steps of the algorithm by using word Start. To input the value of the variable through the key board for that use the word read. All variable name in the algorithm must be written in Upper case alpha bate only. If the value of any variable is to all ready known then that value is assign to that variable in the step initialization. We can replaced the assignment operators (=) with the help of arrow which is pointed towards the left. The output of the algorithm is to be displaced by using Word Write/Print/Display. Finish all the steps of the algorithm by using word Stop/End.

Flowchart:- It is the method in which steps involved in the program solving are shown by Drawing symbol in the sequence of their use in the program. Flowchart is an easy tools with which completed procedure can be shown. It help programmer to know steps and their sequence in the program before writing actual program which minimize changes of mistakes and time in correcting the mistake. Some flow chart symbol:- In the drawing of flow chart some specific symbol are used .which are given below. Symbol Purpose of Symbol To show START or END of program To show input and output statement

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

To show decision or Control statement

To show calculation statement

To show connection on next page

Q1. (c)Write short notes on :I) Compiler II) Interpreter Ans:- Please Show this answers in (summer 2004 paper) and write short notes. Q1 ) (d) Explain with suitable example the term branching and looping in flowcharts . Ans :Q2. (a) What is looping? Explain in details for loop in C++ language. Ans :Loops:-The versatility of the computer lies in its ability to perform a set of instruction repeatedly .This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operations is done through a loop control structure. There are three method by ways of which we can repeat a part of a program , They are 4.) For statement 5.) While Statement. 6.) Do-while Statement. For loop:The purpose of for loop is same as while loop but writing format is different , perhaps one reason why few programmers use while is that they are too busy using the for . which is the most popular control . for allows us to specify three things about a loop in a single line. The general form of for statement is as under.

Syntex :for(initialize counter ; test counter ; increment counter) { do this; and this; and this; } Explanation how for statement gets executed :When program control reaches to for first time is executed . Then condition is checked . The result of the condition is true then body of the loop is executed otherwise control comes outside loop .After executing body of the loop increment is executed then again condition is executed and process repeats.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Flowchart of for loop:-

START Declare variable Initiate

F
STOP

for condition

Increment

T
Statement 1 ; Statement 2;

Example :main() { int I; for(i=1;i<=5 ;i++) { Cout<<endl<<i; } getche(); } Q 2. (b) What is type casting ? Explain casting with suitable example . Ans :-Type casting :- Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast: main() { short a=2000; int b; b=a; cout<<b; } Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Q 2.(c) Explain the usage of the conditional operator with the help of suitable example . Ans :Conditional operators :- The conditional operators ? and : are sometimes called as ternary operators since they take three arguments . Syntex :Expression1 ? expression2 : expression3; Explanation :- if expression1 is true , then the value returned will be expression2 otherwise value returned will be expression3 . Example :main() { int x,y; cout<<Enter value of x; cin>>x; y=(x>5 ? 3: 4); cout<<endl<<y; getche(); } If user enter value of x greater than 5 then 3 gets assign to variable y , and if it is less than 4 will gets assign to y.

Q2 (d) Differentiate between keyword and an identifier . List the rules of writing an identifier . Ans:Keywords :-Keywords are explicitly reserved identifiers and cannot be used as names for the program variables or other user-defined program elements. Some example are :- private ,public , for ,while, goto, ..etc. Identifier: - Identifiers refar to the names of variable ,functions ,array , classes ,etc . created by the programmer . They are the fundamental requirement of any language .Each language has its own rules for naming these identifiers. The following rules are common to both C and C++ 1) Only alphabetic characters, digits and underscores are permitted. 2) The name cannot start with a digit. 3) Uppercase and lowercase letters are distinct. 4) A declare keyword cannot be used as a variable name. Q3 (a) Explain how does a class enforce data-hiding ,abstraction and encapsulation . Q3 (b). Explain with suitable example passing a parameter by value and by reference . Ans:-Explain Answers summer-2004 paper Q3 (d). Q3 (c) What is recursion ? Write a program to find out factorial of a given integer using recursion method. Ans :Recursion:In C and C++ it is possible for the function to call themselves. A function is called recursion , if a statement within the body of a function calls the same function. Sometimes called Circular definition . Recursion is thus the process of defining something it terms of itself

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Example: Q) What is recursion ? Write a program to find the factorial of a positive integer using recursion. Ans:void main() { int number,factorial; cout<<Enter any number; cin>>number; factorial= function(number); cout<<factorial; } function( int x) { int f; if(x==1) return(1); else f=x*function(x-1); return(f); }

// Working Recursion

What is Objects ? How they are created ? Differentiate between an object and class . Ans :Differentiate between an object and class are as fallows A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change. The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed. An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change. Example :Let us consider the class car. Cars have a body, wheels, an engine, seats, are used to transport people between locations, and require at least one person in the car for it to move by its own power. These are some of the attributes of the class - car - and all members that this class has ever or will ever have share these attributes. The members of the class - car - are objects and the objects are individual and specific cars. Each individual car has a creation date (an example of an object having an attribute that is static), an owner, a registered address (examples of attributes that may or may not change), a current location, current occupants, current fuel level (examples of attributes that change quickly), and it may be covered by insurance (an example of an attribute that may or may not exist). To use a more programming related example, the class window has edges, a title bar, maximize and minimize buttons, and an area to display the window contents. A specific window has a location on the screen, a size, a title, and may or may not have something in the content area. So basically the difference between a class and an object is that a class is a general concept while objects are the specific and real instances that embody that concept. When creating an object oriented program we define the classes and the relationships between the classes. We then execute the program to create, update, and destroy the objects which are the specific realization of these classes.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Q4 (a) What are constructors and destructors ? Explain . Ans :Constructor: Constructor is a special member function whose task is to initialize the object of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an ibject of its associated class is created.It is called constructor because it constructs the values of data members of the class. A constructor is declared and defined as follows. //class with a constructor Class integer { Int m,n; Public: Integer(void); }; Integer ::integer(void) { m=0; n=0; } When a class contains a constructor like the one defined above, it is guaranted that an object created by the class will be initialized automatically. For example the declaration Integer obj1; Not only create the object obj1 of type integer but also initializes its data members m and n to zero .There is no need to write any statement to invoke the constructor function .If a normal member function is defined for zero initialization .we would need to invoke this function for each of the objects separately .This would be very inconvenient, if there are a large number of objects. A constructor that accepts no parameters is called the default constructor.The default constructors for class A is A::A(). If no such constructor is defined, then the compiler supplies a default constructors. Therefore a statement such as A a; Invoked the default constructors of the compiler to create the object a. Destructors:A destructor, as the name implies, is used to destroy the objects that have been created a constructors. Like a constructor,the destructor is a member function whose name is the same as the class name but is preceded by a tilde. For Example,the destructor for the class integer can be defined as shown below. ~integer() { } A destructor never taken any argument nor does it return any value. It will be invokedimplicitly by the compiler upon exit from the program to clear up storage that is no longer accessible. It is a good practice to declare destructor in a program since it released memory space for future use. Whenever new is used to allocate memory in the constructors, we should use delete to free the memory. For example,the destructor for the matrix class discussed above may be defined as follows. Matrix :: ~matrix() { For(int i=0;i<10;i++) delete p[i]; delete p; }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Example :Class alpha { Public: alpha() { . . } ~alpha() { } }; Void main() { } Q4. (b) What is operator overloading ? Write a program to overload the unary operator and ++. Ans :Q 4.(c) Distinguish between single inheritance and multiple inheritance . Ans:Single Inheritance Multiple Inheritance 1)The Derived class having only one Base 1) The Derived class having more than class is called single Inheritance. one base class is called Multiple Inheritance. 2) example: class a { public: int x,y; }; class b: public a { public: int z; } 2) example: class a { public: int x,y; }; class b { public: int z; } class c:public a , public b { }

Q4 .Define the term default constructor and parameterized constructor. Ans :Default Constructor :- A default constructor is a constructor that has no parameters, or if it has parameters, all the parameters have default values. Example :-

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

class X { public: X( ); // default constructor, no arguments }; Parameterized constructor: - Which constructor has arguments that is called Parameterized Constructor. Example :class X { public: X( int x, int y ,float z); }; Q5. (a) What is new and delete operators ? Explain with the help of suitable example . Ans :New operators: -The new operator in C++ is used for dynamic storage memory allocation. This operator can be used to create object of any type. syntax of new operator in C++: pointer variable = new datatype; For example: int *a=new int; // default constructor, no arguments

In the above example, the new operator allocates sufficient memory to hold the object of datatype int and returns a pointer to its starting point. The pointer variable a holds the address of memory space allocated. int *a = new int(20); delete operator :- The delete operator in C++ is used for releasing memory space when the object is no longer needed. Once a new operator is used, it is efficient to use the corresponding delete operator for release of memory. Syntax of delete operator in C++: delete pointer variable; Example: to understand the concept of new and delete memory management operator in C++: #include <iostream.h> void main() { int *a= new a; //Allocates using new operator memory space in memory for storing a integer datatype *a=100; cout << " The Output is:a="<<a; delete a; //Memory Released using delete operator } Q5 (b) Write a program to create a text file . Further extendyour program to find out number of lines , number of characters in the file . Q5 (c ) Why do we need virtual functions ? When the virtual function is made pure . Q 5 (d) Explain the different error that occurs during file operations .

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Summer -2005 Paper II C++ OBJECT ORIENTED PROGRAMMING Q 1 (a) Explain the characteristics of a good language . Ans :- Answers Explain Winter -2004 ( Please read it ) Q1 (b) Discuss the conceptual development of solution with suitable example . Ans :-

Q1 (c) Differentiate between Compiler ,Interpreter and Assembler . Ans :Compiler -- reads human-readable source code, produces machine-executable binary code. Examples are C, COBOL, Java, etc. Easiest for humans to program, but does not always produce the most efficient executables. Interpreter -- Reads human-readable code, line at a time, and produces and executes machine instructions "on the fly". Example is good old BASIC. Good for testing, but is VERY slow. Assembler -- Converts machine-manipulation coding directly into binary machine instructions. Produces the most efficient executables, but is the most difficult (for humans) to work with. Q 1. (d) What is an algorithm ? Write Analysis and algorithm to calculate all the root of a quadratic equation ax2+bx+c , where a, b and c are the coefficients of a quadratic equation .

Ans :- Algorithm:6) It is the theory representation of any problem in any types of language like English. 7) The algorithm of any language, may be written into of its steps. 8) Every steps of an algorithm has its own instructions which is written in square bracket above the shape of algorithm. 9) These is no such restriction to write the steps in the algorithm that is Algorithm of any problem may be one or more than one steps. 10) To write the steps in an algorithm following points may be remembers.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Write the steps of the algorithm by using word Start. To input the value of the variable through the key board for that use the word read. All variable name in the algorithm must be written in Upper case alpha bate only. If the value of any variable is to all ready known then that value is assign to that variable in the step initialization. We can replaced the assignment operators (=) with the help of arrow which is pointed towards the left. The output of the algorithm is to be displaced by using Word Write/Print/Display. Finish all the steps of the algorithm by using word Stop/End.

Analysis :- If the value of a,b and c are known then roots x1 and x2 can be calculated by the following formula .

Algorithm :I> II> III> IV> Start [Input coefficient of a ,b,c of a quadratic equation ] [Calculate all the roots of a quadratic equation ax2+bx+c,]

v>

[output] Display x1 and x2

vi>

[Finish] Stop

Q2 (a) Explain the basic concept of object oriented programming . Ans:Some of the important object oriented features are namely:

Objects Classes Inheritance Data Abstraction Data Encapsulation Polymorphism Overloading Reusability

Objects: Object is the basic unit of object-oriented programming. Objects are identified by its unique name. An object represents a particular instance of a class. There can be more than one instance of an object. Each instance of an object can hold its own relevant data

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

An Object is a collection of data members and associated member functions also known as methods. Classes: Classes are data types based on which objects are created. Objects with similar properties and methods are grouped together to form a Class. Thus a Class represent a set of individual objects. Characteristics of an object are represented in a class as Properties. The actions that can be performed by objects becomes functions of the class and is referred to as Methods.

For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR represents individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture, Colour, Top Speed, Engine Power etc., which form Properties of the Car class and the associated actions i.e., object functions like Start, Move, Stop form the Methods of Car Class. No memory is allocated when a class is created. Memory is allocated only when an object is created, i.e., when an instance of a class is created. Inheritance: Inheritance is the process of forming a new class from an existing class or base class. The base class is also known as parent class or super class, The new class that is formed is called derived class. Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall code size of the program, which is an important concept in object-oriented programming. Data Abstraction: Data Abstraction increases the power of programming language by creating user defined data types. Data Abstraction also represents the needed information in the program without presenting the details. Data Encapsulation: Data Encapsulation combines data and functions into a single unit called Class. When using Data Encapsulation, data is not accessed directly; it is only accessible through the functions present inside the class. Data Encapsulation enables the important concept of data hiding possible. Polymorphism: Polymorphism allows routines to use variables of different types at different times. An operator or function can be given different meanings or functions. Polymorphism refers to a single function or multi-functioning operator performing in different ways. Overloading: Overloading is one type of Polymorphism. It allows an object to have different meanings, depending on its context. When an exiting operator or function begins to operate on new data type, or class, it is understood to be overloaded. Reusability: This term refers to the ability for multiple programmers to use the same written and debugged existing class of data. This is a time saving device and adds code efficiency to the language. Additionally, the programmer can incorporate new features to the

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) existing class, further developing the application and allowing users to achieve increased performance. This time saving feature optimizes code, helps in gaining secured applications and facilitates easier maintenance on the application. The implementation of each of the above object-oriented programming features for C++ will be highlighted in later sections. Q2. ( b) Write a program in C++ to test an entered number is prime or not prime . Ans :void main() { int i,n,r=0; cout<<"Enter any no: "; cin>>n; for(i=2;i<=n-1;i++) { if(n%i==0) r=1; break; } if(r==0) cout<<"prime no"; else cout<<"Not prime"; getch(); }

Q2 . (c ) What is keyword and identifier ? Explain the rules for writing variable in C++ . Ans :-Explain in Paper Winter -2004 in Q2(d) Q2.(d). Explain a switch structure with suitable example . Ans :- Switch Statement :-Switch is one more decision statement like if and if-else statement but different is that , switch is the selection of particular choice from the given list of options . as we switch on the button to start particular devices from the series of button mounted on the electricity board such as one button is to start Fan , another may be to switch on TV and so on . same concepts is used in switch statement ,as per the value of an expression or choice a particular case is executed . The syntax of Switch statement is as follows. Syntax :expression ; switch(expression) { case Constant1: Statement1; .. case Constant2: Statement2; . . default : Statement3; } Here constant1 and constant2 .. are all either integer or character. Float constant are not allowed.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) expression in switch () gets evaluated then value of this expression is compared with constant in each case . All the statement from that satisfied case gets execute until closing brace of switch or break is encountered. To execute any particular case , break statement should be given at the ends of each case . Default is a special case which gets executed whenever encountered. Program :main() { iInt a; printf(Enter month from 1 to 12 ); scanf(%d,&a); switch(a) { case 1: cout<<January; break; case 2: cout<<Feburary; break; case 3: cout<<March; break; case 4: cout<<April; break; case 5: cout<<May; break; case 6: cout<<June; break; case 7: cout<<July; break; case 8: cout<<August; break; case 9: cout<<September; break; case 10 : cout<<Octomber; break; case 11: cout<<November; break; case 12: cout<<December; break; default : cout<<You entered invalid number; } } Q3 . (a) What is a user defined function ? Differentiate between Default and Constant argument function with suitable example . Ans :- User defined function :- A main() program is also a function , called as a system function which is used to

write main program within its block , C and C++ compiler start execution of the program from the main function and follows instructions written in the program in the form of C and C++ statement User defined function is also a program just link a main() function consisting of different types of statements within its own block or braces . program for function is written or defined outside the block or braces. Program for function is written or defined outside the block of main program , start within its own name and name of a function is written in the main program and search a function name and if found ,execute all statement inside the block of function program from top to bottom one by one and then control return back in the main program to the point from where function with executed or called in the main program. Whenever control comes out of the main() program for execution of the function program then main program

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

becomes idle and after the execution of the function program controls return back to the main program and function program become idle . All statements of a program can be processed in the function. It can have input assignment and output statement in the block of a function as shown below. main() { functions(); } functions() { statement; }
Default Constant argument function :#include <stdio.h> void function(const char *p); int main(void) { char str[80]; printf("Enter a string: "); gets(str); print_str(str); return 0; } void function(const char *p) { while(*p) putchar(*p++); } Q3 .(b). Explain with suitable example . Array within class and Arrays of Objects . Ans:Array within class:- When we create a class and declare array type of variable within a class . Example :class abc { int a,b; int array[10]; //Array within a class }; Arrays of object:We knoe that an array can be of any data type including struct. Similarly ,we can also have array of variable that are of the type class.Such variable are called arrays of objects. Consider the following class definition. class employee { char name[30]; float age; public: void getdata(void); void putdata(void); };

//users functions is called // users functions is defined.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) The identifier employee is a user-defined data type and can be used to create objects that relate to different categories of the employee. employee manager[3]; employee foreman[15]; employee worker[75]; The array manager contains three objects(managers),namely,manager[0], manager[1],manager[2],of type employee class. Similarly the foreman array contains 15 objects and the worker array ciontains 75 objects Sonce an array of objects behave like any other array,we can use the usualarray accessing methods to access individual element ,and then the dot member operator to access the member functions.

For example the statement Manager[i].putdata(); Will display the data of the ith eelement of the array manager. That is ,this statementrequired the objects manager[i] to invoked themember function putdata() An array of objects is stored inside the memory in the same way as a multi-dimensional array. The array manager is represented in fig . Note that only the space for data items of the objects is created.Member function are stored separately and will be used by all the objects. Name Age Name Age Name Age Example:class employee { char name[30]; float age; public: void getdata( void); void putdata(void); }; void employee ::getdata(void) { cout<<Enter name; cin>>name; cout<<Enter age; cin>>age; } void employee ::putdata(void) { cout<<name<<age; } const int size=3; int main() manager[0] manager[1] manager[2]

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) { employee manager[size]; for(int i=0;i<size;i++ { manager[i].getdata(); } for(i=0;i<size;i++) { manager[i].putdata(); } return 0; } Q3. (c ) Explain the following access specifiers :i)Private II) public III)protected. Q3. (d) Differentiate between structure and union . Structure 1. structure allocates the memory equal to sum of the memory allocated to its each individual members 2. in case of structure, each member have their own memory space Union 1. Union allocates the memory equal to the maximum memory required by the member of the union 2. In Union, one block is used by all the member of union.

Q4. (a) What is a constructor? Explain the initialization of object with suitable example . Ans :Constructor: Constructor is a special member function whose task is to initialize the object of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created .It is called constructor because it constructs the values of data members of the class. A constructor is declared and defined as follows. //class with a constructor Class integer { Int m,n; Public: Integer(void); }; Integer ::integer(void) { m=0; n=0; } When a class contains a constructor like the one defined above, it is guaranted that an object created by the class will be initialized automatically. For example the declaration Integer obj1; Not only create the object obj1 of type integer but also initializes its data members m and n to zero .There is no need to write any statement to invoke the constructor function .If a normal member function is defined for zero initialization .we would need to invoke this function for each of the objects separately .This would be very inconvenient, if there are a large number of objects.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) A constructor that accepts no parameters is called the default constructor.The default constructors for class A is A::A(). If no such constructor is defined, then the compiler supplies a default constructors. Therefore a statement such as A a; Invoked the default constructors of the compiler to create the object a. Q4.(b)How does inheritance influence the working of constructor and destructors ? Explain multiple inheritances. Q4. ( c) Discuss significance of the destructor in brief. Explain the difference between a constructor and a destructor. Ans:- Destructors:A destructor, as the name implies, is used to destroy the objects that have been created a constructors. Like a constructor,the destructor is a member function whose name is the same as the class name but is preceded by a tilde. For Example,the destructor for the class integer can be defined as shown below. ~integer() { } A destructor never taken any argument nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program to clear up storage that is no longer accessible. It is a good practice to declare destructor in a program since it released memory space for future use. Whenever new is used to allocate memory in the constructors, we should use delete to free the memory constructor destructors 1. A constructor is called when you want to create a new 1. A destructor is called when you want to free up the class memory of an object (when you delete it). 2.A constructor constructs the value of an object 2. A destructor destructs the value created by the constructor for the object.

Q4 (d) Discuss the rules of operator overloading with example . Ans :- Rules for overloading Operators: a) Only existing operators can be overloaded .New operators cannot be created. b) The overloaded operator must have at least one operand that is of user-defined type. c) We cannot change the basic meaning of an operator. That is to say, we cannot redefined the plus (+) operator to subtract one value from the other. d) Overloaded operators follow the syntax rules of the original operators. They cannot be overridden. e) There are some operators that cannot be overloaded. f) We cannot used friend function to overload certain operators. However , member functions can be used to overload them. g) Unary operators, overloaded by means of a member function, take no explicit argument and return no explicit values ,but ,those overloaded by means of a friend function ,take one reference argument. h) Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments. i) When using binary operators overloaded through a member function , the left hand operand must be an object of the relevant class. j) Binary arithmetic operators such as + , - , * , / must explicitly return a value. They must not attempt to change their own argument. Q5.(a)What is this pointer ? Explain with suitable example. Ans: Answers is explain in paper summer 2004 Please read it . Q5. (b) What are different types of error that might be encounter while processing files ? Explain. Ans:-There are different types of error that might be encounter while processing files, these are , 1). A file which we are attempting to open for reading does not exist.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) 2). The file name used for a new file may already exist. 3). We may attempt an invalid operation such as reading past the end of file. 4) . There may not be any space in the disk for storing more data. 5). We may use an invalid file name. 6). We may attempt to perform an operation when the file is not opened for that purpose.

Q5.(c) What are Virtual Functions ? Why do we need Virtual Functions? Explain with an example. Ans:- A function that is defined in a base class but overridden by the derived class is called a virtual function.
To create virtual functions precede the function declaration in the base class with the keyword virtual. When a class containing a virtual function is inherited the derived class overrides the virtual function with its own definition. Virtual functions are like member functions however what makes them different is the capability to support run time polymorphism when accessed via a pointer. A base class pointer can point to an object of a derived class. When a base class pointer points to an object of a derived class that contains a virtual function, C++ determines which function version to call based on the type of object pointed by the base class pointer. This is runtime polymorphism as it can be determined at run time. In this way when different objects are pointed to then different versions of virtual functions are executed. Whenever a virtual function is defined all aspects of its prototype should match. Also virtual functions should be non static members of the class and they cannot be friend functions too.

C++ Virtual function - Example:


This article assumes a base class named Window with a virtual member function named Create. The derived class name will be CommandButton, with our over ridden function Create. class Window { public: virtual void Create() { cout <<"Base class Window"<<ENDL; } }; // Base class for C++ virtual function example

// virtual function for C++ virtual function example

class CommandButton : public Window { public: void Create() { cout<<"Derived class Command Button - Overridden C++ virtual function"<<endl; } }; void main() { Window *x, *y; x = new Window(); x->Create(); y = new CommandButton(); y->Create(); } The output of the above program will be, Base class Window Derived class Command Button

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)
If the function had not been declared virtual, then the base class function would have been called all the times. Because, the function address would have been statically bound during compile time. But now, as the function is declared virtual it is a candidate for run-time linking and the derived class function is being invoked. Q5.(d) What are file modes ? Write a program that creates a text file . Write statement using seekg() to achieve the following :(i) (ii) To go to the beginning after an operation is over. To move to the pointer by 15 position backward from the current position.

WINTER -2005 Paper-II c++ object oriented programming Q1(a) What is compiler ? Explain the different phases of compilation process. Ans : Explain in previous two paper please read its content and solve. b. What is a flowchart ? Explain the different symbol used in flow chart. Discuss the advantages of flowchart. Ans :- Explain in previous paper please read its content and solved it. c.Difference between machine level and Assembly language. Ans:- Explain in paper summer 2004 please read it and solve. d. Explain the pseudo code and its characteristic. Ans :- Pseudocode: It is a tool used to formulate the processing steps of a program. Pseudocode uses English word to describe the processing steps of program or module. The logic control instructions within a structured design are emphasized in pseudocode. Ex: MOV is used for move, ADD is used for addition, and SUB is used for subtraction.

Advantage:
4. 5. 6. 4. 5. 6. As compared to a flowchart, converting a pseudocode into a programming language is much easier. As compared to a flowchart, it is easier to modify the pseudocode of program logic when program modifications are necessary. Writing of pseudocode involves much less time and effort than drawing an equivalent flowchart. In case of pseudocode, a graphic representation of program logic is not available. There are no standard rules to follow in writing pseudocode. Different programmer uses their own style of writing pseudocode. Hence communication problem occur due to lack of standardization. For beginner, it is difficult to follow the logic of pseudocode or write pseudocode as compared to flowcharting.

Disadvantage:

Q2 a Explain Expressions . write down the rules that apply to expression whose operands are of different data type. Ans:- Expressions: - expression refar to the names of variable ,functions ,array , classes ,etc . created by the

programmer . They are the fundamental requirement of any language .Each language has its own rules for naming these identifiers. The following rules are common to both C and C++ 1) Only alphabetic characters, digits and underscores are permitted. 2) The name cannot start with a digit. 3) Uppercase and lowercase letters are distinct. 4) A declare keyword cannot be used as a variable name.
b. Write a program in C++ to sum the sine series upto 4 significence digits. Since series.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Ans :C What is a manipulator ? Explain any two with suitable example. Ans:-Manipulators Manipulators are used to change formatting parameters on streams and to insert or extract certain special characters. These manipulators are usable on both input and output streams, although many only have an effect when applied to either output or input streams. endl Insert newline and flush (manipulator function) ends Insert null character (manipulator function)

d. What is c++? What are advantages of c++? C++ is a object oriented programming language. Initially C++ was named as C with classes. C was developed by Bjarne Stroustrup at AT & T bell library in USA, in early eighties. The advantages of C++ over C: C++ is an incremented version of C. It is a superset of C. Almost All C programs can also run in c++ compiler. The important facilities added in C++ are classes, Function overloading, operator overloading. C++ allow user to create abstract data types, to inherit properties from existing data types. C++ supports polymorphism. Any real life application system such as editor, compiler, and databases communication systems can be built by C++. Object oriented library builts in C++. C++ programs can be easily implemented, maintained and expanded. Q3aExplain with suitable example passing a structure to a function. Ans:Like any ordinary variable, a structure variable can also be passed to a function. We may either pass individual structure element or the entire structure one go. Example 1:void main() { struct book { char name[25]; char author[25]; Int price; }; struct book b1={ Asp.Net,Bridjan,250}; display(b1.name,b1.author,b1.price); } display(char *s,char *t,int n) { Cout<<s<<t<<n; } And here is the output. Asp.Net Bridjan 250 Observe that in the declaration of the structure , name and author have been declared as arrays . Therefore ,when we call the function display() using ,

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) display(b1.name,b1.author,b1.price); we are passing the base address of the arrays name and author , but the value stored in price. Thus ,this is a mixed call by value and call by refrence .

bWhat is function overloading ? Explain overloading of a function by considering suitable example. Ans :- Explain this answers in summer 2004 paper Q3 Please read it. c. Explain with suitable example an object as function prototyping. Ans:#includeiostream.h class temp { int hours,minutes; Public: void getdata(int h,int m) { hours=h;minutes=m; } void puttime(void) { Cout<<hours<<minutes; } void sum(time,time); }; void time ::sum(time t1,time t2) { minutes=t1.minutes+t2.minutes; hours=minutes/60; minutes=minutes%60; hours=hours+t1.hours+t2.hours; } main() { time t1,t2,t3; t1.gettime(2,45); t2.gettime(3,30); t3.sum(t1,t2); cout<<t1.puttime(); cout<<t2.puttime(); cout<<t3.puttime(); } d. What is user defined function? Explain function prototype. Ans :Explain this answers in summer 2004 paper Please read it carefully. 4 a State difference between constructor and destructor. Ans :- Explain this answer insummer 2005 Q4 (c) b. What is operator overloading ? write a program to overloading ++ operator using friend function. c. What is parameterized constructor ? Explain with copy constructors.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Ans:-

parameterized constructor :C++ permits us to achieve this objects bt passing argument to the constructor function when the object are created . The constructor that can take arguments are called parametrized constructors Example:class abc { int m,n; public: abc(int x,int y); //paramererise constructor ................ ................. }; abc::abc(int x,int y) { m=x;n=y; }

Copy constructor:- Explain summer 2004 paper please read it carefully.

d. What is a containership. ? How does it differ from inheritance? Ans:Container: a class contains another object as member data. The class which contains the object cannot access any protected or private members of the contained class (unless the container it was made a friend in the definition of the contained class). Assuming the contained object is not public, the contained class is encapsulated by the container and so programs constructing a container object cannot access the contained class methods unless the container class provides "ribbon-cable" access methods to the contained class. The relationship between the container and the contained object is "has-a" instead of "is-a". Example :class A { int a; }x; class B { A y; }z;

// All the data members and member functions of class A can be accessed through the object 'y'

Inheritance: a (derived) class that inherits from another (base) class is a specialized form of the base class. The derived class
inherits the member data and methods from the base class, and can manipulate base public/protected member data as its own data. By default, a program which constructs a derived class can directly access the public members of the base class as well. The derived class can be safely downcast to the base class, because the derived class "is-a" base class. Example:class A { Int a; }; class B: public A { Int p; }; main() { B object; }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Q5a What is command line argument ? Write a program using command line argument which simulate the DOS command TYPE Ans:- Explain this answer in summer-2004 paper Please read it casefully . b.Explain the friend function giving suitable example. Discuss the merits and demerits of using friend function. Ans:- Explain this answers in summer 2004 Q5(A) c. What is the pointer ? What do you understand by memory leaks ? What are the possible reasons for it? How can memory leaks be avoided. Ans:Pointer: A pointer is a variable that holds the memory address of other variable. It is also of different data types, ex- char pointer can store address of only char variables, int pointer can store address of int variables and so on.

Classes for file stream operations://class that define the file handeling method.Thease include iftream , ofstream and fstream.These classes are derive from fstreambase and for the corresponding iostream class.These class design to manage the disk file,are declare fstream and therefore we must include this file in any program that used file.

fstream:-Provide support for input and output operations . Contains open() with default input mode . Inherits all the function from istream and ostream classes through iostream . Ofstream:- Provide output operations , Contains open() with default output mode . Inherits put(), seekp() ,tellp() ,and write(), function from ostream . Ifstream :- Provide input operations . Contains open() with default input mode . Inherits the function get() , getline() , read() , seekg() and tellg() function from istream . filebuf :- Its purpose is to set the file buffers to read and write . Contains Openprot constant used in the open() of file stream classes . Also contains close() and open() as members. Fstreambase :- Provides operations common to the file stream, Serves as a base for fstream, ifstream and ofstream class . Contains open() and close() functions. d. what is file mode ? Explain ios::ate and ios::app file modes. a. Open a file for input and read in its content
Ans:#include <fstream> #include <iostream> using namespace std; int main () { char buffer[256]; fstream myfile; // open it for input and read in myfile.open("test.txt",ios::in); //ios::in means Open file for reading only myfile.getline(buffer,100); cout << "The file contains " << buffer << "\n"; myfile.close(); return 0; } b. Open a file for appending and append

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

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) int main () { char buffer[256]; fstream myfile; //open for appending and append myfile.open("test.txt",ios::app); //ios::app means Append to end of file myfile << " Hey this is another line \n"; myfile.close(); return 0; }
c. Open a file as binary file and get its size

Ans:-.
#include <fstream> #include <iostream> using namespace std; int main () { long start,end; ifstream myfile ("test.txt", ios::in|ios::binary); start = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout << "size of " << "test.txt"; cout << " is " << (end-start) << " bytes.\n"; return 0; } d. Opening text Files for Read and Write

Ans:#include <fstream> #include <iostream> using namespace std; int main() { char buffer[255]; ofstream fout("text.txt"); fout << "this is a test\n"; cout << "Enter text for the file: "; cin.ignore(1,'\n'); cin.getline(buffer,255); fout << buffer << "\n"; fout.close(); ifstream fin("text.txt"); cout << "Here's the contents of the file:\n"; char ch; while (fin.get(ch)) cout << ch;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) fin.close(); return 0; }
e.

Appending to the End of a File

Ans:#include <fstream> #include <iostream> using namespace std; int main() { char buffer[255]; ifstream fin("text.txt"); if (fin) { char ch; while (fin.get(ch)) cout << ch; } fin.close(); cout << "in append mode...\n"; ofstream fout("text.txt",ios::app); if (!fout) { cout << "Unable to open for appending.\n"; return(1); } cout << "\nEnter text for the file: "; cin.ignore(1,'\n'); cin.getline(buffer,255); fout << buffer << "\n"; fout.close(); fin.open("text.txt"); if (!fin) { cout << "Unable to open for reading.\n"; return(1); } char ch; while (fin.get(ch)) cout << ch; fin.close(); return 0; }

f.opening file for read and write. Ans:#include <fstream>

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) #include <iostream> using namespace std; int main() { char buffer[255]; ofstream fout("text.txt"); fout << "test\n"; cout << "Enter text for the file: "; cin.ignore(1,'\n'); cin.getline(buffer,255); fout << buffer << "\n"; fout.close(); ifstream fin("text.txt"); char ch; while (fin.get(ch)) cout << ch; fin.close(); return 0; }

Summer 2006
C++ programming
Q1 a. Write characteristic of good programming? Ans:- Explain this answers Winter 2004 Please read It and understand. Q2 b.Difference between compilar and interpreter . Ans: Explain this answers in summere 2004 Please read it and understand. Q3 Draw a flowchart to find sum of the fillowing series for N terms. Sum=1+ ----------------+N Ans:Program:Main() { float x,sum=0,n=1; cout<<Enter value of x; cin>>x; while(n<=10) { sum=sum+pow(x,n)/n; n=n+1; } cout<<sum; } Q4 What is an Algorithm ? list advantages and Disadvantages of Algorithm. ? Ans:-

Algorithm:
Algorithm is a step by step instruction of a program. It is a finite set of step by step instructions that solve a problem. After defining the problem, we can create algorithms of our application. Ex: short paper planning of any program.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) Computer program is another example of an algorithm. Every computer program is a set of series in specific order, designed to perform a specific task. Ex: Algorithm for largest no out of two no: 1. Start 2. Read no x and y from user 3. Check x>y if yes go to step 4 otherwise goto step 5 4. Print X is largest. Goto step 6 5. Print y is largest 7. Stop Advantage: 5. An algorithm is generally written in spoken language and not in any programming language so hence it is easy to understand. 6. Also written an algorithm helps eliminate any error in our problem solving logic, so that when we start programming we worry only about the language specific issues. 7. Easy to understand 8. It support in writing program. Disadvantage: 4. Algorithms are only as good as the instruction given. However, and the result will be incorrect if the algorithm is not properly defined. 5. Difficult to depict complex programming steps. 6. Most of the programmers write algorithm after writing the program; which fails the purpose of algorithm.
Q1 Write a program to determine the smallest and the largest emement in a list of element. Ans:-

main() { int n,a=1,small,large; while(a<=10) { cout<<Enter any number; cin>>n; if(a==1) small=n; if(small>n) small =n; a=a+1; } cout<<small; }

Q2 Difference between unary and binary operator .Give an Example. Ans:-

Unray Operators: A type of operators that works with one operand. Following operators are unary operators: -,++,-The above operators are used with one operand as follows:

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) -a; N++; --x; Example:Main() { Int I; For(i=1;i<=10 ;i++) { Cout<<I; } } Binary operators: A type of operator that works with two operands is know as binary operators. +,-,*,/,% these are binary operators. main() { int a=10,b=20,c; c=a+b; cout<<c; } Q4 What is Token ? Which token are available in C++ Ans:-A token is the smallest element of a C++ program that is meaningful to the compiler. The C++ parser recognizes these kinds of
tokens: identifiers, keywords, literals, operators, punctuators, and other separators. A stream of these tokens makes up a translation unit. Tokens are usually separated by "white space." White space can be one or more:

Blanks Horizontal or vertical tabs New lines Formfeeds Comments

Q1] Explain function overloading giving suitable example:= Ans : Explain this answer in summer 2004 Please read it carefully.

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)
Examples:-

1. To find the sum of two number. #include<stdio.h> #include<conio.h> void main() { int a,b,s; clrscr(); printf("Enter two no: "); scanf("%d%d",&a,&b); s=a+b; printf("sum=%d",s); getch(); } 2. find area and circumference of circle. #include<stdio.h> #include<conio.h> void main() { int r; float pi=3.14,area,ci; clrscr(); printf("enter radius of circle: "); scanf("%d",&r); area=pi*r*r; printf("area of circle=%f",area); ci=2*pi*r; printf("circumference=%f",ci); getch(); } 3.To find simple Interest #include<stdio.h> #include<conio.h> void main() { int p,r,t,si; clrscr(); printf("enter principle, Rate of interest & time to find simple interest: "); scanf("%d%d%d",&p,&r,&t); si=(p*r*t)/100; printf("simple intrest= %d",si); getch(); } 4.Program to convert temperature from degree centigrade to Fahrenheit: #include<stdio.h> #include<conio.h> void main() { float c,f;

11.Program to find that entered year is leap year or not

18. Program to print stars Sequence2.

#include<stdio.h> #include<conio.h> void main() void main() { { int n; int i,j,k; clrscr(); clrscr(); printf("enter any year: "); for(i=1;i<=5;i++) scanf("%d",&n); { if(n%4==0) for(j=5;j>=i;j--) printf("year is a leap year"); else printf(" "); printf("year is not a leap year"); for(k=1;k<=i;k++) getch(); printf("*"); }12.Program to find whether given printf("\n"); no is even or odd. } getch(); #include<stdio.h> } #include<conio.h> 19. Program to print Fibonacci void main() { series up to 100. int n; #include<stdio.h> clrscr(); #include<conio.h> printf("enter any no: "); void main() scanf("%d",&n); { if(n%2==0) int a=1,b=1,c=0,i; printf("no is even"); clrscr(); else printf("%d\t%d\t",a,b); printf("no is odd"); for(i=0;i<=10;i++) getch(); { } c=a+b; 13. Program to shift inputed data if(c<100) by two bits to the left. { #include<stdio.h> printf("%d\t",c); #include<conio.h> } void main() a=b; { b=c; int x,y; } clrscr(); printf("Read the integer from getch(); keyboard :- "); } scanf("%d",&x); 20) Program to find factorial x<<=3; of a number. y=x; #include<stdio.h> printf("\nThe left shifted data is = #include<conio.h> %d ",y); void main() getch(); { } int n,i,fact=1; 14. Program to use switch clrscr(); statement. Display Monday to printf("Enter any no: "); Sunday: scanf("%d",&n); #include<stdio.h> for(i=n;i>=1;i--) #include<conio.h> { void main() fact=fact*i; { } char ch;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) clrscr(); clrscr(); printf("enter m for Monday\nt for printf("enter temp in centigrade: "); Tuesday\nw for Wednesday\nh for scanf("%f",&c); Thursday\nf for Friday\ns for f=(1.8*c)+32; Saturday\nu for Sunday); printf("temp in Fahrenheit=%f",f); scanf("%c",&ch); getch(); switch(ch) } { 5. Program to calculate sum of 5 subjects & case 'm': find percentage. case 'M': #include<stdio.h> printf("monday"); #include<conio.h> break; void main() case 't': { case 'T': int s1,s2,s3,s4,s5,sum,total=500; printf("tuesday"); float per; break; clrscr(); case 'w': case 'W': printf("enter marks of 5 subjects: "); scanf("%d%d%d%d%d",&s1,&s2,&s3,&s4,&s5); printf("wednesday"); break; sum=s1+s2+s3+s4+s5; case 'h': printf("sum=%d",sum); case 'H': per=(sum*100)/total; printf("thusday"); printf("percentage=%f",per); break; getch(); case 'f': } case 'F': 6. Program to show swap of two nos printf("friday"); without using third variable. break; #include<stdio.h> case 's': #include<conio.h> case 'S': void main() printf("saturday"); { break; int a,b; case 'u': clrscr(); case 'U': printf("enter value for a & b: "); printf("sunday"); scanf("%d%d",&a,&b); break; a=a+b; default : b=a-b; printf("wrong input"); a=a-b; break; printf("after swapping the value of a & b: %d } %d",a,b); getch(); getch(); } } 15. program to display 7. Program to reverse a given number: arithmetic operator using #include<stdio.h> switch case. #include<conio.h> #include<stdio.h> #include<conio.h> void main() void main() { { int n,a,r=0; int a,b,n,s,m,su,d; clrscr(); clrscr(); printf("enter any no to get its reverse: "); printf("enter two no's : "); scanf("%d",&n); scanf("%d%d",&a,&b); while(n>=1) printf("enter 1 for sum\n2 for { a=n%10; multiply\n3for subtraction\n4 for r=r*10+a; division: ");

printf("Factorial=%d",fact); getch(); } 21. Program to find whether


given no is a prime no or not

#include<stdio.h> #include<conio.h> void main() { int i,n,r=0; clrscr(); printf("Enter any no: "); scanf("%d",&n); for(i=2;i<=n-1;i++) { if(n%i==0) r=1; break; } if(r==0) printf("prime no"); else printf("Not prime"); getch(); } 22. Program to display sum of
series 1+1/2+1/3+.+1/n.

#include<stdio.h> #include<conio.h> void main() { int n,i,sum=0; clrscr(); printf("Enter any no: "); scanf("%d",&n); printf("1"); for(i=2;i<=n-1;i++) printf(" 1/%d +",i); for(i=1;i<=n;i++) sum=sum+i; printf(" 1/%d",n); printf("\nSum=1/%d",sum+1/n); getch(); } 23Program to display series
and find sum of 1+3+5+..+n

#include<stdio.h> #include<conio.h> void main() { int n,i,sum=0;

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) n=n/10; scanf("%d",&n); } switch(n) printf("reverse=%d",r); { getch(); case 1: } s=a+b; 8. Program to find gross salary: printf("sum=%d",s); #include<stdio.h> break; #include<conio.h> case 2: void main() m=a*b; { printf("multiply=%d",m); int gs,bs,da,ta; break; clrscr(); case 3: printf("enter basic salary: "); su=a-b; scanf("%d",&bs); printf("subtraction=%d",su); da=(10*bs)/100; break; ta=(12*bs)/100; case 4: gs=bs+da+ta; printf("gross salary=%d",gs); d=a/b; getch(); printf("divission=%d",d); } break; 9.to find greatest of three number. default: #include<stdio.h> printf("wrong input"); #include<conio.h> break; void main() } { getch(); int a,b,c; } clrscr(); 16. Program to display first printf("enter value of a, b & c: "); 10 natural no & their sum. scanf("%d%d%d",&a,&b,&c); #include<stdio.h> if((a>b)&&(a>c)) #include<conio.h> void main() printf("a is greatest"); { if((b>c)&&(b>a)) int i,sum=0; printf("b is greatest"); clrscr(); if((c>a)&&(c>b)) for(i=1;i<=10;i++) printf("c is greatest"); { getch(); printf("%d no is= %d\n",i,I); } sum=sum+i; 10. Program to show the use of conditional } operator: printf("sum =%d",sum); #include<stdio.h> getch(); #include<conio.h> } void main() 17. Program to print stars { Sequence1: clrscr(); #include<stdio.h> printf("enter value for a & b: "); #include<conio.h> scanf("%d%d",&a,&b); void main() (a>b)?printf("a is greater"):printf("b is { greater"); int i,j; getch(); clrscr(); } for(i=1;i<=5;i++) { for(j=1;j<=i;j++) printf("*"); printf("\n");

clrscr(); printf("Enter any no: "); scanf("%d",&n); for(i=1;i<n;i=i+2) { printf("%d+",i); sum=sum+i; } printf("%d",n); printf("\nsum=%d",sum+n); getch(); } 24. Program to use bitwise
AND operator between the two integers

#include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf("Read the integers from keyboard:- "); scanf("%d %d",&a,&b); c=a&b; printf("\nThe Answer after ANDing is: %d ",c); getch(); } 25. Program to add two
number using pointers

#include<stdio.h> #include<conio.h> void main() { int *p1,*p2,sum; clrscr(); printf("enter two no's: "); scanf("%d%d",&*p1,&*p2); sum=*p1+*p2; printf("sum=%d",sum); } 26. Program to show sum of
10 elements of array & show the average

void main() { int a[10],i,sum=0; float av; clrscr(); printf("enter elements of an aaray: "); for(i=0;i<10;i++) scanf("%d",&a[i]); for(i=0;i<10;i++)

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) } getch(); }

sum=sum+a[i]; printf("sum=%d",sum); av=sum/10; printf(average=%.2f,av); }

27.Program to find the maximum no in an array.

31.Program to display a matrix.

34.Program to find multiplication of two matrices

void main() { int a[5],max,i; printf("enter element for the array: "); for(i=0;i<5;i++) scanf("%d",&a[i]); max=a[0]; for(i=1;i<5;i++) { if(max<a[i]) max=a[i]; } printf("maximum no= %d",max); getch(); } 28.Program to display a matrix main() { int a[3][2],b[3][2],i,j; printf("enter value for a matrix: "); for(i=0;i<3;i++) { for(j=0;j<2;j++) scanf("%d",&a[i][j]); } printf("enter value for b matrix: "); for(i=0;i<3;i++) { for(j=0;j<2;j++) scanf("%d",&b[i][j]); } printf("\na matrix is\n\n"); for(i=0;i<3;i++) { for(j=0;j<2;j++) { printf(" %d ",a[i][j]); } printf("\n"); } printf("\nb matrix is\n\n"); for(i=0;i<3;i++)

#include<stdio.h> #include<conio.h> void main() { int a[3][2],b[3][2],i,j; clrscr(); printf("enter value for a matrix: "); for(i=0;i<3;i++) { for(j=0;j<2;j++) scanf("%d",&a[i][j]); } printf("enter value for b matrix: "); for(i=0;i<3;i++) { for(j=0;j<2;j++) scanf("%d",&b[i][j]); } printf("\na matrix is\n\n"); for(i=0;i<3;i++) { for(j=0;j<2;j++) { printf(" %d ",a[i][j]); } printf("\n"); } printf("\nb matrix is\n\n"); for(i=0;i<3;i++) { for(j=0;j<2;j++) { printf(" %d ",b[i][j]); } printf("\n"); } getch(); } 32.Program to find sum of
two matrices

#include<stdio.h> #include<conio.h> void main() { int a[3][2],b[3][2],c[3][2],i,j; clrscr(); printf("enter value for 1 matrix: "); for(i=0;i<3;i++) { for(j=0;j<2;j++) scanf("%d",&a[i][j]); } printf("enter value for 2 matrix: "); for(i=0;i<3;i++) { for(j=0;j<2;j++) scanf("%d",&b[i][j]); } for(i=0;i<3;i++) { for(j=0;j<2;j++) c[i][j]=a[i][j]*b[i][j]; } printf("matrix is\n"); for(i=0;i<3;i++) { for(j=0;j<2;j++) { printf(" %d ",c[i][j]); } printf("\n"); } getch(); }
35.Program to find transpose of a matrix.

#include<stdio.h> #include<conio.h> void main() { int a[3][2],b[2][3],i,j;

#include<stdio.h>

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) { #include<conio.h> for(j=0;j<2;j++) { void main() printf(" %d ",b[i][j]); { } int a[3][2],b[3][2],c[3][2],i,j; printf("\n"); } getch(); } clrscr(); printf("Enter value for 1 matrix: "); 29.Program to show sum of 10 elements for(i=0;i<3;i++) of array & show the average. { #include<stdio.h> for(j=0;j<2;j++) #include<conio.h> scanf("%d",&a[i][j]); void main() } { printf("Enter value for 2 matrix: "); int a[10],i,sum=0; for(i=0;i<3;i++) float av; { clrscr(); for(j=0;j<2;j++) printf("enter elements of an aaray: "); scanf("%d",&b[i][j]); } for(i=0;i<10;i++) for(i=0;i<3;i++) scanf("%d",&a[i]); { for(i=0;i<10;i++) for(j=0;j<2;j++) sum=sum+a[i]; c[i][j]=a[i][j]+b[i][j]; } printf("sum=%d",sum); printf("Sum of matrix is\n"); av=sum/10; for(i=0;i<3;i++) printf(average=%.2f,av); { getch(); for(j=0;j<2;j++) } { printf("%d\t",c[i][j]); 30.Program to find the maximum no } in an array. printf("\n"); #include<stdio.h> } #include<conio.h> getch(); void main() } { 33.Program to find int a[5],max,i; subtraction of two matrices clrscr(); printf("enter element for the array: "); #include<stdio.h> for(i=0;i<5;i++) #include<conio.h> scanf("%d",&a[i]); max=a[0]; void main() for(i=1;i<5;i++) { { int a[5],b[5],c[5],i; if(max<a[i]) clrscr(); max=a[i]; printf("enter value for array a "); } for(i=0;i<5;i++) printf("maximum no= %d",max); scanf("%d",&a[i]); getch(); printf("enter value for array b "); } for(i=0;i<5;i++) scanf("%d",&b[i]); for(i=0;i<5;i++) c[i]=a[i]-b[i]; printf("subtraction");

clrscr(); printf("Enter value for matrix: "); for(i=0;i<3;i++) { for(j=0;j<2;j++) scanf("%d",&a[i][j]); } printf("Matrix:\n"); for(i=0;i<3;i++) { for(j=0;j<2;j++) printf(" %d ",a[i][j]); printf("\n"); } for(i=0;i<3;i++) { for(j=0;j<2;j++) b[j][i]=a[i][j]; } printf("Transpose matrix:\n"); for(i=0;i<2;i++) { for(j=0;j<3;j++) printf(" %d ",b[i][j]); printf("\n"); } getch(); } 36.Program to find the
maximum number in array using pointer.

#include<stdio.h> #include<conio.h> void main() { int max,i,*a[5]; clrscr(); printf("enter element for the array: "); for(i=0;i<5;i++) scanf("%d",&*a[i]); max=*a[0]; for(i=1;i<5;i++) { if(max<*a[i]) max=*a[i]; } printf("maximum no= %d",max); getch(); }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) for(i=0;i<5;i++) printf(" %d ",c[i]); getch(); }

37.Program to reverse a number using pointer

42.Program to show table of a


number using functions.

46Program to find whether a string is palindrome or not.

#include<stdio.h> #include<conio.h> void main() { int *n,a,r=0; clrscr(); printf("enter any no to get its reverse: "); scanf("%d",&*n); while(*n>=1) { a=*n%10; r=r*10+a; *n=*n/10; } printf("reverse=%d",r); getch(); } 38.Program to show input and
output of a string.

void main() { void table(); clrscr(); table(); getch(); } void table() { int n,i,r; printf("enter a no to know table: "); scanf("%d",&n); for(i=1;i<=10;i++) { r=n*i; printf("%d*%d=%d\n",n,i,r); } } 43.Program to show call by
reference.

#include<stdio.h> #include<conio.h> void main() { char s1[20],s2[20]; clrscr(); printf("enter a string: "); scanf("%s",s1); strcpy(s2,s1); strrev(s2); if(strcmp(s1,s2)==0) printf("string is a palindrome"); else printf("not a palindrome string"); getch(); }
.

#include<stdio.h> #include<conio.h> void main() { char a[50]; clrscr(); printf("enter any string: "); gets(a); puts(a); getch(); } 39.Program to find square of a
number using functions.

#include<stdio.h> #include<conio.h> void main() { int a,b; clrscr(); Printf(Enter value of a and b); Scanf(%d%d,&a,&b); printf("value of a= %d & value of b=%d before swap",a,b); swap(&a,&b); printf("\nvalue of a=%d & b=%d after swap",a,b); getch(); } int swap(int *x,int *y) { int temp; temp=*x; *x=*y; *y=temp;

#include<stdio.h> #include<conio.h> void main() { int rev(int); int r,a; clrscr();

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) printf("enter any no: "); } scanf("%d",&a); 44.Program to find largest of r=rev(a); two numbers using functions. printf("square is : %d",r); #include<stdio.h> getch(); #include<conio.h> } void main() int rev(int x) { { void max(); return(x*x); clrscr(); } max(); getch(); 40.Program to swap two } numbers using functions void max() { #include<stdio.h> int a[5],max,n,i; #include<conio.h> printf("How many no's you want to void main() enter: "); { scanf("%d",&n); void swap(int,int); printf("Enter element for the array: "); int a,b,r; for(i=0;i<n;i++) clrscr(); scanf("%d",&a[i]); printf("enter value for a&b: "); max=a[0]; scanf("%d%d",&a,&b); for(i=1;i<5;i++) swap(a,b); { getch(); if(max<a[i]) } max=a[i]; void swap(int a,int b) } { printf("maximum no= %d",max); int temp; } temp=a; a=b; 45.Program to find factorial of a b=temp; number using recursion. printf("after swapping the value for a & #include<stdio.h> b is : %d %d",a,b); #include<conio.h> } void main() 41.Program to find factorial of a { number using functions. int n; clrscr(); #include<stdio.h> printf("enter number: "); #include<conio.h> scanf("%d",&n); void main() if(n<0) { printf("invalid number"); int a,f; else int fact(int); printf("%d!=%d",n,fact(n)); clrscr(); getch(); printf("enter a no: "); scanf("%d",&a); } f=fact(a); int fact(int x) printf("factorial= %d",f); { getch(); if(x==0) } return 1; int fact(int x) else { return(x*fact(x-1));

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer) int fac=1,i; } for(i=x;i>=1;i--) fac=fac*i; return(fac); }

G.R Solutions Design and Developed by Mr. Goutam Sontakke (Software Developer)

Potrebbero piacerti anche