Anda di halaman 1dari 93

E-528-529, sector-7, Dwarka, New delhi-110075 (Nr. Ramphal chowk and Sector 9 metro station) Ph.

011-47350606, (M) 7838010301-04 www.eduproz.in

Educate Anytime...Anywhere...

"Greetings For The Day" About Eduproz We, at EduProz, started our voyage with a dream of making higher education available for everyone. Since its inception, EduProz has been working as a stepping-stone for the students coming from varied backgrounds. The best part is the classroom for distance learning or correspondence courses for both management (MBA and BBA) and Information Technology (MCA and BCA) streams are free of cost. Experienced faculty-members, a state-of-the-art infrastructure and a congenial environment for learning - are the few things that we offer to our students. Our panel of industrial experts, coming from various industrial domains, lead students not only to secure good marks in examination, but also to get an edge over others in their professional lives. Our study materials are sufficient to keep students abreast of the present nuances of the industry. In addition, we give importance to regular tests and sessions to evaluate our students progress. Students can attend regular classes of distance learning MBA, BBA, MCA and BCA courses at EduProz without paying anything extra. Our centrally air-conditioned classrooms, well-maintained library and well-equipped laboratory facilities provide a comfortable environment for learning.

Honing specific skills is inevitable to get success in an interview. Keeping this in mind, EduProz has a career counselling and career development cell where we help student to prepare for interviews. Our dedicated placement cell has been helping students to land in their dream jobs on completion of the course.

EduProz is strategically located in Dwarka, West Delhi (walking distance from Dwarka Sector 9 Metro Station and 4minutes drive from the national highway); students can easily come to our centre from anywhere Delhi and neighbouring Gurgaon, Haryana and avail of a quality-oriented education facility at apparently no extra cost.

Why Choose Edu Proz for distance learning?

Edu Proz provides class room facilities free of cost. In EduProz Class room teaching is conducted through experienced faculty. Class rooms are spacious fully air-conditioned ensuring comfortable ambience. Course free is not wearily expensive. Placement assistance and student counseling facilities. Edu Proz unlike several other distance learning courses strives to help and motivate pupils to get high grades thus ensuring that they are well placed in life. Students are groomed and prepared to face interview boards. Mock tests, unit tests and examinations are held to evaluate progress. Special care is taken in the personality development department.

"HAVE A GOOD DAY"

Karnataka State Open University

(KSOU) was established on 1st June 1996 with the assent of H.E. Governor of Karnataka as a full fledged University in the academic year 1996 vide Government notification No/EDI/UOV/dated 12th February 1996 (Karnataka State Open University Act 1992). The act was promulgated with the object to incorporate an Open University at the State level for the introduction and promotion of Open University and Distance Education systems in the education pattern of the State and the country for the Co-ordination and determination of standard of such systems. Keeping in view the educational needs of our country, in general, and state in particular the policies and programmes have been geared to cater to the needy.

Karnataka State Open University is a UGC recognised University of Distance Education Council (DEC), New Delhi, regular member of the Association of Indian Universities (AIU), Delhi, permanent member of Association of Commonwealth Universities (ACU), London, UK, Asian Association of Open Universities (AAOU), Beijing, China, and also has association with Commonwealth of Learning (COL).

Karnataka State Open University is situated at the NorthWestern end of the Manasagangotri campus, Mysore. The campus, which is about 5 kms, from the city centre, has a serene atmosphere ideally suited for academic pursuits. The University houses at present the Administrative Office, Academic Block, Lecture Halls, a well-equipped Library, Guest House

Cottages, a Moderate Canteen, Girls Hostel and a few cottages providing limited accommodation to students coming to Mysore for attending the Contact Programmes or Termend examinations.

BC0037-1.1 Introduction
Introduction This unit has the following objectives To understand the importance of object oriented programming approach over procedural languages To learn the basic features supported by OOP languages To learn the basic construct of a C++ program and learn to compile and execute it

BC0037-1.2 Evolution of Programming methodologies


Evolution of Programming methodologies The programming languages have evolved from machine languages, assembly languages to high level languages to the current age of programming tools. While machine level language and assembly language was difficult to learn for a layman, high level languages like C, Basic, Fortran and the like was easy to learn with more English like keywords. These languages were also known as procedural languages as each and every statement in the program had to be specified to instruct the computer to do a specific job. The procedural languages focused on organizing program statements into procedures or functions. Larger programs were either broken into functions or modules which had defined purpose and interface to other functions. Procedural approach for programming had several problems as the size of the softwares grew larger and larger. One of the main problems was data being completely forgotten. The emphasis was on the action and the data was only used in the entire process. Data in the program was created by variables and if more than one functions had to access data, global variables were used. The concept of global variables itself is a problem as it may be accidentally modified by an undesired function. This also leads to difficulty in debugging and modifying the program when several functions access a particular data.

The object oriented approach overcomes this problem by modeling data and functions together there by allowing only certain functions to access the required data. The procedural languages had limitations of extensibility as there was limited support for creating user defined datatypes and defining how these datatypes will be handled. For example if the programmer had to define his own version of string and define how this new datatype will be manipulated, it would be difficult. The object oriented programming provides this flexibility through the concept of class. Another limitation of the procedural languages is that the program model is not closer to real world objects . For example, if you want to develop a gaming application of car race, what data would you use and what functions you would require is difficult questions to answer in a procedural approach. The object oriented approach solves this further by conceptualizing the problem as group of objects which have their own specific data and functionality. In the car game example, we would create several objects such as player, car, traffic signal and so on. Some of the languages that use object oriented programming approach are C++, Java, Csharp, Smalltalk etc. We will be learning C++ in this text to understand object oriented programming. C++ is a superset of C. Several features are similar in C and C++. Self Assessment Questions 1. List the limitations of procedural languages 2. _______ is an OOP Language 3. In OOP approach programmers can create their own data types. True/False 4. In procedural languages, the programs are written by dividing the programs into smaller units known as __________

BC0037-1.3 Introduction to OOP and its basic features


Introduction to OOP and its basic features As discussed earlier, one of the basic concept in Object Oriented Programming approach is bundling both data and functions into one unit known as object. The functions of a particular object can only access the data in the object providing high level of security for the data. The functions in the object are known as member functions or sometimes as methods. The key features of OOP programming languages are:

Objects and Classes

An Object is a program representation of some real-world thing (i.e person, place or an event). Objects can have both attributes(data) and behaviours (functions or methods). Attributes describe the object with respect to certain parameters and Behaviour or functions describe the functionality of the object. Table 1.1 Example of Objects Polygon Object
Attributes Behaviour Move

Bank Account
Behaviour Attributes

Deduct Funds

Position Fill Color Border color

Erase Changecolor

Account number Transferfunds Balance DepositFunds Showbalance

According to Pressman, Objects can be any one of the following: a) External entities b) Things c) Occurrences or events d) Roles e) Organisational units f) Places g) Data Structures For example, objects can be an menu or button in an graphic user interface program or it may be an employee in an payroll application. Objects can also represent a data structure such as a stack or a linked list. It may be a server or a client in an networking environment. Objects with the same data structure and behavior are grouped together as class. In other words, Objects are instances of a class. Classes are templates that provide definition to the objects of similar type. Objects are like variables created whenever necessary in the program. For example, Employee may be a class and Pawan, Sujay and Ganesh are objects of the class employees. Just as you can create as many variables of a default datatype such as integer, you can create as many objects of a class. Classes and Objects support data encapsulation and data hiding which are key terms describing object oriented programming languages. Data and functions are said to be encapsulated in an single entity as object. The data is said to be hidden thus not allowing accidental modification.

Inheritance Inheritance is one of the most powerful feature of Object Oriented Programming Languages that allows you to derive a class from an existing class and inherit all the characteristics and behaviour of the parent class. This feature allows easy modification of existing code and also reuse code. The ability to reuse components of a program is an important feature for any programming language

Polymorphism and Overloading Operator overloading feature allows users to define how basic operators work with objects. The operator + will be adding two numbers when used with integer variables. However when used with user defined string class, + operator may concatenate two strings. Similarly same functions with same function name can perform different actions depending upon which object calls the function. This feature of C++ where same operators or functions behave differently depending upon what they are operating on is called as polymorphism (Same thing with different forms). Operator overloading is a kind of polymorphism. OOP approach offers several advantages to the programmers such as

Code can be reused in situations requiring customization o Program modeling and development closer to real world situations and objects Easy to modify code o Only required data binded to operations thus hiding data from unrelated functions Self Assessment Questions 1. _____________ feature in OOP allows to reuse code. 2. The concept of bundling data and functions into single unit is termed as ___________ 3. Object is an __________ of a class 4. Give an example of a class and an object 5. ______________ is an advantage of OOP approach

BC0037-1.4 Basic components of a C++ Program and program structure


1.4 Basic components of a C++ Program and program structure

The C++ is a superset of C. At the basic level, the programs look similar in both C and C++. Every statement in C++ ends with a semicolon (;). All the reserved words have to be written in small case and the c++ compiler is case sensitive. Data in programming languages are stored in variables. To create a variable, the variable should support an inbuilt datatype. The variable is a name given to a particular location in the memory and the value stored in a variable can be altered during program execution. The datatypes supported in C++ are listed below Table 1.2 Basic Datatypes in c++ Data Type Size (in bytes) Int 2 Bool 1 Char 1 Long 4 Float 4 Double 8 Long double 10 Unsigned int 2 Values that can be taken -32768 to 32767 False and true / 0 and 1 -128 to 127 -2,147,483,648 to 2,147,483,647 3.4 X 10-38 to 3.4 X 1038 (Precision 7) 1.7 X 10-308 to 1.7 X 10308 (Precision 15) 3.4 X 10-4932 to 1.1 X 104932 (Precision 19) 0 to 65,535

Variables can be named according to following rules


Can comprise of 1 to 8 alphabets, digits or underscore First character should be an alphabet Names are case sensitive Reserve words of c++ cannot be used

Variables have to be declared before using them in the program. The declaration is done in the following way: datatype variablename Eg: int data ; The above declaration declares a integer variable named data. The value stored in int data by default is a junk value. Values can also be assigned to the variable during declarations or initialized separately using the assignment operator =. Eg: int data=0; Or int data; data=0;

Constants are those which do not change during execution of a program. The constants in C++ can be numeric, character or string constants. Examples of each are shown in table 1.3 Table 1.3 Example of Constants Constant Numeric Constant Character Constant String Constant Example 23000 Constraints

Can be negative or positive, cannot contain blanks or 450.6 (Floating commas, or $ point) Any character enclosed within single quotes, represented by A unique ASCII number in the memory Set of characters enclosed in double quotes, last character in Hello the string is null character \0

Operators supported in C++ are listed below. Unary operators are used with one operand and binary operator is used with two operands. Table 1.4 Operators in C++ Arithmetic Operators + * / % ++ Relational Operators > >= < <= == != Logical Operators && || ! Action Unary as well as binary Subtraction for binary and minus for unary Binary Addition Binary Multiplication Binary Division Binary Modulus (remainder after dividing) Unary Decrement value by one Unary Increment value by one Type Action Binary Greater than Binary Greater than or equal Binary Less than Binary Less than equal Binary Comparision for equality Binary Comparision for inequality Type Action Binary AND Binary OR Unary NOT Type

Lets begin with a simple c++ program // sum.cpp

#include<iostream.h> void main() { int a,b,sum; cout<<Please enter any two numbers<<endl; cin>>a>>b; sum=a+b; cout<<Sum of two numbers is <<sum; } The above program asks the user to enter two numbers and displays the sum of the two numbers. Iostream.h is a header file. The first statement of the above program is required if you would like to include the cin and cout statements which is used for standard input or input from keyboard and standard output or output to display screen. cin and cout are actually predefined objects in C++. Iostream.h file contains the declarations for using the cin and cout statements. There are several such header files which have to be included depending on the functions you are using. We will come across many such header files as we progress. Every C++ program should have a main() function. C++ allows you to create your own functions in the program, like C. However the program execution always begins with the master function main(). Paranthesis are used to group statements belonging to one function or program statement. Every opening parathesis ({ ) should have a matching closing parathesis ( }). The third statement declares three integer variables a, b and sum. The fourth statement displays Please enter any two numbers on the display screen using cout statement. Cout (pronounced as C out) uses << or insertion operator to push data to the output stream. Operators known as manipulators can be used along with the << operator to modify the way data is displayed. Endl is an operator which is similar to \n character in C that inserts a linefeed into the output. The first cout statement in the program displays a statement where as the second cout statement displays a statement and the value stored in the variable sum. Cin (pronounced as c in) statement uses >> or extraction operator to feed the data to the input stream. The above cin statement waits for user to enter two integers. The values entered by the user is then stored in the variables a and b. Each variable in cin statement should separated by >> operator.

Comment statements can be included in the program by prefixing the statement with // for single line comments. Comments add clarity to the program. Multiple line comments can be added by enclosing the statements between /* and */. Self Assessment Questions 1. ______________ is a header file used in c++ that handles input and output functions. 2. ____________ statement is used to input data from the user in c++. 3. ______________ statement is used to display data on the display screen in c++. 4. ______________ is a master function required in all C++ program and program execution begins from the first statement of this function.

BC0037-1.5 Compiling and Executing C++ Program


Compiling and Executing C++ Program 1. There are three steps in executing a c++ program: Compiling, Linking and Running the program. The c++ programs have to be typed in a compiler. All the programs discussed in the book will be compiled on turbo c++ compiler. The turbo c++ compiler comes with an editor to type and edit c++ program. After typing the program the file is saved with an extension .cpp. This is known as source code. The source code has to be converted to an object code which is understandable by the machine. This process is known as compiling the program. You can compile your program by selecting compile from compile menu or press Alt+f9. After compiling a file with the same name as source code file but with extension .obj. is created. Second step is linking the program which creates an executable file .exe (filename same as source code) after linking the object code and the library files (cs.lib) required for the program. In a simple program, linking process may involve one object file and one library file. However in a project, there may be several smaller programs. The object codes of these programs and the library files are linked to create a single executable file. Third and the last step is running the executable file where the statements in the program will be executed one by one. Fig 1.1 shows the entire process. When you execute the program, the compiler displays the output of the program and comes back to the program editor. To view the output and wait for user to press any key to return to the editor, type getch() as the last statement in the program. Getch() is an inbuilt predefined library function which inputs a character from the user through standard input. However you should include another header file named conio.h to use this function. Conio.h contains the necessary declarations for using this function. The include statement will be similar to iostream.h.

Fig. 1.1: Compiling and Linking

During compilation, if there are any errors that will be listing by the compiler. The errors may be any one of the following 1. Syntax error This error occurs due to mistake in writing the syntax of a c++ statement or wrong use of reserved words, improper variable names, using variables without declaration etc. Examples are : missing semi colon or paranthesis, type integer for int datatype etc. Appropriate error message and the statement number will be displayed. You can see the statement and make correction to the program file, save and recompile it. 2. Logical error This error occurs due to the flaw in the logic. This will not be identified by the compiler. However it can be traced using the debug tool in the editor. First identify the variable which you suspect creating the error and add them to watch list by selecting Debug ->Watches->Add watch. Write the variable name in the watch expression. After adding all the variables required to the watch list, go to the statement from where you want to observe. If you are not sure, you can go to the first statement of the program. Then select Debug ->Toggle Breakpoint (or press ctrl + f8). A red line will appear on the statement. Then Run the program by selecting Ctrl + f9 or Run option from run menu. The execution will halt at the statement where you had added the breakpoint. The watch variables and their values at that point of time will be displayed in the bottom in the watch window. Press F8 to execute the next statement till you reach the end of the program. In this way you can watch closely the values in the watch variables after execution of each and every statement in the program. If you want to exit before execution of the last statement press Ctrl + Break. To remove the breakpoint in the program go to the statement where you have added breakpoint select Debug ->Toggle Breakpoint (or press ctrl + f8). Select Debug -> watch >remove watches to remove the variables in the watch list. This tool helps in knowing the values taken by the variable at each and every step. You can compare the expected value with the actual value to identify the error. 3. Linker error This error occur when the files during linking are missing or mispelt 4. Runtime error

This error occurs if the programs encounters division by zero, accessing a null pointer etc during execution of the program Self Assessment Questions 1. ___________, ______________ and _____________ are phases in execution of a C++ program 2. The logical error is identified by the compiler. True/False 3. ________________ is the extension of C++ program source files 4. ________________ is the extension of C++ object code

BC0037-1.6 Summary
Summary Object oriented Programming enables storing data and functions together which enables hiding data from unnecessary exposure. Procedural languages differs from the Object oriented programming in the approach used in solving the problem. While the former focuses on organizing programs around functions, the later focuses organizing programs around classes. Classes allow users to define their own datatypes and functionality. This allows extension of the basic datatypes supported by the language. Reusability of code through inheritance allows users to use the existing code without modifying it but also extend the functionality of the existing code. The C++ programs are similar to C except for the object oriented programming features. Every C++ program has a main function from where the execution starts. C++ programs goes through two phases ie compiling and linking before execution.

BC0037-2.1 Introduction
Introduction This unit has the following objectives To learn to use selection control statements in C++ To learn to use loops or iteration in C++ To implement programs using relational, logical, increment and decrement operators in C++

BC0037-2.2 Selection control statements in C++


Selection control statements in C++ There are basically two types of control statements in c++ which allows the programmer to modify the regular sequential execution of statements.They are selection and iteration statements. The selection statements allow to choose a set of statements for execution depending on a condition. If statement and switch statement are two statements which allow selection in c++. There is also an operator known as conditional operator which enables selection. If statement Syntax : if (expression or condition) { statement 1; statement 2; } else { statement 3; statement 4; } The expression or condition is any expression built using relational operators which either yields true or false condition. If no relational operators are used for comparison, then the expression will be evaluated and zero is taken as false and non zero value is taken as true. If the condition is true, statement1 and statement2 is executed otherwise statement 3 and statement 4 is executed. Else part in the if statement is optional. If there is no else part, then the next statement after the if statement is exceuted, if the condition is false. If there is only one statement to be executed in the if part or in the else part, braces can be omitted. Following example program implements the if statement. // evenodd.cpp # include <iostream.h> # include <conio.h>

void main() { int num; cout<<Please enter a number<<endl; cin>>num; if ((num%2) == 0) cout<<num << is a even number; else cout<<num << is a odd number; getch(); } The above program accepts a number from the user and divides it by 2 and if the remainder (remainder is obtained by modulus operator) is zero, it displays the number is even, otherwise as odd. We make use of the relational operator == to compare whether remainder is equal to zero or not. Nested If statement If statement can be nested in another if statement to check multiple conditions. If (condition1) { if (condition 2) { statement1; Statement2; } else if (condition3) {statement3; }

} else statement4; The flowchart of the above example is shown below

Fig. 2.1: Nested If Statement Multiple conditions can be checked using logical && operator(AND) and || operator (OR). If ((condition1) && (condition2)) statement1; else statement2; In the above example statement1 will be executed if both the condition1 and condition2 are true and in all other cases statement2 will be executed. If ((condition1 || (condition2)) statement1; else statement2; In the above example statement1 will be executed if either condition1 or condition2 are true and even if both are true. Statement2 will be executed if both the conditions are false. The following program demonstrates the use of && operator and nested if statement.

//Large.cpp # include <iostream.h> void main() { int a,b,c; cout<<Please enter three numbers; cin>>a>>b>>c; if ((a>b) && (b>c)) cout<<a<< is the largest number; else if ((b>a) && (b>c)) cout<<b<< is the largest number; else if ((c>a) && (c>b)) cout<<c<< is the largest number; } The above program accepts three numbers from the user and displays which is the largest number among the three.( assumption is that all the numbers are unique, the program has to be modified if you would like to allow same number twice) Switch statement Nested ifs can be confusing if the if statement is deeply nested. One alternative to nested if is the switch statement which can be used to increase clarity in case of checking the different values of the same variable and execute statements accordingly. Syntax : Switch (variablename) { case value1: statement1; break; case value2: statement2;

break; case value3: statement3; break; default: statement4; } If the variable in the switch statement is equal to value1 then statement1 is executed, if it is equal to value2 then statement2 is executed, if it is value3 then statement3 is executed. If the variable value is not in any of the cases listed then the default case statement or statement4 is executed. The default case specification is optional, however keeping it is a good practice. It can also be used for displaying any error message. Each case can have any number of statements. However every case should have a break statement as the last statement. Break statement takes the control out of the switch statement. The absence of the break statement can cause execution of statements in the next case. No break is necessary for the last case. In the above example, default case does not contain a break statement. The flowchart for the switch statement is shown in Fig 2.2

Fig. 2.2: Switch Statement

The following program implements the switch statement position.cpp # include<iostream.h> void main()

{ char pos; int x=15, y=15; cout << you are currently located at <<x<< <<y<<endl; cout>>please choose the letter to move l for left, r for right, u for up and d for down <<endl; cin>>pos; switch (pos) { case l: x; break; case r: x++; break; case u: y++; break; case d: y; break; default: cout<<You selected a wrong option; } cout<< you are now located at <<x<< <<y; } The above program asks the user to enter l,r,u,d for allowing him to move left,right,up and down respectively. The position is initialised to 15 and 15 which are x and y coordinates of his position. Depending upon the what user has selected the the x and y co-ordinates are incremented or decremented by one(x++ is same as x=x+1). If the user types a letter other than l,r,u,d, he gets an error message. Since the switch variable is a character, l,u,r,d and enclosed within single quote. ++ and operator can be used as postfix or as prefix operator which has no effect if used as an independent statement. However if it used as part of an expression, the prefix operator will be

operated and then the expression will be evaluated whereas the postfix operated will be evaluated later. For example in the statement x= a+ (b++), a will be added to b and then stored in x and then the value of b will be incremented. If the same expression is written as x=a+(++b), the the b will be incremented and then added to a and stored in x. Conditional Operator Conditional operator (?:) is a handy operator which acts like a shortcut for if else statement. If you had to compare two variables a and b and then depending on which is larger, you wanted to store that variable in another variable called large. You would do this using if else statement in the following way: if (a>b) large=a; else large=b; The above can be done using conditional operator in the following way: large= (a>b) ? a : b ; Self Assessment Questions 1. In if else statement, at any point of time statements in both the if and else part may be executed. True/False 2. Conditional operator is an alternative to __________ statement 3. ++ operator increments the value of the operand by _________ 4. The ++ operator used as postfix and prefix has the same effect. True or False 5. Each case in switch statement should end with _________ statement

BC0037-2.3 Iteration statements in C++


Iteration statements in C++

Iteration or loops are important statements in c++ which helps to accomplish repeatitive execution of programming statements. There are three loop statements in C++ : while loop, do while loop and for loop
While loop

Syntax: while (condition expression) { Statement1; Statement 2; } In the above example, condition expression is evaluated and if the condition is true, then the statement1 and statement2 are executed. After execution, the condition is checked again. If true, the statements inside the while loop are executed again. This continues until the loop condition becomes false. Hence the variable used in the loop condition should be modified inside the loop so that the loop termination condition is reached. Otherwise the loop will be executed infinitely and the program will hang when executed. Also the loop variable should be iniatialised to avoid the variable taking junk value and create bugs in the program. The flowchart for the While statement is shown in Fig 2.3.

Fig. 2.3: While Statement

The following program implements the while loop // average1.cpp # include <iostream.h>

void main() { int n=0,a; int sum=0; cout<< enter five numbers; while (n<5) { cin>>a; sum=sum+a; n++; } cout<<Average of the numbers is<<(sum/n); } The above program accepts five numbers from the user and finds the average of the five numbers. In the above while loop, the variable n is initialized to zero and this variable keeps track of the count of numbers input from the user. It is incremented every time a number is input from the user. The number accepted from the user is added to the value stored in the sum variable. When n becomes 5 the while loop condition becomes false and the average of the numbers is printed. Please note that there is no semicolon after while and condition expression. Do..while loop The do while loop is same as while loop except that the condition is checked after the execution of statements in the do..while loop. Hence in do..while loop, statements inside the loop are executed atleast once. However, in while loop, since the condition is checked before, the statements inside the loop will not be executed if the loop condition is false. Syntax: do {

Statement1; Statement2 } while (condition expression); In the above example the statement1 and statement2 are executed and the condition is checked. If the condition is true then the statements are executed again and if the condition is false then the control is transferred to the next statement after the do..while statement. The flowchart for the do..while statement is shown in Fig 2.4

Fig. 2.4: Do..while Statement Please note that there is no semicolon after do, but there is a semicolon after the condition expression in while part. The average1.cpp program is rewritten using do..while loop as follows // average2.cpp # include <iostream.h> void main() { int n=0,a; int sum=0; cout<< enter five numbers; do {

cin>>a; sum=sum+a; n++; }while (n<5); cout<<Average of the numbers is<<(sum/n); } The decision on whether to use while or do..while statement depends on whether the statements inside the loop have to be executed atleast once or not. If it has to be executed atleast once, then the do..while statement should be used. For loop The for loop is one of the popular control statement as it is compact and clear in specification. The loop initialization, loop termination condition statement and statement for the next iteration are all included in one statement. Syntax: for(initialization statement;loop termination condition;statement to increment/decrement the loop variable) { Statement1; Statement2; } In the above example, initiation statement is executed first and then the termination is checked. If the condition is true, statement1 and statement2 will be executed. Then the third statement in the for loop is executed which modifies the loop control variable. The flowchart for the for statement is shown in Fig 2.5

Fig. 2.5: For Statement Please note that there is no semicolon after the for statement. The average2.cpp rewritten using for loop is as follows: // average3.cpp # include <iostream.h> void main() { int a; int sum=0; cout<< enter five numbers; for(int n=0;n<5;n++) { cin>>a; sum=sum+a; } cout<<Average of the numbers is<<(sum/n);

} In the above example n variable is loop variable which is initialized to zero. Please note that the variable is also declared inside the for loop. So this variable can be accessible only inside the for loop. The scope of the variables will be declared in detail in unit 4. The statements inside the loop are executed until the loop termination condition n<5 becomes false. After every iteration, the loop variable n is incremented. The following program demonstrates the use of for loop using decrement operator to find the factorial of a number. // factorial.cpp # include <iostream.h> void main() { int number,fact=1; cout<< enter a number; cin>>number; for(int i=number;i>1;i) fact=fact*i; cout<<Factorial of <<number<<is<<fact; } All the above loops can be nested. The inner loop is executed completely and then the outer loop is executed. For every iteration of outer loop, all the iterations of the inner loop is executed. The for statement can also have multiple initialization and decrement and increment statements as shown in the following expression for(i=0,j=0;i<=n;j++,i++) { statements; }

Please note that in case of multiple statements, each statement should be separated by a comma. Selection of which type of loop to be used depends on the programmer and his style. However you should use for loop if you know in advance how many times the loop has to be executed. If the loop has to be executed atleast once irrespective of whether the condition is true or false, then do while loop should be used. Self Assessment Questions 1. Which of the following loop will be executed atleast once even if the condition is false. a. For loop b. while loop c. do..while loop d. None of the above 2. ___________ is the loop variable in the loop for(int k=n;k!=0;k=k-2) 3. The loop for(int i=0;i<n;i++) will be executed till the statement _________ becomes false. 4. If there is more than one statements inside a loop, then the statement should be enclosed within ______________

BC0037-2.4 Break continue and exit statements in C++


2.4 Break, continue and exit statements in C++ All the loops or iteration statements discussed in previous section are executed until the loop condition becomes false. However if required, the control sequence can be changed by using break, continue or exit statements. Break statement transfers the control to the next statement after the loop and all the remaining statements and the iterations in the loop are skipped. It is used if you would like to exit the loop when a certain condition is met. In the switch statement break statement takes the control to the next statement after the switch statement. The following program demonstrates the use of break statement inside for loop. // prime.cpp # include <iostream.h> void main() { int number;

int prime=0; cout<<Enter a number; cin>>number; // check whether the number is divisible by any number from 2 to number/2 for (int i=2;i<=number/2;i++) { if ((number%i)==0) { prime=1; break; } } if (prime==0) cout<<The number is prime number; else cout<< The number is not a prime number; } In the above program, the user is asked to enter a number and the program checks whether the number is prime or not and displays the message accordingly. To check whether the number is prime or not, the number is divided by 2,3 and so on till number/2. If the number is divisible by any number, the variable prime is assigned a value one and the loop is terminated as there is no need to check whether the number is divisible by rest of the numbers. The value 1 in the prime indicates that the number was divisible by one of the numbers between 2 to number/2. Continue statement is used to take the control to the next iteration of the loop. It is used if the control has to be transferred to the next iteration of the loop based on a condition skipping all the other statements in the loop. The following program shows the use of continue statement. move.cpp # include<iostream.h>

# include<conio.h> void main() { int x,y; char choice=y; do { clrscr(); cout<<please enter the dividend; cin>>x; cout<<Please enter the divisor; cin>>y; if (y==0) { cout<<error!! Division by zero, try again; continue; } cout<<The quotient is <<(x/y); cout<<the remainder is<<(x%y); cout<<do u wish to continue; cin>>choice; }while (choice==y); }

In the above example clrscr() function which is a library function is used to clear the screen before accepting the input from the user. To use this function, conio.h header file must be included. Exit function in a program takes the control out of the program. Exit is an inbuilt library function. To use this function process.h header file has to be included in the program. The syntax of this function is exit(integer).While terminating the program, the integer is returned to the operating system. Usually the function integer 0 is used to imply no error or successful termination and non zero value implies error while exiting the program . Go to statement is a statement which should be avoided. It take the control to a particular statement. The statement should have a label. Syntax: goto statement labelname Statements can be given labels in the following way labelname: statement The use of goto statement should be avoided as it creates problems in program debugging and the program may have confusing jumps from one statement to another. Self Assessment Questions 1. _________ statement takes the control out of the loop. 2. __________ header file should be included to use exit function 3. __________ statement takes the control to the beginning of the loop. 4. ________ statement takes the control to a particular statement

BC0037-2.5 Summary
Summary Selection and iteration statements allow to execute statements in the program based on a condition bypassing the normal sequential execution. Selection is enabled through if statement, switch statement and conditional operator. Switch statement is suitable when you have multiple conditions to be checked and nested if can be avoided. Iteration is enabled in C++ through while, do..while and for loops. Loops execute the statements repeatitively until a particular condition becomes false. Break, continue and exit statements are used to transfer control out of the loop, to the next iteration of the loop and out of the program respectively.

BC0037-3.1 Introduction
Introduction This unit has the following objectives To understand what are arrays and how they are useful in C++ programming To learn to create and use multidimensional arrays To understand how strings are represented and used in C++

BC0037-3.2 Introduction to Arrays


Introduction to Arrays Arrays are used when you want to store related data of same type together with the same name so that you can access them easily. Arrays can be defined as datastructures that allow to store group of data of same datatype. You can retrieve data stored in the array in any order. For example, let us suppose you want to write a program which will help you to compute average marks scored by students in a class of 60. To allow this computation, your program should store marks scored by 60 students in a class separately, so that you can do any kind of computation when required. It would be tedious, if you had to create 60 different variables to store marks of 60 students and manage them separately. Arrays solves this problem, by grouping data of similar type with same name but can be referred separately through the position or the index number. Arrays should be declared like any other variable. However array size should be specified during declaration which determines how many elements the array can store. The following is a declaration of an integer array named data which can store 20 integers. int data[20]; Please note that in the above declaration, data is the name of the array followed by the size of the array enclosed within square brackets.The datatype of data stored by the array can be any default datatypes supported by c++ or user defined datatypes. Elements in the array can be accessed through index numbers. The data in the array are stored with index numbers 0,1, and so on. Since the index number starts with 0 the last index number of an array of size n will be n-1. The elements stored in the array are accessed by using the array name followed by the index number within the square brackets. For example, in the above array, the integers in the array can be accessed as data[0], data[1] and so on till data[19]. This makes it very easy to store and access large number of data. The code can be simplified by including common statements that needs to be performed on the array elements inside a loop and making the loop variable as the variable that stores the index variable.

The following programs shows how you can store and retrieve data from the array //max.cpp #include<iostream.h> void main() { int max=0, a[50]; for (int i=0; i<50;i++) { cin>>a[i]; if (a[i]>max) max=a[i]; } cout<<Largest number in the array is<<max; } In the above program, a is an array that stores 50 integers. The program accepts 50 integers from the user, and stores in an array and finds out the maximum number in the array. The a[i] represents a particular element in the array and i is the index number. As the iteration varies, the value stored in i also varies. Another interesting aspect of the array is that all the elements in the arrays are allotted consecutive spaces in the memory by the operating system. The following program sorts an array. Here nested for loops are used to enable this. //sort.cpp # include<iostream.h> void main() {

int a[10],temp; for (int i=0; i<10;i++) { cin>>a[i]; } cout<<Array after sorting is ; for(int j=0; j<9;j++) for(i=0;i<9;i++) { if (a[i]>a[i+1]) {temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; } } for (i=0; i<10;i++) { cout<<a[i]<<endl; } } Array elements can be initialized. All the elements in the array should be initialized. Every data should be separated by a comma and all elements enclosed within flower brackets as shown below int data[5] = {3,5,7,4,9}; In the above initialization, data[0] is initialized to 3, data[1] is initialized to 5 and so on..

Self Assessment Questions 1. Arrays group data of __________ type 2. An array declared as int a[10] can store __________ integers 3. a[5] represents the _________ integer in the above array. 4. Array elements are accessed through _______________

BC0037-3.3 Multidimensional Arrays


Multidimensional Arrays The arrays can be multidimensional as well to store the required data. For example a two dimensional array can be created to store data about a matrix. A 34 matrix that has 12 data elements can be created using the following declaration int mat[3][4]; The above array has 3 rows and four columns. The elements in the array can be accessed by two indexes. To refer to an element in the first row and second column mat[0][1] has to be used as the index starts from zero. The following program accepts from the user two 23 matrices and adds the two matrices. //matrix.cpp # include <iostream.h> void main() { int a[2][3], b[2][3], c[2][3];

int i,j; cout<<Enter the elements for the first 23 matrix; for (i=0;i<2;i++) for (j=0;j<3;j++) { cin>>a[i][j];} cout<<Enter the elements for the second 23 matrix; for (i=0;i<2;i++) for (j=0;j<3;j++) { cin>>b[i][j]; c[i][j]=a[i][j]+b[i][j]; } cout<<The resultant matrix is; for ( i=0;i<2;i++) { for ( j=0;j<3;j++) { cout<<c[i][j]<< ; } cout<< endl; } } Multi dimensional arrays can also be initialized as follows

int a[2][2] = {{ 3,4}, { 2, 7}} Every row elements are initialized by enclosing them in separate flower brackets.In the above example elements 3 and 4 will be initialized to a[0][0] and a[0][1] respectively. Self Assessment Questions 1. An array with the declaration int x[4][5] can store ________ numbers 2. In the above array the number in the third row and fourth column can be accessed by ____________ 3. int a[ ] [ ] is a valid declaration. True/False

BC0037-3.4 Strings and String related Library Functions


Strings and String related Library Functions Strings are nothing but character arrays. Strings are usually used to store data such as employee name, address, product description, password etc. The size of the string is defined during declaration like any other array. One basic difference between other arrays and strings is that the compiler stores an extra null character (/0) for every string to mark the end of the string. This enables a good means of identifying the end of the string as string variables usually store variable length values. Strings, unlike other arrays can be input without using a loop. When inputting strings using cin statement, the compiler stops taking input from the user once it encounters space or linefeed (pressing enter key). For example, consider the following program statements: char str[10]; cin>>str; If the user inputs HELLO and presses enter key , the contents for the str variable will be as follows: H str[0] E str[1] L str[2] L str [3] O str[4] /0 str[5]

The strings can be also initialised as arrays. However they can be initialized by enclosing the characters in the string constant with double quotes instead of initializing it character by character. For example, the following statement initializes the str variable to hello: char str[10]=hello; Strings can also be defined without specifying the size, but in that case they have to be initialized to a string constant as shown in the following example. char str[]=hello world However, there is no built in mechanism in C++ that disallows the user to enter characters than the string maximum size. The extra characters entered by the user will be truncated. To keep a check on the number of characters, setw() function can also be used. To use this function, iomanip.h header file should be included. #include<iostream.h> #include<iomanip.h> const int size=10; void main() { Char str[size]; Cout<<enter a string; Cin>>setw(size)>>str; } The above program allows user to enter only 9 characters(one character saved for null character).While inputting strings, cin stops reading once it encounters space or linefeed character( when user presses enter). To read blanks between the strings or to read multiple lines of text, get function which is a member function of cin can be used.The following statement will allow user to input a maximum of 39 characters which can even include blanks. It will stop reading once it encounters linefeed character. cin.get(str, 40); To read multiple line of text from the user, you have to specify a terminating character which will be used to recognize end of input. In the following example, the terminating character is $.

cin.get(str,40,$); The above example will allow users to enter a maximum of 39 characters which can include embedded blanks and linefeed. C++ has several string related library functions that are used to manipulate strings. Some of these are discussed below. To use these functions, header file string.h has to be included. Some of the library functions such as strlen, strcpy, strrev, strcmp is discussed below. Strlen Function Strlen function is used to find the length of the string. The syntax of the strlen function is strlen(string variable). The function returns the length of the string or the number of characters in the string which is a integer. Example : int len; char str[10]=hello; len=strlen(str); In the above example, the number of characters in the string str(five in this case) is stored in the integer variable named len Strrev function Strrev function arranges the characters in the string variable in reverse order except for the null character. The syntax of strrev function is strrev(string variable). It returns the reversed string. For example, in the following program statement, the output will be olleh The null character will be the last character of the string. char str[10]=hello; cout<<strrev(str); Strcpy function Strcpy function copies the contents of one string to another. The syntax of strcpy function is strcpy(destination string, source string). The function returns the destination string value after copying. For example, in the following program statement, the contents of the string str will be copied to string name char str[10]=ravi;

char name[10]; strcpy(name,str); The strcpy can also use string constants to be assigned to a string variable like in the following statement. strcpy(name,ravi); In the above statement the string constant ravi is assigned to the string variable name. The assignment of a string variable cannot be done using an assignment operator. It should be done using strcpy function. The following statement in a program will provide an compilation error: name=ravi; //wrong statement Strcmp function Strcmp function is used to compare two strings. The syntax of strcmp is strcmp(string1,string2). Every character of string1 will be compared with corresponding character of string2. The ASCII values of the character will be used to decide the return value. The function returns an integer and the value returned will differ based on the conditions as shown below: If string1 < string2, value returned will be <0 If string1==string2, value returned will be 0 If string1> string2, value returned will be greater than zero. Thus, a return value 0 implies that strings are equal and a non zero return value implies than the two strings are not equal. Please note that the above function is case sensitive. Strcmpi() function can be used if the two strings have to be compared without case sensitiveness. The following program implements strcmp function # include <iostream.h> # include<string.h> const char str[6] = XYZPQR void main() { char pass[6];

int flag=0; for(int i=0;i<3;i++) { cout<<Please enter your password; cin>>pass; if (strcmp(str, pass)==0) { cout<<Welcome; flag=1; break; } else cout<<Invalid password, try again<<endl; } } if (flag==0) cout<<Access denied; } Self Assessment Questions 1. char str[ ]; is a valid statement. True/False 2. char str[20] will allow maximum of ________ characters to stored in the string. 3. _________ member function of cin allows user to input embedded blanks and linefeed within the string. 4. _________ libray function can be used to copy the contents of one string to another string.

BC0037-3.5 Summary
Summary Arrays are used to store large volumes of similar data together. The array elements can be accessed by specifying array name followed by the number which indicates the position of the element in the array. Arrays of basic datatypes such as integers, characters etc and user defined datatypes such as structures, objects can be defined. Arrays can be multidimensional to store data that are related. Strings are character arrays that are handled slightly differently than other arrays. Every string has a null character \0 as its last character which marks the end of the string. There are several string related library functions that can be used to manipulate strings

BC0037-4.1 Introduction
Introduction This unit has the following objectives To understand what are functions and how they enable program organisation To understand different types of variables and their use in C++ To learn to what are structures and grouping data of different data types together

BC0037-4.2 Introduction to Functions


Introduction to Functions Functions provide an easy means to organize the programs into smaller modules and use them again without rewriting all the code. It enables reuse of program code. Functions enable programmers to group program code under one name and invoke them whenever required. We have been using several library functions till now without worrying about the code to implement them. Programmers can define their own functions in C++. In this unit, we will learn how to implement user defined functions. Every function has three components: return value, function name, and a set of arguments. Function name enables users to refer to the functions and is also used when user wants to call and execute the code defined in the function. Every function may or may not return a value. During declaration of function, the datatype of the return value should be specified. If there is no value returned it should be specified as void.The function main() which we had been using in all

the programs is one of the default functions which also has been defined as having no return value. When you have several user defined functions in a program, the statements in the main() function is executed first irrespective of where it is located in the program. Every function can have no or any number of arguments. Arguments are input to the functions and are used inside the function. During declaration of the function, the datatypes of the arguments should be specified. Each argument should be separated with a comma. The arguments should match during function call with respect to datatype and order of the arguments. In case of default arguments the value need not be specified during call. Every user-defined function should be declared in the program before it is used. The definition can be present in any part of the program. The following is an example of declaration of a function named square which inputs a number and returns the square of the number. int square(int); Please note that all the arguments are enclosed within brackets. If there are no arguments, void should be specified within the brackets. The following is the declaration of a function which does not have return value and does not have any arguments. void xyz(void); The functions can be invoked or called by referring to the function name followed by the variables or constants that has to be passed as arguments. If there are no arguments that has to be passed to the functions, then the function name should be followed by a pair of paranthesis. The following program would invoke the xyz function: xyz(); To invoke a square function which inputs a number and returns a number following statement can be used: s=square(n); Where s and n are integer variables. The function will compute square of n and the result will be stored in variable s. Please note that during function call, constants can also be passed. To understand the relevance of functions and its use, let us take an example. Let us suppose you would like to write a program that computes the combination of n items taken r at a time. The mathematical formula for computing nCr is n!/(r!*(n-r)!). In this problem, the factorial of the numbers have to be computed three times. The code for implementing factorial of a number has been discussed in the unit 2.3 in factorial.cpp program. If the same code has to be directly implemented without functions, the code has to be repeated three times in the program to compute factorial of n, r and n-r. This would not only make programs unnecessarily big but also difficult to correct or debug. To avoid this problem, we can define a user defined function named

fact which would input a number and compute the factorial of that number and return the result. The declaration for the function will be as below int fact(int); We can compute the factorial of n just by specifying fact(n) which would call the function fact and execute the statements. The complete program for implementing the above problem is as below: //function.cpp # include <iostream.h> int fact(int); // function declaration void main() { int n,r,ncr ; cout<< enter n; cin>>n; cout<< enter r ; cin>>r ; ncr=fact(n)/(fact(r)*fact(n-r)); cout<<NCR= <<ncr; } int fact(int number) //function definition { int f=1; for(int i=number;i>1;i) f=f*i; return f; //return computed value

} In the above program, the user inputs value for n and r. To compute the value of ncr, the fact function is invoked or called first by passing n variable. When the compiler encounters the first statement of the function, it copies the value of the variable n to the variable number. The variable number has scope only inside the function fact and is known as local variable. It cannot be accessed outside the function and so is the variable f and i that has been defined in the function. The factorial of the variable number (same value as n) is computed and then returned to the calling program through the return statement. The return statement is used to return values or results to the main program. This process is repeated for the values r and n-r as well. All the results are then used in the formula in the main program to compute the value of ncr. If the function does not have any return value, the return statement can be skipped. The control goes back to the main program once the last statement in the program is encountered. Alternatively, simply using the return statement without any variable would also imply that no value is being returned to the main program. Self Assessment questions 1. Functions enable to reuse code. True/False 2. void print() would return _______ value 3. ________ statement is used to return value to the main program. 4. Function call should always contain function name followed by paranthesis even if there are no arguments. True/False

BC0037-4.2 Introduction to Functions


Introduction to Functions Functions provide an easy means to organize the programs into smaller modules and use them again without rewriting all the code. It enables reuse of program code. Functions enable programmers to group program code under one name and invoke them whenever required. We have been using several library functions till now without worrying about the code to implement them. Programmers can define their own functions in C++. In this unit, we will learn how to implement user defined functions. Every function has three components: return value, function name, and a set of arguments. Function name enables users to refer to the functions and is also used when user wants to call and execute the code defined in the function. Every function may or may not return a value. During declaration of function, the datatype of the return value should be specified. If there is no value returned it should be specified as void.The function main() which we had been using in all the programs is one of the default functions which also has been defined as having no return

value. When you have several user defined functions in a program, the statements in the main() function is executed first irrespective of where it is located in the program. Every function can have no or any number of arguments. Arguments are input to the functions and are used inside the function. During declaration of the function, the datatypes of the arguments should be specified. Each argument should be separated with a comma. The arguments should match during function call with respect to datatype and order of the arguments. In case of default arguments the value need not be specified during call. Every user-defined function should be declared in the program before it is used. The definition can be present in any part of the program. The following is an example of declaration of a function named square which inputs a number and returns the square of the number. int square(int); Please note that all the arguments are enclosed within brackets. If there are no arguments, void should be specified within the brackets. The following is the declaration of a function which does not have return value and does not have any arguments. void xyz(void); The functions can be invoked or called by referring to the function name followed by the variables or constants that has to be passed as arguments. If there are no arguments that has to be passed to the functions, then the function name should be followed by a pair of paranthesis. The following program would invoke the xyz function: xyz(); To invoke a square function which inputs a number and returns a number following statement can be used: s=square(n); Where s and n are integer variables. The function will compute square of n and the result will be stored in variable s. Please note that during function call, constants can also be passed. To understand the relevance of functions and its use, let us take an example. Let us suppose you would like to write a program that computes the combination of n items taken r at a time. The mathematical formula for computing nCr is n!/(r!*(n-r)!). In this problem, the factorial of the numbers have to be computed three times. The code for implementing factorial of a number has been discussed in the unit 2.3 in factorial.cpp program. If the same code has to be directly implemented without functions, the code has to be repeated three times in the program to compute factorial of n, r and n-r. This would not only make programs unnecessarily big but also difficult to correct or debug. To avoid this problem, we can define a user defined function named fact which would input a number and compute the factorial of that number and return the result. The declaration for the function will be as below

int fact(int); We can compute the factorial of n just by specifying fact(n) which would call the function fact and execute the statements. The complete program for implementing the above problem is as below: //function.cpp # include <iostream.h> int fact(int); // function declaration void main() { int n,r,ncr ; cout<< enter n; cin>>n; cout<< enter r ; cin>>r ; ncr=fact(n)/(fact(r)*fact(n-r)); cout<<NCR= <<ncr; } int fact(int number) //function definition { int f=1; for(int i=number;i>1;i) f=f*i; return f; //return computed value }

In the above program, the user inputs value for n and r. To compute the value of ncr, the fact function is invoked or called first by passing n variable. When the compiler encounters the first statement of the function, it copies the value of the variable n to the variable number. The variable number has scope only inside the function fact and is known as local variable. It cannot be accessed outside the function and so is the variable f and i that has been defined in the function. The factorial of the variable number (same value as n) is computed and then returned to the calling program through the return statement. The return statement is used to return values or results to the main program. This process is repeated for the values r and n-r as well. All the results are then used in the formula in the main program to compute the value of ncr. If the function does not have any return value, the return statement can be skipped. The control goes back to the main program once the last statement in the program is encountered. Alternatively, simply using the return statement without any variable would also imply that no value is being returned to the main program. Self Assessment questions 1. Functions enable to reuse code. True/False 2. void print() would return _______ value 3. ________ statement is used to return value to the main program. 4. Function call should always contain function name followed by paranthesis even if there are no arguments. True/False

BC0037- 4.4 Scope and Visibility of variables in Functions


Scope and Visibility of variables in Functions Functions save memory as all the calls to the function cause the same code to be executed. However, with this there is overhead of execution time as there must be instructions for jump to the function, saving data in registers, pushing arguments to stack and removing them, restoring data, instructions for returning to the calling program and return values. To save execution time of functions, one of the feature in c++ is inline functions. An inline functions code is put with the code in the calling program for every function call. The inline function is written like any other function except that the function declaration begins with the keyword inline. This type of function is suitable for small functions which has to be repeatedly called. This enables the user to write programs using functions which would make programs look neat and less lengthy, at the same time the actual code is inserted in all the places where the function is called after compilation enabling faster execution of the program.

The several types of variables can be created in C++ which can be different in terms of life, visibility and the way it is initialized. These are also known as storage classes. We will discuss three types of storage classes in this section : Automatic, External and Static variables. Automatic variables is default variable in C++. All the variables we have created and used in programs are automatic variables. These variables can also be declared by prefixing the keyword auto. One of important characteristics of these variables are that they are created only when the function or program block in which they are declared are called. Once the execution of function or module execution is over, the variables are destroyed and the values are lost. The reason for limiting the lifetime of automatic variables is to save memory. When the variables are not be used by the function, they are removed from the memory. They can be accessed only within the function where they are declared. Beyond which they are not idenfiable. By default the automatic variables are not initialized to any specific values unless and until specified. They contain junk value depending on the value stored in the memory. Therefore it is necessary to initialize automatic variables to avoid problems in debugging. External variables are variables external to any function. Thus they can be accessed by multiple functions. This is the easiest way to share data among various functions. However too many external variables can create problems in debugging as the programmer will have tough time figuring out which function modified which data. Object oriented programming provides an alternative to use external variables. This feature is just to support backward compatibility with C. External variables are also known as global variables and are automatically initialized to zero. These variables are declared before main and declaration statement does not belong to any function. The following program shows the difference between an external variable and an automatic variable. //external.cpp # include<iostream.h> int x; void f1(); void f2(); void main() { x=x+2;

f1(); f2(); cout<<x; } void f1() { int x; x=x*2; } void f2() { x++; } In the above program, we have defined an external variable x. This variable will be automatically initialized to zero. The statement x=x+2; will store two in x. The function f1 will not have any impact on the value of the external variable as there is another local automatic variable x defined in the function which will be modified (Please note that when automatic and global variable have same name, the local variable will override the global variable). The function f2 will increment global variable by one. Thus the final output of the above program will be 3. External variables have a life of the file/program in which they are defined. Static variables are a mix of external and automatic variables. They have the scope of the function in which they are defined like automatic variables. But they can retain their values even after the function execution is over and are automatically initialized to zero like external variables. The following program shows the use of the static variables. // static.cpp # include <iostream.h> void main() {

int num; char ch; do { cout<<Enter a number; cin>>num; f1(num); cout<<Do u want to enter another number; cin>>ch; }while (ch==y') } void f1(int x) { static int sum, n; sum=sum+x; n=n+1; avg=sum/n; cout<< Average is<<avg; } The above program allows the user to enter any number of integers and computes the average of the numbers till then. The static variables sum and n are intitialised to zero. They are updated when user enters a new number and the function is called. The values of these variables are retained even after the function returns back to the main program. The summary of all three storage classes is shown below: Automatic Function Function Static Function Program External Program Program

Visibility Lifetime

Intialised to Purpose

Junk value in memory Variables used by single function

Zero Same as automatic but the value should be retained when function terminates

Zero Variables used by several functions

Self Assessment questions 1. Inline functions help in saving ______________ of programs 1. Static variables are initialized to _________ automatically. 2. External variables are accessible throughout the _________.

BC0037-4.5 Structures in C++


Structures in C++ We have seen in unit three how we can group data of same type together with arrays. Data that are of different types but are logically related can also be grouped together. This can be done through structures. Structures are a group of dissimilar data that are related with each other. For example, if you want to store all the details of an employee such as employee id (integer), name (string), department code(integer), and salary as one entity, you can do this using structure as shown below: struct employee { int empid; char name[35]; int deptcode; float salary; }; Structure is a feature in C++ that enables you to define a user-defined datatype. Once you specify the definition of the structure, you can create variables of that structure. In the above definition, we have defined a structure using the keyword struct followed by the name of the structure (employee). All the data items that needs to be defined are defined by specifying the datatype and name of the variable. Once the definition is done, variables of type employee can be created. For example, the following statement creates a variable e1 of type employee. employee e1;

Structure variables can be initialized during declaration. The values for all the members should be specified separated by comma and all the values enclosed within flower brackets as shown below employee e1= {1234, Ajay, 12, 6900.00}; Structure variables can be copied and assigned to another structure variable as shown below employee e2; e2=e1; To access the members of the structure variables, dot operators can be used. For example to access empid of structure variable e1, you would say e1.empid (structure variable. membervariable name). Structures can be nested within each other. When accessing the members and submembers dot operators can be used. Let us suppose you have defined a structure named distance with two members length and width as declared below: struct distance { int feet; int inches; } Let us define now a structure named room which contains variables of type distance struct room { distance length; distance width; distance height; } bedroom; In the above definition, we have declared a variable bedroom of type room along with the definition. To access the members of the bedroom we can use bedroom.length.feet

bedroom.length.inches bedroom.width.feet bedroom.width.inches and so on To initialize nested structures you have to group together all the elements of the structure room dining = {{12, 3},{13,0},{11,2}} In the above declaration, the values 12 and 3 refer to dining.length.feet and dining.length.inches repectively. Similarly the second and third set of values represent feet and inches of width and height respectively. Array of structures can be created. The index number should be specified immediately after the structure variable. For example, the statement employee emp[50] ; will create a array of structure employee. To access the first array member, you can say emp[0].empid The following program implements a structure point with x and y co-ordinates. #include<iostream.h> #include<conio.h> # include<math.h> struct point { int x,y; } p1,p2; void main() { int s; cout<< Enter the co-ordinates for first co-ordinate ; cin>> p1.x>>p1.y;

cout<<enter the co-ordinates for second co-ordinate; cin>>p2.x>>p2.y; s=sqrt(((p2.y-p1.y)*(p2.y-p1.y))+((p2.x-p1.x)*(p2.x-p1.x))) ; cout<<endl<<the distance between the two points is<<s; getch(); } In the above program we have defined a structure point which stores x and y co-ordinates of the point. Along with the declaration we have also created two point variables p1 and p2. This is a way to create variables along with the structure decalaration. This can be a separate statement also as discussed earlier. The program accepts two points from the user and displays the distance between them. Structures are good mechanism of creating userdefined datatypes. C++ specifies another method known as enumerated data type to enable users create their own datatypes. Enumerated data types can store fixed set of values and you can perform arithmetic on them as well. They are defined using the keyword enum. The following program creates an enumerated datatype which stores different days of the week. //enumerated.cpp #include <iostream.h> enum weekday {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; void main ( ) { weekday day1,day2; day1=Mon; day2= Fri; int diff=day2-day1; cout<<days between =<<diff; if (day1<day2) cout<<day1 comes before day2;

} In the above program enumerated datatype weekday is created. The first value (Sun) is assigned zero by default and so on. The variables day1 and day2 can be assigned only the values specified in the datatype declaration or their integer equivalent. They cannot be assigned any other value. Self Assessment Questions 1. Structures group data of similar type. True/False 2. ___________ keyword is used to create structures. 3. Member data of the structure are accessed by ________ operator

BC0037-4.6 Summary
Summary Functions provide good mechanism to organize data. Functions are given a name which can be used to call the function and execute the statements in the functions. Functions can also take input which are known as arguments which passed during function call. Arguments can be passed either by value or by reference. They can also have return value which can return an computed value back to the main program. Inline functions enable programmers to save processing time by reducing the overheads involved in function call. Programs can make use of automatic, external and static variables which have different types of utility depending on the way the variable should be accessed and whether the value has to be retained. Structures and enumerated data types enable to users to create user defined datatypes. Structure group data items that have different datatypes. Enumerated datatypes create datatypes that can store pre-defined and fixed set of values

BC0037-5.1 Introduction
Introduction This unit has the following objectives To understand what are classes and Objects and learn to implement them To learn to use constructors and destructors in a class To understand static variables and functions with respect to a class

BC0037-5.2 Creating classes and objects


Creating classes and objects In the unit 1, we had a brief discussion of objects and classes. In this section, we will see how we can implement them. Classes provide users a method to create user defined datatypes. We have seen two types of user defined datatypes structures and enumeration in the last unit. Both are primarily used for modeling data only. In several real life situation, you would require to model functionality of the datatype along with the data. Classes enable you to bind data and functions that operate on data together. However, in C++ you can use structures same as classes by binding functions with data. But usually the structures are only used when you want to group data and classes when you want to group both data and functions. Classes can model either physical or real things such as employee, product, customer etc or it can model a new datatype such user defined string, distance, etc. Objects has the same relationship to a class that a variable has to a datatype. Object is an instance of a class. Class is a definition, objects are used in the program that enables you to store data and use them. To understand the various syntactical requirements for implementing a class, let us take an example. // distance.cpp #include<iostream.h> class distance { private: int feet; int inches; public: void setdistance(int a, int b) { feet=a; inches=b; }

void display() { cout<<feet<<ft<<inches<<inches;} }; void main() { distance d1; d1. setdistance(10, 2); d1.display(); } In the above program, we have created a class called distance with two data members feet and inches and two functions or methods setdistance and display (). Classes are defined with the keyword class followed by the name of the class. The object of this class is d1. Every objects of a class have their own copy of data, but all the objects of a class share the functions. No separate copy of the methods is created for each and every object. Objects can access the data through the methods. To invloke a method, objectname.methodname is used. The methods defined in the class can only be invoked by the objects of the class. Without an object, methods of the function cannot be invoked. You can see in the above program, the data elements feet and inches are defined as private. The methods are defined as public. These are known as access specifiers. Data and functions in a class can have any one access specifiers: private, public and protected. Protected access specifier we will discuss later in unit 7 along with inheritance. Private data and functions can be accessed only by the member functions of the class. None of the external functions can access the private data and member functions. Public data and member functions can be accessed through the objects of the class externally from any function. However to access these data and functions, you need to have an object of that class. This feature of object oriented programming is sometimes referred to as data hiding. The data is hidden from accidently getting modified by an unknown function. Only a fixed set of functions can access the data. In a class, the data and functions are private by default so private keyword can be omitted.

Fig. 5.1: Access specifiers in a class

Certain object oriented programming languages refer to methods as messages. Thus d1.display() is a message to d1 to display itself Usually, data are declared as private and functions as public. However, in certain case you may even declare private functions and public data. Please note that the class definition has a semicolon in the end. Array of objects can also be created. It is similar to array of structures. distance d[10]; creates a array of objects of type distance. If the first distance object accesses the member function display you can use d[0].display() Let us see how we can perform operations on the objects data. We will see a program which implements an add member function to the distance class. We can do this in two ways. The prototypes of the function is shown below: void add(distance, distance); or distance add(distance); The first function takes two distance objects as arguments and stores the result in the object invoking the member function. It can be implemented as follows: //adddist1.cpp #include<iostream.h> class distance { private: int feet; int inches; public: void setdistance(int a, int b) { feet=a; inches=b;

} void display() { cout<<feet<<ft<<inches<<inches;} void add(distance dist1, dist2) { feet=dist1.feet+dist2.feet; inches=dist1.inches+dist2.inches; if (inches>12) { feet++; inches=inches-12; } } }; void main() { distance d1,d2,d3; d1. setdistance(10, 2); d2.setdistance(2,4); d3.add(d1,d2); d3.display(); } In the above program, object d3 invokes the add function so the feet and inches refers the invoking objects data members. After adding the respective data of d1 and d2 it is stored in d3 object. Alternatively, the above program can be implemented in a different way as shown below //adddist2.cpp

#include<iostream.h> class distance { private: int feet; int inches; public: void setdistance(int a, int b) { feet=a; inches=b; } void display() { cout<<feet<<ft<<inches<<inches;} distance add(distance dist) { distance temp; temp.feet=dist.feet+feet; temp.inches=dist.inches+inches; if (temp.inches>12) { temp.feet++; temp.inches=temp.inches-12; } return temp; } };

void main() { distance d1,d2,d3; d1. setdistance(10, 2); d2.setdistance(2,4); d3 =d1.add(d2); d3.display(); } In the above program, we have implemented the add function which is invoked by d1 object and d2 is passed as an argument. Since the calling objects data are passed automatically, d1 objects data members can be accessed in the function. They are referred directly as feet and inches without the objectname (as it is implicit in the member function). The add function stores the summed value in a temporary variable and then returns it to the calling program. Self Assessment Questions 1. Private data members can be accessed only by the __________ of the class 2. Public data members can be accessed directly in the main function without an object. True/False 3. Every object of a class has its own copy of the data and functions. True/False

BC0037-5.3 Constructors and Destructors


Constructors and Destructors Constructors and destructors are very important components of a class. Constructors are member functions of a class which have same name as the class name. Constructors are called automatically whenever an object of the class is created. This feature makes it very useful to initialize the class data members whenever a new object is created. It also can perform any other function that needs to be performed for all the objects of the class without explicitly specifying it. Destructors on the other hand are also member functions with the same name as class but are prefixed with tilde (~) sign to differentiate it from the constructor. They are invoked automatically whenever the objects life expires or it is destroyed. It can be used to return the memory back to the operating system if the memory was dynamically allocated. We will see dynamic allocation of memory in Unit 7 while discussing pointers.

The following program implements the constructor and destructors for a class // constdest.cpp # include<iostream.h> class sample { private: int data; public: sample() {data=0; cout<<Constructor invoked<<endl;} ~sample() {cout<<Destructor invoked;} void display() { cout<<Data=<<data<<endl;} }; void main() { sample obj1; obj.display(); } If you run the above program you will get the output as follows: Constructor invoked Data=0 Destructor invoked When object of sample class, obj is created, automatically the constructor is invoked and data is initialized to zero. When the program ends the object is destroyed which invokes the destructor. Please note that both the constructor and destructor is declared as public and they have no return value. However, constructors can have arguments and can be overloaded so that different constructors can be called depending upon the arguments that is passed. Destructors on the other

hand cannot be overloaded and cannot have any arguments. The following program implements the overloaded constructors for the distance class. //overloadconst.cpp #include<iostream.h> class distance { private: int feet; int inches; public: distance() { feet=0; inches=0;} distance(int f, int i) { feet=f; inches=i;} void display() { cout<<feet<<ft<<inches<<inches;} }; void main() { distance d1, d2(10,2); d1.display(); d2.display() }

In the above program, the setdistance function is replaced with the two constructors. These are automatically invoked. When object d1 is created the first constructor distance() is invoked. When object d2 is created the second constructor distance (int f, int i) is invoked as two arguments are passed. Please note that to invoke a constructor with arguments, argument values have to be passed along with the object name during declaration. Self Assessment Questions 1. Constructors are member functions of the class which is invoked when ________ is created. 2. Destructors have same name as a class but are prefixed with ________ sign 3. Destructors can be overloaded. True/False 4. Constructors can be overloaded. True/False

BC0037-5.4 Static variables and Functions in class


Static variables and Functions in class We have seen that when an object is created, a separate copy of data members is created for each and every object. But static data member in a class is an exception. Static data member of the class is one data member that is common for all the objects of the class and are accessible for the class. It is useful to store information like count of number of objects created for a particular class or any other common data about the class. Static data member is declared by prefixing the keyword static. We have learnt that to invoke a member function of a class, you need to have object. Suppose we have a static data member which keeps track of the total objects created and there is a showtotal function which displays the total value. We will not be able to know the total if there are no objects which is a serious limitation. Static functions are the solution for this. Static functions are special type of functions which can be invoked even without an object of the class. Static functions are also defined by prefixing the keyword static. It is called using classname followed by scope resolution operator and function name. The following program implements the static data and functions //classstatic.cpp # include <iostream.h> class A { static int total;

int id; public: A() { total++; id=total; } ~A() { total; cout<<\n destroying ID number=<<id; } static void showtotal() {cout<<endl <<total;} void showid() {cout<<endl <<id;} }; int A::total=0; void main() { A::showtotal(); A a1,a2; A::showtotal(); a1.showid(); a2.showid();

} The output of the above program 0 2 1 2 In the above program total is an static variable which is shared by all objects of the class A. The static variables of the class have to be explicitly initialised outside the class using the class name followed by scope resolution operator (::) and static variable name. Please note that you have to specify the datatype but need not specify the keyword static during initialization. The variable total is incremented in the constructor which will increment the total whenever a new object is created. Similarly, it is decremented through the destructor when the object is destroyed. The function showtotal is a static function which is invoked without the object and using the classname. The fig 5.2 summarises member functions and data of a class

Fig. 5.2: Data and Functions in a class Self Assessment Questions 1. Static data member of a class can be modified by all objects of the class. True/False 2. Static functions are accessed using __________ 3. Static data need not be initialized. True/False

BC0037-5.5-Summary

Summary Class enable user to create user-defined datatypes and define their functionality. Objects are instances of classes. Class can contain both data and functions. Class data can be initialized using constructors which are invoked when the objects of a class are created. Destructors are member functions which are invoked when the objects are destroyed. Member functions can be accessed only through the objects of the class. Static functions can be accessed without objects. Static data can be accessed by all the objects of the class and only one copy of this data is maintained.

BC0037-6.1 Introduction
Introduction This unit has the following objectives To learn how C++ supports operator overloading To learn to overload different types of unary and binary operators To understand limitations of operator overloading

BC0037-6.2 Operator Overloading in C++


Operator Overloading in C++ Operator overloading is an interesting feature of C++ that allows programmers to specify how various arithmetic, relational and many other operators work with user defined datatypes or classes. It provides a flexible way to work with classes and can make program code look obvious. In the unit 5, we had written an add function for the class distance. To perform addition of two distance objects we used a call d3.add(d1,d2). Instead of such statements it would be more clear if we could use statements like d3=d1+d2. This is possible only if we inform compiler about how + operator works with distance class. This is exactly what operator overloading feature in C++ does. It helps to use the default operators with the user defined objects for making the code simpler. However there are several problems with operator overloading which you should be aware of. When using operator overloading, the operator should perform only the most obvious function. Otherwise it will lead to more confusion. If you are overloading + operator for distance class it should add two distance objects, and should not do something else. However some syntactical characteristics of operators cannot be changed even if you want to. For example, you cannot overload a binary operator to be a unary operator and vice versa. Several operators such as dot operator, scope resolution (::) operator, conditional operator (?:) etc cannot be overloaded.

Therefore operator overloading should be used for a class where it is required to perform obvious functions with the default operators and there can be no other meaning for the same. Self Assessment Questions 1. Operator overloading feature helps to change the functionality of operators with any datatype. True/False 2. You can overload all operators in C++. True/False 3. It is necessary to overload operators for all classes. True/False

BC0037-6.3 Overloading Unary Operators


Overloading Unary Operators We have seen that unary operators are those operators which work on one operator. Some of the unary operators are ++, , and minus (-). Operator overloading works similar to any member function of a class. But it is not invoked using dot operator. Just like member function the operator has a return value and takes arguments. It is invoked by the operand which uses it. In case of overloading of unary operators, the calling operand can be either left or right of the operator like in case of increment and decrement operators. While defining the operator functionality for the class the keyword operator is used. Let us overload the increment operator for a class. //unary.cpp # include <iostream.h> class counter { unsigned int count; public: counter() {count=0;} int getcount() {return count;} void operator ++()

{ count++;} }; void main() { counter c1; c1++; ++c1; cout<<c1.getcount(); } In the above example, the operator ++ is defined to return void and take no arguments. All unary operators do not take no arguments as it operates on only one operand and that operand itself invokes the operator. Therefore the operand is sent by default. However the above implementation cannot be used in statements such as c2=c1++; where c1 and c2 are counter variables. This is because the operator ++ returns void which makes an counter variable being assigned void value. To overcome this, you can make the operator return an counter variable as shown below //incremnt.cpp # include <iostream.h> class counter { unsigned int count; public: counter() {count=0;} counter(int c) {count=c;} int getcount() {return count;}

counter operator ++() { count++; return counter(count);} }; void main() { counter c1,c2; c1++; c2=++c1; cout<<c1.getcount()<<endl; cout<<c2.getcount(); } In the above implementation, we are returning the counter variable without creating a variable. This is enabled by including constructor with one argument. When return counter(count) is specified, value stored in the variable count of the invoking object is passed to the constructor and a nameless object is created which is initialized to the value stored in the count and returned to the calling program. One argument constructor is used in this case. Unary operators like increment and decrement operators cannot be completely duplicated. As the compiler cannot differentiate between post and pre increment/decrement operators. This one of the limitation of overloading unary operators. Self Assessment Questions 1. Unary operators are implemented with _____ arguments. 2. Unary operators should have return value as ________. 3. Unary operators overloaded for the class can differentiate between post and pre operators. True/False

BC0037-6.4 Overloading binary operators


Overloading binary operators

Binary operators are those that work on two operands. Arithmetic operators like + , * etc and relational operators like <, > etc are some examples of binary operators. Overloading binary operators is different from overloading unary operators mainly in terms of the way it is invoked and arguments passed. When you overload a binary operator, the operand to the left of the operator calls the operator and the operand to the right of the operator is passed as an argument. The following example shows the overloaded + operator for the class distance. # include<iostream.h> class distance { private: int feet, inches; public: distance() {feet=0; inches=0;} distance(int f) {feet=f; inches=0;} distance(int f, int i) {feet=f;inches=i;} void display() {cout<<feet << <<inches<<endl;} distance operator + (distance d1) { int f = feet+d1.feet; int i = inches+d1.inches; return distance(f,i);} }; void main()

{ distance d1(2,5), d2(1,4),d3, d4; d3=d1+d2; d3.display(); d4=d3+2; d4.display(); } In the above program, the operator + is overloaded. The declaration shows that a distance object is passed as an argument and an distance object is returned. In the main program, the statement d3=d1+d2 invokes the + operator where d1,d2,d3 are distance objects. The object d1 calls the + operator (left operand) and d2 is passed as an argument (right operand) and after the two objects are added they are returned to the main program which is stored in the d3 object. In the second statement, d4=d3+2, d3 invokes the + operator and 2 is passed as an argument. The one argument constructor is invoked to convert 2 (integer datatype) into distance object. However the above implementation has a limitation. The compiler will not understand how to handle statements like d2=10+d1 where the left operand which calls the operand is not a distance object. This can be however handled through a concept known as friend functions. By declaring the operator + as a friend you can accomplish it to handle multiple datatypes. Friend functions are external functions that can access the private data members of a class. However, the class definition should declare the function as a friend. They can act as a bridge between two classes or in other words they can be used when a single function has to operate on multiple datatypes. A function is made friend by just prefixing the keyword friend in the function declaration within the class definition. # include<iostream.h> class distance { private: int feet, inches; public: distance() {feet=0; inches=0;}

distance(int f) {feet=f; inches=0;} distance(int f, int i) {feet=f;inches=i;} void display() {cout<<feet << <<inches<<endl;} friend distance operator + (distance, distance); }; distance operator + (distance d1, distance d2) { int f = d1.feet+d2.feet; int i = d1.inches+d2.inches; return distance(f,i);} void main() { distance d1(2,5), d2; d2=10+d1; d2.display(); } Let us see another type of binary operator < and learn how relational operators can be overloaded. In case of relational operators also there can be one argument overloading or two argument overloading (using friend functions). However, the return value should be integer (0 or 1) indicating true or false or some compilers support to create boolean datatypes. The following program implements the program for < relational operator overloading for the distance class. # include<iostream.h>

class distance { private: int feet, inches; public: distance() {feet=0; inches=0;} distance(int f) {feet=f; inches=0;} distance(int f, int i) {feet=f;inches=i;} void display(); void getdata(); int operator < (distance d1) { if (feet<d1.feet) return 1; else if (feet==d1.feet) && (inches<d1.inches) return 1; else return 0; } }; void distance :: display() {cout<<feet << <<inches<<endl;}

void distance :: getdata() { cout<<Enter distance in feet and inches; cin>>feet >>inches;} void main() { distance d1,d2; d1.getdata(); d2.getdata(); if (d1<d2) cout<<d1.display() << is smaller; else cout<<d2.display()<< is smaller; } In the above program the d1 object invokes the operator < and d2 is passed as an argument. The return value is either 0 or 1 which indicates false or true respectively. Certain compilers support boolean datatype which can be alternatively used instead of integer. The above program also implements display and getdata member functions differently. The member functions are declared inside the class but are defined outside the class. But to specify that the member function belongs to the distance class, the class name is included along with the function name separated by the scope resolution operator (::). Self Assessment Questions 1. Member functions of a class can be defined outside the class using ________ operator along with the class name. 2. _________ functions are external functions that can access private data members of a class. 3. Overloaded relational binary operators should return _________ 4. Left operand calls the operator in case of binary operator. True/False.

BC0037-6.5 Summary
Summary Operator overloading allows to define new meaning for normal C++ operators and specifies how it can be used with the user defined classes. Overloading should be used only to imply default meanings to avoid confusion in its usage. Not all operators can be overloaded.

BC0037-8.1 Introduction
8.1 Introduction This unit has the following objectives To understand how to implement multiple inheritance To understand the complexities that might arise in multiple inheritance To learn the concept of virtual functions and polymorphism

BC0037-8.2 Introduction to Multiple Inheritance


Introduction to Multiple Inheritance We have learnt in the last unit the concept of inheritance. We will explore in detail the concept of multiple inheritance and the ambiguities that might arise in multiple inheritance. Multiple Inheritance is the process of inheriting a class from more than one parent class. This would be required in several instances where you would like to have the functionalities of several classes . This is also extensively used in class libraries. The syntax for implementing multiple inheritance is similar to single inheritance. Let us suppose, there are two classes A and B, you want to derive a class C from A and B. The syntax of class definition will be as follows: class C : public A, public B { };

Let us implement a program where there are two classes namely student and employee. We will derive a class manager from the above two classes and see how member functions and constructors are implemented in multiple inheritance. //multiple.cpp # include<iostream.h> # include<string.h> # include<conio.h> class student { protected: char qual[6]; // highest degree earned int percent; // percentage score in the last degree public: student() { strcpy(qual, ); percent=0;} student(char ch[6], int p) { strcpy(qual, ch); percent=p;} void display() { cout<<endl<<Qualification<<qual; cout<<endl<<Score<<percent; }} ; class employee { protected: int empno; char ename[25];

public: employee() { empno=0; strcpy(ename,"); } employee(int n, char ch[25]) { empno=n; strcpy(ename,ch); } void display() {cout<<endl <<Emp Code:<<empno; cout<<endl <<Name:<<ename; } }; class manager: public employee, public student { protected: float basic; float hra; public: manager():employee(),student() { basic=0.0; hra=0.0;} manager(int n,char ch[25], char ch1[6], int p, float i, float j): employee(n,ch), student(ch1,p)

{ basic=i; hra=j;} void display() { employee::display(); student::display(); cout<<endl <<Basic<<basic; cout<<endl <<HRA<<hra; } }; void main() { clrscr(); manager m1(205, pawan, MBA, 80, 40000.00, 5000.00); m1.display(); getch(); } You can see in the above program, that the derived class constructors calls both the parent class constructors. This is because every object of the derived class has its own copy of parent data members. Therefore it is required to initialize them as well. The parent class member functions are invoked using the scope resolution operator as shown in the display function of the manager class. The output of the above program will be Emp Code:205 Name:pawan Qualification MBA Score 80

Basic 40000 HRA 5000 Even though implementation of multiple inheritance is simple, there are several type of ambiguities that might arise in its implementation. Let us suppose there are two parent classes A and B. Class C has been derived from A and B. There is a function f1() defined in both the parent classes but f1() has not been defined in the child class. When the child class object (objc) tries to access the function f1() through a statement objc.f1(), there is compiler error. This is because the statement is ambiguous because the compiler will not be able to figure out which parents f1() function have to be called. The ambiguity can be resolved by prefixing the parent class name followed by scope resolution operator before the function name. The following statement would resolve the ambiguity objc.A::f1(); The above statement implies that use the function f1() of class A. Another solution would be to introduce a dummy function f1() in Class C and invoke the parent functions whichever applicable. Another common ambiguity raised is in the case of diamond inheritance. Diamond inheritance is a situation as shown in the following diagram arises when both the parent classes have been derived from a single parent class.

Fig. 8.1: Diamond Inheritance

Imagine the above situation where there is a parent class A with a protected data member a. Two child classes B and C are derived publicly from A. Class D is derived both from B and C publicly. The compiler complains when the grandchild class D tries to access the member a of the parent class A. This ambiguity arises because when classes B and C are derived from A, each inherits a copy of A called subobject and contains own copy of parent data. The ambiguity arises for the grandchild in resolving which copy of the child class subobject to be accessed.

The solution for this is virtual base class. By making classes B and C as virtual classes, the two classes will share a common subobject and will result in resolving the ambiguity as shown below. class A {protected: int a;}; class B : virtual public A {} class C: virtual public A {} class D : public B, public C { public: int f1() return a; //only one copy of the parent } Self Assessment questions 1. In case of multiple inheritance, the child class has a copy of data of all the parent classes. True/False 2. The problem of diamond inheritance ambiguity is resolved by declaring the child classes as ____________ 3. In multiple inheritance if the both the parent class (A and B) have same function and child class (C) does not have that function, then the which function is called a. Class A b. Class B c. Have to be specified explicitly d. No function will be called

BC0037-8.3 Introduction to Virtual Functions


Introduction to Virtual Functions Virtual means existing in effect but not in reality. Virtual functions are primarily used in inheritance. Let us suppose you have a class base as shown in the following program and two classes derv1 and derv2 are publicly derived from class base. You would like to create a pointer that points to any of the derived class objects. If you create a pointer of derv1, then it can point to derv1 object only. Compiler will complain if you assign any other object is assigned to the pointer. The solution is to create a pointer to Base class. // objectptr.cpp # include <iostream.h> class base { public: void show() {cout<<base<<endl;}}; class derv1:public base { public: void show() {cout<<derv1<<endl;}}; class derv2: public base { public: void show() {cout<<derv2<<endl;}}; void main() {

derv1 dv1; derv2 dv2; base *ptr; ptr=&dv1; ptr->show(); ptr=&dv2; ptr->show(); } The output of the above program will be surprisingly: base base Even though the address of derived classes is assigned to the pointer, the compiler executes the base class function. However, if the base class function is made virtual, we get the desired result. In the following program we have made the base class function show() as virtual function by prefixing with the keyword virtual. //virtual.cpp # include <iostream.h> class base { public: virtual void show() // virtual function {cout<<base<<endl;}}; class derv1:public base { public: void show() {cout<<derv1<<endl;}};

class derv2: public base { public: void show() {cout<<derv2<<endl;}}; void main() { derv1 dv1; derv2 dv2; base *ptr; ptr=&dv1; ptr->show(); ptr=&dv2; ptr->show(); } By declaring the base class function as virtual, we now get the output as: derv1 derv2 In the above program, depending on the contents in the pointer, the compiler decides which class function to call during runtime. This is known as late binding or dynamic binding. Virtual functions are for just name sake and will not be executed many a times. If the virtual function has no specific role in the base but just declared for enabling the derived class objects access through pointers, the function can be declared as a pure virtual function. A pure virtual function is one which does not have any body. Virtual functions declared by equating it to zero as shown below: virtual void show()=0;

In inheritance, many a times you would create a class just for grouping data or functionality but the class do not have any instances of its own. Such classes which does not have any objects are known as abstract classes. For example, there is a class known as employee and there are many classes derived from this class such as manager, worker etc. In the program, the employee class brings together the common data and functions to all the subclasses and to avoid coding same functionality in each and every class. Here employee class is the abstract class. Self Assessment questions 1. Base class functions which does not have any body is known as _______ 2. The process of deciding which class function to be called during runtime is known as _______________________ 3. The classes which do not have any objects are known as ___________

BC0037-8.4 Introduction to Polymorphism


8.4 Introduction to Polymorphism Virtual functions in C++ are important to implement the concept of polymorphism. Polymorphism means same content but different forms. In C++, polymorphism enables the same program code calling different functions of different classes. Imagine a situation where you would like to create a class shape and derive classes such as rectangle, circle, triangle etc. Let us suppose each of the classes has a member function draw() that causes the object to be drawn on the screen. You would like to write a common code as following so that you can draw several of these shapes with same code and the shape to be drawn is decided during runtime: Shape *ptrarr[100] for (int j=0;j<n;j++) Ptrarr[j]->draw(); This is an very desirable capability that completely different functions are executed by same function call. If the ptrarr is pointing to a rectangle, a rectangle is drawn. If it is pointint to circle, circle is drawn. This is exactly what is polymorphism. However to implement this approach several conditions should be met. Firstly, all the classes rectangle, circle, triangle should be derived from a single class (Here it is shape class). Secondly, the draw() function must be declared as virtual in the base class (in the shape class). Operator overloading is, a type of polymorphism which allows the same operators to behave differently with different datatypes/operands.

Self Assessment questions 1. A pointer to a base class can point to the objects of a derived class. True/False 2. If there is a pointer p, to the objects of a base class and it contains the address of an object of a derived class, and both classes contain a virtual member function, ding(), then the statement p>ding(); will cause the version of ding() in the ________________ class to be executed 3. Polymorphism in C++ is implemented through ________________.

BC0037-8.5 Summary
Summary Inheritance has to be implemented with care especially when it is multiple inheritance. Multiple inheritance creates ambiguity in situation where the derived class does not implement the function implemented in both the parent class and also in case of diamond inheritance. Virtual base class helps in resolving the ambiguity. Virtual functions in base class helps to implement polymorphism in C++. Abstract classes are classes without any objects.

BC0037-9.1 Introduction
9.1 Introduction This unit has the following objectives To understand how file input output is handled in C++ To learn how to pass arguments during runtime To learn how to handle output to printer

BC0037-9.2 Introduction to files and streams in C++


Introduction to files and streams in C++ File input and output in C++ is handled completely by predefined file and stream related classes. The cin and cout statements which we were using for input from keyboard and output to display screen are also predefined objects of these predefined stream classes.

The header file iostream.h is a header file containing the declarations of these classes which we have been using in all our programs. Similarly other header file fstream.h contains declarations for classes used for disk file I/O. Let us first understand what is a stream. Streams are name given for flow of data. They are logical abstraction between user and the external device.Each stream is associated and represented through a class in C++. All streams behave in the same way even though they are connected to different devices. This capability allows same functions to be used even though devices are different. The member functions in stream classes contains definitions and procedures for handling a particular kind of data. For example ifstream class is defined for handling input from disk files. So the files in C++ are objects of a particular stream class. The stream classes are organized in a beautiful hierarchy which is slightly complex. But overview of how they are organized will provide an excellent example of inheritance and help understand files and streams in a better way. The following figure shows a portion of stream class hierarchy in C++ which we will be using in our programs in this unit

Fig. 9.1: Stream Classes in C++ As shown in the fig. 9.1 all stream classes have been inherited from the base class ios. It contains many constants and member functions common to all kind of input and output. The class istream is derived from ios class which contains all the necessary functions for handling input. Some of the functions such as get(), getline(), read and overloaded extraction (>>) operators are defined in istream class. While ostream class which is also derived from ios class is dedicated for output related functions of all kinds and contains functions such as put() and write and overloaded insertion operator (<<). The class iostream is inherited from both istream and ostream through multiple inheritance so that other classes can inherit both the functionalities of input and output from it. Three classes istream_withassign, ostream_withassign, iostream_withassign are inherited from istream, ostream, iostream respectively which adds assignment operators to these classes.Cout is an

predefined object of the class ostream_withassign class. Cin is an object of the class istream_withassign class. The class ifstream which is inherited from both istream and fstreambase is used for input files. Similarly, class ofstream which is inherited from both ostream and fstreambase is used for output files. The class fstream inherited from both iostream and fstreambase is used for files that will perform both input and output. All the three classes for file input and output ie fstream, ifstream and ofstream are declared in the header file fstream.h. The file fstream.h also includes iostream.h, so the programs using fstream.h need not explicitly include iostream.h. Self Assessment questions 1. cin is a predefined object of _____________ class 2. ___________ header file has to be included for file input and output. 3. cout is a predefined object of ____________ class.

BC0037-9.3 Character and String input and output to files


Character and String input and output to files Let us see some programs that writes and reads characters and strings to text file. To write any data to a file, you should create an object of ofstream class. The function put() is used with the object to write to the file. It however writes one character at a time. The syntax of put() function is : objectname.put(character variable). The following program shows the use of put() function: #include<fstream.h> # include<string.h> void main() { ofstream outfile(test.txt); char str[ ]=hello world;

for (int j=0;j<strlen(str);j++) outfile.put(str[j]); } In the above program we have created an ofstream object named outfile. The constructor of the class is invoked and a text file named test.txt is assigned to the object outfile. A text file is created in the output directory specified in your compiler and if there is already an text file with the same name, then it is overwritten. The contents of the string str is written to the file test.txt. Please note that we have include fstream.h header file. Since the insertion operator (<<) is overloaded in the class ostream class (ofstream is derived from ostream), it can be used along with the ofstream object to write text directly to the file. The following program shows that #include<fstream.h> void main() { ofstream outfile(test.txt); outfile<<This is my first file\n; outfile<<Bye\n; } To read data from any file, you should create an object of ifstream class. The function get() and getline() is used with the object to read the file. The function get() reads one character at a time. The syntax of get() function is : objectname.get(character variable) where object is an object of the ifstream class and the character read is stored in the variable. The following program reads the contents of a text file character by character and prints on the screen. #include<fstream.h> #include <conio.h> void main()

{ ifstream infile(test.txt); char ch; clrscr(); while (infile) // infile becomes 0 when eof condition is reached {infile.get(ch); cout << ch;} getch();} In the above program, we have checked the end of file condition using the objectname itself which becomes zero when end of file is reached. Alternatively, eof() member function is used to check end of file condition. It returns non zero value when end of file is reached and returns zero while it is reading the file. The getline() function reads line by line as shown in the following program #include<fstream.h> #include <conio.h> void main() { ifstream infile(test.txt); char buffer[80]; clrscr(); while (!infile.eof()) //returns nonzero value when eof condition is reached {infile.getline(buffer,80); cout << buffer;} getch();}

Since the extraction operator (>>) is overloaded in the class istream class (ifstream is derived from istream), it can be used along with the ifstream object to read text. However it reads one word at a time. The following program shows that #include<fstream.h> #include <conio.h> void main() { ifstream infile(test.txt); char buffer[25]; clrscr(); while (infile) //infile becomes 0 when eof condition is reached {infile>>buffer; cout << buffer;} getch();} While reading files, we have assumed that the files have already been existing on the disk. However it would be wise to include checks that report in case the file you intend to read is not found on the disk. The ios class contains many such status checks. The above program has been rewritten with error check while opening the file. #include<fstream.h> #include <conio.h> void main() { ifstream infile(test.txt); if (!infile) // check for error while opening the file cout<<Cannot open file; else

{ char buffer[25]; clrscr(); while (infile) //infile becomes 0 when eof condition is reached {infile>>buffer; cout << buffer;} } getch();} Self Assessment questions 1. __________ is class object is used to read data from disk files 2. ________ class object is used to write date into disk files 3. __________ functions reads data from files line by line 4. _________ function writes data into files character by character

BC0037-9.4 Command Line Arguments and Printer Output


Command Line Arguments and Printer Output Command line arguments are useful to pass arguments to the program while running the program. These arguments can be used within the program and used. Command line arguments are used when invoking the program from DOS. In C++, like C, there are two default variables argc of type int and argv (array of strings) predefined for storing command line arguments which are usually defined as arguments to the main function. The following program shows the implementation of command line arguments and simply displays them. //comline.cpp # include <iostream.h> void main(int argc, char* argv[])

{ cout<<endl<<argc= <<argc; for (int j=0;j<argc;j++) cout<<endl<<Argument <<j<<= <<argv[j]; } If you invoke the above program with the statement C:/tc> comline sujay pawan vignesh Then the output will be as follows argc= 4 Argument0= c:/tc/comline.exe Argument1= sujay Argument2= pawan Argument3= vignesh As you can see in the output, the argc variable contains the argument count or number of arguments including the filename. Argv contains along with the path of the executable program, the strings passed as arguments. They can be referred by their index number. Let us see how we can send data to printer. It is similar to sending data to a disk file seen in the last section. The program uses filenames predefined in DOS for various hardware devices. PRN or LPT1 is the filename for the printer which is connected to the first parallel port. LPT2, LPT3 so on can be used if the printer is connected to second, third parallel port respectively. The following program prints a test message to the printer //printtest.cpp # include<fstream.h> void main() { ofstream prnfile(PRN); prnfile<<This is a test print page;

} In the above program we have created a ofstream object and associated it with the printer file name PRN and then flushed the contents to the object. As you can see the code and the way we direct the contents to a stream does not differ. Whether it is sending contents to display screen or printer or disk file, the syntax remains same. That is the beauty of stream class organization hierarchy. Self Assessment questions 1. __________ is the predefined filename assigned to printer by DOS 2. ________ variable holds the count of command line arguments. 3. ___________ object is created to send any content to printer.

BC0037-9.5 Summary
Summary Disk Input and output is handled is C++ using an hierarchy of stream classes. Files in C++ are objects of classes ifstream for input, ofstream for output and fstream for input as well as output. The class organization and inheritance enables the same syntax and methods to be used irrespective of the hardware device involved in input or output. Cin and cout are predefined objects of stream classes. These classes have several status checks for checking end of file, error conditions etc.

Anda mungkin juga menyukai