C++123

1,287 views

Published on

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,287
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
28
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

C++123

  1. 1. 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.inEducate Anytime...Anywhere..."Greetings For The Day"About EduprozWe, at EduProz, started our voyage with a dream of making higher education available for everyone. Since itsinception, EduProz has been working as a stepping-stone for the students coming from varied backgrounds. The bestpart is – the classroom for distance learning or correspondence courses for both management (MBA and BBA) andInformation 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 fewthings that we offer to our students. Our panel of industrial experts, coming from various industrial domains, leadstudents 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 giveimportance 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 withoutpaying anything extra. Our centrally air-conditioned classrooms, well-maintained library and well-equipped laboratoryfacilities provide a comfortable environment for learning.Honing specific skills is inevitable to get success in an interview. Keeping this in mind, EduProz has a careercounselling and career development cell where we help student to prepare for interviews. Our dedicated placementcell 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 4-minutes drive from the national highway); students can easily come to our centre from anywhere Delhi andneighbouring Gurgaon, Haryana and avail of a quality-oriented education facility at apparently no extra cost.Why Choose Edu Proz for distance learning?
  2. 2. • 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 Karnatakaas a full fledged University in the academic year 1996 vide Government notificationNo/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 forthe introduction and promotion of Open University and Distance Education systems in theeducation pattern of the State and the country for the Co-ordination and determination ofstandard of such systems. Keeping in view the educational needs of our country, in general, andstate 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, AsianAssociation of Open Universities (AAOU), Beijing, China, and also has association withCommonwealth of Learning (COL).Karnataka State Open University is situated at the North–Western end of the Manasagangotricampus, Mysore. The campus, which is about 5 kms, from the city centre, has a sereneatmosphere ideally suited for academic pursuits. The University houses at present theAdministrative Office, Academic Block, Lecture Halls, a well-equipped Library, Guest House
  3. 3. Cottages, a Moderate Canteen, Girls Hostel and a few cottages providing limitedaccommodation to students coming to Mysore for attending the Contact Programmes or Term-end examinations.BC0037-1.1 IntroductionIntroductionThis unit has the following objectives· To understand the importance of object oriented programming approach over procedurallanguages· To learn the basic features supported by OOP languages· To learn the basic construct of a C++ program and learn to compile and execute itBC0037-1.2 Evolution of ProgrammingmethodologiesEvolution of Programming methodologiesThe programming languages have evolved from machine languages, assembly languages to highlevel languages to the current age of programming tools. While machine level language andassembly language was difficult to learn for a layman, high level languages like C, Basic, Fortranand the like was easy to learn with more English like keywords. These languages were alsoknown as procedural languages as each and every statement in the program had to be specified toinstruct the computer to do a specific job. The procedural languages focused on organizingprogram statements into procedures or functions. Larger programs were either broken intofunctions or modules which had defined purpose and interface to other functions.Procedural approach for programming had several problems as the size of the softwares grewlarger and larger. One of the main problems was data being completely forgotten. The emphasiswas on the action and the data was only used in the entire process. Data in the program wascreated by variables and if more than one functions had to access data, global variables wereused. The concept of global variables itself is a problem as it may be accidentally modified by anundesired function. This also leads to difficulty in debugging and modifying the program whenseveral functions access a particular data.
  4. 4. The object oriented approach overcomes this problem by modeling data and functions togetherthere by allowing only certain functions to access the required data.The procedural languages had limitations of extensibility as there was limited support forcreating user defined datatypes and defining how these datatypes will be handled. For example ifthe programmer had to define his own version of string and define how this new datatype will bemanipulated, it would be difficult. The object oriented programming provides this flexibilitythrough the concept of class.Another limitation of the procedural languages is that the program model is not closer to realworld objects . For example, if you want to develop a gaming application of car race, what datawould you use and what functions you would require is difficult questions to answer in aprocedural approach. The object oriented approach solves this further by conceptualizing theproblem as group of objects which have their own specific data and functionality. In the cargame 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 Questions1. List the limitations of procedural languages2. _______ is an OOP Language3. In OOP approach programmers can create their own data types. True/False4. In procedural languages, the programs are written by dividing the programs into smaller unitsknown as __________BC0037-1.3 Introduction to OOP and itsbasic featuresIntroduction to OOP and its basic featuresAs discussed earlier, one of the basic concept in Object Oriented Programming approach isbundling both data and functions into one unit known as object. The functions of a particularobject can only access the data in the object providing high level of security for the data. Thefunctions in the object are known as member functions or sometimes as methods.The key features of OOP programming languages are: • Objects and Classes
  5. 5. 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 ObjectsPolygon Object Bank Account BehaviourAttributes Behaviour Attributes Deduct Funds MovePosition Account number Transferfunds EraseFill Color Balance DepositFunds ChangecolorBorder color ShowbalanceAccording to Pressman, Objects can be any one of the following:a) External entitiesb) Thingsc) Occurrences or eventsd) Rolese) Organisational unitsf) Placesg) Data StructuresFor example, objects can be an menu or button in an graphic user interface program orit may be an employee in an payroll application. Objects can also represent a datastructure such as a stack or a linked list. It may be a server or a client in an networkingenvironment.Objects with the same data structure and behaviorare grouped together as class. In other words, Objects are “instances” of a class. Classesare templates that provide definition to the objects of similar type. Objects are likevariables created whenever necessary in the program. For example, Employee may be aclass and Pawan, Sujay and Ganesh are objects of the class employees. Just as you cancreate as many variables of a default datatype such as integer, you can create as manyobjects of a class.Classes and Objects support data encapsulation and data hiding which are key termsdescribing object oriented programming languages. Data and functions are said to beencapsulated in an single entity as object. The data is said to be hidden thus not allowingaccidental modification.
  6. 6. • 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 approachBC0037-1.4 Basic components of a C++Program and program structure1.4 Basic components of a C++ Program and program structure
  7. 7. The C++ is a superset of C. At the basic level, the programs look similar in both C and C++. Everystatement in C++ ends with a semicolon (;). All the reserved words have to be written in smallcase and the c++ compiler is case sensitive. Data in programming languages are stored invariables. To create a variable, the variable should support an inbuilt datatype. The variable is aname given to a particular location in the memory and the value stored in a variable can bealtered during program execution. The datatypes supported in C++ are listed belowTable 1.2 Basic Datatypes in c++Data Type Size (in bytes) Values that can be takenInt 2 -32768 to 32767Bool 1 False and true / 0 and 1Char 1 -128 to 127Long 4 -2,147,483,648 to 2,147,483,647Float 4 3.4 X 10-38 to 3.4 X 1038 (Precision 7)Double 8 1.7 X 10-308 to 1.7 X 10308 (Precision 15)Long double 10 3.4 X 10-4932 to 1.1 X 104932 (Precision 19)Unsigned int 2 0 to 65,535Variables 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 usedVariables have to be declared before using them in the program. The declaration is done in thefollowing way:datatype variablenameEg: int data ;The above declaration declares a integer variable named data. The value stored in int data bydefault is a junk value. Values can also be assigned to the variable during declarations orinitialized separately using the assignment operator =.Eg: int data=0;Or int data;data=0;
  8. 8. 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.3Table 1.3 Example of ConstantsConstant Example Constraints 23000Numeric Can be negative or positive, cannot contain blanks orConstant 450.6 (Floating commas, or $ point)Character Any character enclosed within single quotes, represented by ‘A’Constant unique ASCII number in the memoryString Set of characters enclosed in double quotes, last character in “Hello”Constant the string is null character ‘0′Operators supported in C++ are listed below. Unary operators are used with one operand andbinary operator is used with two operands.Table 1.4 Operators in C++Arithmetic Operators Type 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 oneRelational Operators Type Action> Binary Greater than>= Binary Greater than or equal< Binary Less than<= Binary Less than equal== Binary Comparision for equality!= Binary Comparision for inequalityLogical Operators Type Action&& Binary AND|| Binary OR! Unary NOTLets begin with a simple c++ program// sum.cpp
  9. 9. #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 twonumbers. Iostream.h is a header file. The first statement of the above program is required ifyou would like to include the cin and cout statements which is used for standard input or inputfrom keyboard and standard output or output to display screen. cin and cout are actuallypredefined objects in C++. Iostream.h file contains the declarations for using the cin and coutstatements. There are several such header files which have to be included depending on thefunctions 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 functionsin the program, like C. However the program execution always begins with the master functionmain(). Paranthesis are used to group statements belonging to one function or programstatement. 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 asC 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 waydata is displayed. Endl is an operator which is similar to ‘n’ character in C that inserts a linefeedinto the output. The first cout statement in the program displays a statement where as thesecond 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 inputstream. The above cin statement waits for user to enter two integers. The values entered by theuser is then stored in the variables a and b. Each variable in cin statement should separated by >>operator.
  10. 10. Comment statements can be included in the program by prefixing the statement with “//” forsingle line comments. Comments add clarity to the program. Multiple line comments can beadded 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++ProgramCompiling and Executing C++ Program1. There are three steps in executing a c++ program: Compiling, Linking and Running theprogram. The c++ programs have to be typed in a compiler. All the programs discussed in thebook will be compiled on turbo c++ compiler. The turbo c++ compiler comes with an editor totype 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 isunderstandable by the machine. This process is known as compiling the program. You cancompile your program by selecting compile from compile menu or press Alt+f9. After compilinga 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 assource 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 ina project, there may be several smaller programs. The object codes of these programs and thelibrary files are linked to create a single executable file. Third and the last step is running theexecutable 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 theoutput of the program and comes back to the program editor. To view the output and wait foruser 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 throughstandard input. However you should include another header file named conio.h to use thisfunction. Conio.h contains the necessary declarations for using this function. The includestatement will be similar to iostream.h.
  11. 11. Fig. 1.1: Compiling and LinkingDuring compilation, if there are any errors that will be listing by the compiler. The errors may beany one of the following1. Syntax errorThis error occurs due to mistake in writing the syntax of a c++ statement or wrong use ofreserved words, improper variable names, using variables without declaration etc. Examples are :missing semi colon or paranthesis, type integer for int datatype etc. Appropriate error messageand the statement number will be displayed. You can see the statement and make correction tothe program file, save and recompile it.2. Logical errorThis 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 yoususpect 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 thewatch list, go to the statement from where you want to observe. If you are not sure, you can go tothe first statement of the program. Then select Debug ->Toggle Breakpoint (or press ctrl + f8). Ared line will appear on the statement. Then Run the program by selecting Ctrl + f9 or Run optionfrom 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 thewatch window. Press F8 to execute the next statement till you reach the end of the program. Inthis way you can watch closely the values in the watch variables after execution of each andevery statement in the program. If you want to exit before execution of the last statement pressCtrl + Break. To remove the breakpoint in the program go to the statement where you haveadded 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 valuestaken by the variable at each and every step. You can compare the expected value with the actualvalue to identify the error.3. Linker errorThis error occur when the files during linking are missing or mispelt4. Runtime error
  12. 12. This error occurs if the programs encounters division by zero, accessing a null pointer etc duringexecution of the programSelf Assessment Questions1. ___________, ______________ and _____________ are phases in execution of a C++program2. The logical error is identified by the compiler. True/False3. ________________ is the extension of C++ program source files4. ________________ is the extension of C++ object codeBC0037-1.6 SummarySummaryObject oriented Programming enables storing data and functions together which enables hidingdata from unnecessary exposure. Procedural languages differs from the Object orientedprogramming in the approach used in solving the problem. While the former focuses onorganizing programs around functions, the later focuses organizing programs around classes.Classes allow users to define their own datatypes and functionality. This allows extension of thebasic datatypes supported by the language. Reusability of code through inheritance allows usersto use the existing code without modifying it but also extend the functionality of the existingcode. 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 goesthrough two phases ie compiling and linking before execution.BC0037-2.1 IntroductionIntroductionThis 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++
  13. 13. BC0037-2.2 Selection control statements inC++Selection control statements in C++There are basically two types of control statements in c++ which allows the programmer tomodify the regular sequential execution of statements.They are selection and iterationstatements. The selection statements allow to choose a set of statements for execution dependingon a condition. If statement and switch statement are two statements which allow selection inc++. There is also an operator known as conditional operator which enables selection.If statementSyntax : 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 yieldstrue or false condition. If no relational operators are used for comparison, then the expressionwill be evaluated and zero is taken as false and non zero value is taken as true. If the condition istrue, 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 ifstatement is exceuted, if the condition is false. If there is only one statement to be executed in theif 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>
  14. 14. void main(){int num;cout<<”Please enter a number”<<endl;cin>>num;if ((num%2) == 0)cout<<num <<” is a even number”;elsecout<<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 asodd. We make use of the relational operator == to compare whether remainder is equal to zero ornot.Nested If statementIf statement can be nested in another if statement to check multiple conditions.If (condition1){ if (condition 2){ statement1;Statement2;}else if (condition3){statement3;}
  15. 15. }else statement4;The flowchart of the above example is shown belowFig. 2.1: Nested If StatementMultiple conditions can be checked using logical && operator(AND) and || operator (OR).If ((condition1) && (condition2))statement1;elsestatement2;In the above example statement1 will be executed if both the condition1 and condition2 are trueand in all other cases statement2 will be executed.If ((condition1 || (condition2))statement1;elsestatement2;In the above example statement1 will be executed if either condition1 or condition2 are true andeven if both are true. Statement2 will be executed if both the conditions are false. The followingprogram demonstrates the use of && operator and nested if statement.
  16. 16. //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 largestnumber among the three.( assumption is that all the numbers are unique, the program has to bemodified if you would like to allow same number twice)Switch statementNested ifs can be confusing if the if statement is deeply nested. One alternative to nested if is theswitch statement which can be used to increase clarity in case of checking the different values ofthe same variable and execute statements accordingly.Syntax :Switch (variablename){ case value1: statement1;break;case value2: statement2;
  17. 17. 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 equalto value2 then statement2 is executed, if it is value3 then statement3 is executed. If the variablevalue 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 beused for displaying any error message. Each case can have any number of statements. Howeverevery case should have a break statement as the last statement. Break statement takes the controlout of the switch statement. The absence of the break statement can cause execution ofstatements in the next case. No break is necessary for the last case. In the above example, defaultcase does not contain a break statement.The flowchart for the switch statement is shown in Fig 2.2Fig. 2.2: Switch StatementThe following program implements the switch statementposition.cpp# include<iostream.h>void main()
  18. 18. { 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 downrespectively. The position is initialised to 15 and 15 which are x and y coordinates of hisposition. Depending upon the what user has selected the the x and y co-ordinates are incrementedor decremented by one(x++ is same as x=x+1). If the user types a letter other than l,r,u,d, he getsan error message. Since the switch variable is a character, l,u,r,d and enclosed within singlequote.++ and — operator can be used as postfix or as prefix operator which has no effect if used as anindependent statement. However if it used as part of an expression, the prefix operator will be
  19. 19. operated and then the expression will be evaluated whereas the postfix operated will be evaluatedlater.For example in the statement x= a+ (b++), a will be added to b and then stored in x and then thevalue of b will be incremented. If the same expression is written as x=a+(++b), the the b will beincremented and then added to a and stored in x.Conditional OperatorConditional operator (?:) is a handy operator which acts like a shortcut for if else statement. Ifyou had to compare two variables a and b and then depending on which is larger, you wanted tostore that variable in another variable called large. You would do this using if else statement inthe following way:if (a>b)large=a;elselarge=b;The above can be done using conditional operator in the following way:large= (a>b) ? a : b ;Self Assessment Questions1. In if else statement, at any point of time statements in both the if and else part may beexecuted. True/False2. Conditional operator is an alternative to __________ statement3. ++ operator increments the value of the operand by _________4. The ++ operator used as postfix and prefix has the same effect. True or False5. Each case in switch statement should end with _________ statementBC0037-2.3 Iteration statements in C++Iteration statements in C++
  20. 20. Iteration or loops are important statements in c++ which helps to accomplish repeatitiveexecution of programming statements. There are three loop statements in C++ : while loop, dowhile loop and for loopWhile loopSyntax: while (condition expression){Statement1;Statement 2;}In the above example, condition expression is evaluated and if the condition is true, then thestatement1 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 conditionbecomes false. Hence the variable used in the loop condition should be modified inside the loopso that the loop termination condition is reached. Otherwise the loop will be executed infinitelyand the program will hang when executed. Also the loop variable should be iniatialised to avoidthe 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 StatementThe following program implements the while loop// average1.cpp# include <iostream.h>
  21. 21. 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 fivenumbers. In the above while loop, the variable n is initialized to zero and this variable keepstrack of the count of numbers input from the user. It is incremented every time a number is inputfrom the user. The number accepted from the user is added to the value stored in the sumvariable. When n becomes 5 the while loop condition becomes false and the average of thenumbers is printed. Please note that there is no semicolon after while and condition expression.Do..while loopThe do while loop is same as while loop except that the condition is checked after the executionof statements in the do..while loop. Hence in do..while loop, statements inside the loop areexecuted atleast once. However, in while loop, since the condition is checked before, thestatements inside the loop will not be executed if the loop condition is false.Syntax:do{
  22. 22. Statement1;Statement2} while (condition expression);In the above example the statement1 and statement2 are executed and the condition is checked. Ifthe condition is true then the statements are executed again and if the condition is false then thecontrol is transferred to the next statement after the do..while statement.The flowchart for the do..while statement is shown in Fig 2.4Fig. 2.4: Do..while StatementPlease note that there is no semicolon after do, but there is a semicolon after the conditionexpression 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{
  23. 23. 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 statementsinside the loop have to be executed atleast once or not. If it has to be executed atleast once, thenthe do..while statement should be used.For loopThe 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 iterationare all included in one statement.Syntax:for(initialization statement;loop termination condition;statement to increment/decrement the loopvariable){Statement1;Statement2;}In the above example, initiation statement is executed first and then the termination is checked. Ifthe condition is true, statement1 and statement2 will be executed. Then the third statement in thefor loop is executed which modifies the loop control variable.The flowchart for the for statement is shown in Fig 2.5
  24. 24. Fig. 2.5: For StatementPlease 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);
  25. 25. }In the above example n variable is loop variable which is initialized to zero. Please note that thevariable is also declared inside the for loop. So this variable can be accessible only inside the forloop. The scope of the variables will be declared in detail in unit 4. The statements inside theloop 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 thefactorial 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 loopis 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 statementsas shown in the following expressionfor(i=0,j=0;i<=n;j++,i++){statements;}
  26. 26. 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. Howeveryou should use for loop if you know in advance how many times the loop has to be executed. Ifthe loop has to be executed atleast once irrespective of whether the condition is true or false, thendo while loop should be used.Self Assessment Questions1. 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 above2. ___________ 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 enclosedwithin ______________BC0037-2.4 Break continue and exitstatements 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 loopcondition becomes false. However if required, the control sequence can be changed by usingbreak, continue or exit statements.Break statement transfers the control to the next statement after the loop and all the remainingstatements and the iterations in the loop are skipped. It is used if you would like to exit the loopwhen a certain condition is met. In the switch statement break statement takes the control to thenext 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;
  27. 27. int prime=0;cout<<”Enter a number”;cin>>number;// check whether the number is divisible by any number from 2 to number/2for (int i=2;i<=number/2;i++){if ((number%i)==0){ prime=1;break;}}if (prime==0)cout<<”The number is prime number”;elsecout<<” The number is not a prime number”;}In the above program, the user is asked to enter a number and the program checks whether thenumber is prime or not and displays the message accordingly. To check whether the number isprime or not, the number is divided by 2,3… and so on till number/2. If the number is divisibleby any number, the variable prime is assigned a value one and the loop is terminated as there isno need to check whether the number is divisible by rest of the numbers. The value 1 in theprime 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 thecontrol has to be transferred to the next iteration of the loop based on a condition skipping all theother statements in the loop. The following program shows the use of continue statement.move.cpp# include<iostream.h>
  28. 28. # 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’);}
  29. 29. In the above example clrscr() function which is a library function is used to clear the screenbefore accepting the input from the user. To use this function, conio.h header file must beincluded.Exit function in a program takes the control out of the program. Exit is an inbuilt libraryfunction. To use this function process.h header file has to be included in the program. The syntaxof this function is exit(integer).While terminating the program, the integer is returned to theoperating system. Usually the function integer 0 is used to imply no error or successfultermination 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 particularstatement. The statement should have a label.Syntax: goto statement labelnameStatements can be given labels in the following waylabelname: statementThe use of goto statement should be avoided as it creates problems in program debugging andthe program may have confusing jumps from one statement to another.Self Assessment Questions1. _________ statement takes the control out of the loop.2. __________ header file should be included to use exit function3. __________ statement takes the control to the beginning of the loop.4. ________ statement takes the control to a particular statementBC0037-2.5 SummarySummarySelection and iteration statements allow to execute statements in the program based on acondition bypassing the normal sequential execution. Selection is enabled through if statement,switch statement and conditional operator. Switch statement is suitable when you have multipleconditions 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 conditionbecomes false. Break, continue and exit statements are used to transfer control out of the loop, tothe next iteration of the loop and out of the program respectively.
  30. 30. BC0037-3.1 IntroductionIntroductionThis 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 ArraysIntroduction to ArraysArrays are used when you want to store related data of same type together with the same name sothat you can access them easily. Arrays can be defined as datastructures that allow to store groupof data of same datatype. You can retrieve data stored in the array in any order. For example, letus suppose you want to write a program which will help you to compute average marks scoredby students in a class of 60. To allow this computation, your program should store marks scoredby 60 students in a class separately, so that you can do any kind of computation when required. Itwould be tedious, if you had to create 60 different variables to store marks of 60 students andmanage them separately. Arrays solves this problem, by grouping data of similar type with samename 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 duringdeclaration which determines how many elements the array can store. The following is adeclaration 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 thearray enclosed within square brackets.The datatype of data stored by the array can be any defaultdatatypes supported by c++ or user defined datatypes.Elements in the array can be accessed through index numbers. The data in the array are storedwith index numbers 0,1, and so on. Since the index number starts with 0 the last index number ofan array of size n will be n-1. The elements stored in the array are accessed by using the arrayname 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 itvery easy to store and access large number of data. The code can be simplified by includingcommon statements that needs to be performed on the array elements inside a loop and makingthe loop variable as the variable that stores the index variable.
  31. 31. 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 fromthe 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, thevalue stored in i also varies.Another interesting aspect of the array is that all the elements in the arrays are allottedconsecutive 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(){
  32. 32. 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 datashould be separated by a comma and all elements enclosed within flower brackets as shownbelowint 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..
  33. 33. Self Assessment Questions1. Arrays group data of __________ type2. An array declared as int a[10] can store __________ integers3. a[5] represents the _________ integer in the above array.4. Array elements are accessed through _______________BC0037-3.3 Multidimensional ArraysMultidimensional ArraysThe arrays can be multidimensional as well to store the required data. For example a twodimensional array can be created to store data about a matrix. A 3×4 matrix that has 12 dataelements can be created using the following declarationint mat[3][4];The above array has 3 rows and four columns. The elements in the array can be accessed by twoindexes. To refer to an element in the first row and second column mat[0][1] has to be used asthe index starts from zero.The following program accepts from the user two 2×3 matrices and adds the two matrices.//matrix.cpp# include <iostream.h>void main(){ int a[2][3], b[2][3], c[2][3];
  34. 34. int i,j;cout<<”Enter the elements for the first 2×3 matrix”;for (i=0;i<2;i++)for (j=0;j<3;j++){ cin>>a[i][j];}cout<<”Enter the elements for the second 2×3 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
  35. 35. int a[2][2] = {{ 3,4},{ 2, 7}}Every row elements are initialized by enclosing them in separate flower brackets.In the aboveexample elements 3 and 4 will be initialized to a[0][0] and a[0][1] respectively.Self Assessment Questions1. An array with the declaration int x[4][5] can store ________ numbers2. 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/FalseBC0037-3.4 Strings and String relatedLibrary FunctionsStrings and String related Library FunctionsStrings are nothing but character arrays. Strings are usually used to store data such as employeename, address, product description, password etc. The size of the string is defined duringdeclaration like any other array. One basic difference between other arrays and strings is that thecompiler stores an extra null character (’/0′) for every string to mark the end of the string. Thisenables a good means of identifying the end of the string as string variables usually store variablelength values. Strings, unlike other arrays can be input without using a loop. When inputtingstrings using cin statement, the compiler stops taking input from the user once it encountersspace 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 asfollows:H str[0]E str[1]L str[2]L str [3]O str[4]/0 str[5]
  36. 36. The strings can be also initialised as arrays. However they can be initialized by enclosing thecharacters in the string constant with double quotes instead of initializing it character bycharacter. 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 initializedto 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 thanthe string maximum size. The extra characters entered by the user will be truncated. To keep acheck 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 nullcharacter).While inputting strings, cin stops reading once it encounters space or linefeedcharacter( when user presses enter). To read blanks between the strings or to read multiple linesof text, get function which is a member function of cin can be used.The following statement willallow user to input a maximum of 39 characters which can even include blanks. It will stopreading 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 whichwill be used to recognize end of input. In the following example, the terminating character is $.
  37. 37. cin.get(str,40,$);The above example will allow users to enter a maximum of 39 characters which can includeembedded blanks and linefeed.C++ has several string related library functions that are used to manipulate strings. Some ofthese are discussed below. To use these functions, header file string.h has to be included. Someof the library functions such as strlen, strcpy, strrev, strcmp is discussed below.Strlen FunctionStrlen function is used to find the length of the string. The syntax of the strlen function isstrlen(string variable). The function returns the length of the string or the number of characters inthe 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 theinteger variable named lenStrrev functionStrrev function arranges the characters in the string variable in reverse order except for the nullcharacter. 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 ollehThe null character will be the last character of the string.char str[10]=”hello”;cout<<strrev(str);Strcpy functionStrcpy function copies the contents of one string to another. The syntax of strcpy function isstrcpy(destination string, source string). The function returns the destination string value aftercopying. For example, in the following program statement, the contents of the string str will becopied to string namechar str[10]=”ravi”;
  38. 38. char name[10];strcpy(name,str);The strcpy can also use string constants to be assigned to a string variable like in the followingstatement.strcpy(name,”ravi”);In the above statement the string constant ravi is assigned to the string variable name. Theassignment of a string variable cannot be done using an assignment operator. It should be doneusing strcpy function. The following statement in a program will provide an compilation error:name=”ravi”; //wrong statementStrcmp functionStrcmp 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 ASCIIvalues of the character will be used to decide the return value. The function returns an integerand the value returned will differ based on the conditions as shown below:If string1 < string2, value returned will be <0If string1==string2, value returned will be 0If 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 thetwo strings are not equal. Please note that the above function is case sensitive. Strcmpi() functioncan 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];
  39. 39. 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;}elsecout<<”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.
  40. 40. BC0037-3.5 SummarySummaryArrays are used to store large volumes of similar data together. The array elements can beaccessed by specifying array name followed by the number which indicates the position of theelement in the array. Arrays of basic datatypes such as integers, characters etc and user defineddatatypes 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 stringhas a null character ‘0’ as its last character which marks the end of the string. There are severalstring related library functions that can be used to manipulate stringsBC0037-4.1 IntroductionIntroductionThis 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 togetherBC0037-4.2 Introduction to FunctionsIntroduction to FunctionsFunctions provide an easy means to organize the programs into smaller modules and use themagain without rewriting all the code. It enables reuse of program code. Functions enableprogrammers to group program code under one name and invoke them whenever required. Wehave been using several library functions till now without worrying about the code to implementthem. Programmers can define their own functions in C++. In this unit, we will learn how toimplement 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 calland 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 novalue returned it should be specified as void.The function main() which we had been using in all
  41. 41. the programs is one of the default functions which also has been defined as having no returnvalue. 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 functionsand are used inside the function. During declaration of the function, the datatypes of thearguments should be specified. Each argument should be separated with a comma. Thearguments 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 definitioncan be present in any part of the program. The following is an example of declaration of afunction 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, voidshould be specified within the brackets. The following is the declaration of a function which doesnot 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 thevariables or constants that has to be passed as arguments. If there are no arguments that has to bepassed to the functions, then the function name should be followed by a pair of paranthesis. Thefollowing program would invoke the xyz function:xyz();To invoke a square function which inputs a number and returns a number following statementcan be used:s=square(n);Where s and n are integer variables. The function will compute square of n and the result will bestored 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 youwould like to write a program that computes the combination of n items taken r at a time. Themathematical formula for computing nCr is n!/(r!*(n-r)!). In this problem, the factorial of thenumbers have to be computed three times. The code for implementing factorial of a number hasbeen discussed in the unit 2.3 in factorial.cpp program. If the same code has to be directlyimplemented without functions, the code has to be repeated three times in the program tocompute factorial of n, r and n-r. This would not only make programs unnecessarily big but alsodifficult to correct or debug. To avoid this problem, we can define a user defined function named
  42. 42. 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 belowint fact(int);We can compute the factorial of n just by specifying fact(n) which would call the function factand execute the statements. The complete program for implementing the above problem is asbelow://function.cpp# include <iostream.h>int fact(int); // function declarationvoid 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
  43. 43. }In the above program, the user inputs value for n and r. To compute the value of ncr, the factfunction is invoked or called first by passing n variable. When the compiler encounters the firststatement of the function, it copies the value of the variable n to the variable number. Thevariable number has scope only inside the function fact and is known as local variable. It cannotbe accessed outside the function and so is the variable f and i that has been defined in thefunction. The factorial of the variable number (same value as n) is computed and then returned tothe calling program through the return statement. The return statement is used to return values orresults to the main program. This process is repeated for the values r and n-r as well. All theresults 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 controlgoes 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 novalue is being returned to the main program.Self Assessment questions1. Functions enable to reuse code. True/False2. void print() would return _______ value3. ________ statement is used to return value to the main program.4. Function call should always contain function name followed by paranthesis even if there areno arguments. True/FalseBC0037-4.2 Introduction to FunctionsIntroduction to FunctionsFunctions provide an easy means to organize the programs into smaller modules and use themagain without rewriting all the code. It enables reuse of program code. Functions enableprogrammers to group program code under one name and invoke them whenever required. Wehave been using several library functions till now without worrying about the code to implementthem. Programmers can define their own functions in C++. In this unit, we will learn how toimplement 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 calland 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 novalue returned it should be specified as void.The function main() which we had been using in allthe programs is one of the default functions which also has been defined as having no return
  44. 44. 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 functionsand are used inside the function. During declaration of the function, the datatypes of thearguments should be specified. Each argument should be separated with a comma. Thearguments 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 definitioncan be present in any part of the program. The following is an example of declaration of afunction 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, voidshould be specified within the brackets. The following is the declaration of a function which doesnot 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 thevariables or constants that has to be passed as arguments. If there are no arguments that has to bepassed to the functions, then the function name should be followed by a pair of paranthesis. Thefollowing program would invoke the xyz function:xyz();To invoke a square function which inputs a number and returns a number following statementcan be used:s=square(n);Where s and n are integer variables. The function will compute square of n and the result will bestored 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 youwould like to write a program that computes the combination of n items taken r at a time. Themathematical formula for computing nCr is n!/(r!*(n-r)!). In this problem, the factorial of thenumbers have to be computed three times. The code for implementing factorial of a number hasbeen discussed in the unit 2.3 in factorial.cpp program. If the same code has to be directlyimplemented without functions, the code has to be repeated three times in the program tocompute factorial of n, r and n-r. This would not only make programs unnecessarily big but alsodifficult to correct or debug. To avoid this problem, we can define a user defined function namedfact 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
  45. 45. int fact(int);We can compute the factorial of n just by specifying fact(n) which would call the function factand execute the statements. The complete program for implementing the above problem is asbelow://function.cpp# include <iostream.h>int fact(int); // function declarationvoid 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}
  46. 46. In the above program, the user inputs value for n and r. To compute the value of ncr, the factfunction is invoked or called first by passing n variable. When the compiler encounters the firststatement of the function, it copies the value of the variable n to the variable number. Thevariable number has scope only inside the function fact and is known as local variable. It cannotbe accessed outside the function and so is the variable f and i that has been defined in thefunction. The factorial of the variable number (same value as n) is computed and then returned tothe calling program through the return statement. The return statement is used to return values orresults to the main program. This process is repeated for the values r and n-r as well. All theresults 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 controlgoes 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 novalue is being returned to the main program.Self Assessment questions1. Functions enable to reuse code. True/False2. void print() would return _______ value3. ________ statement is used to return value to the main program.4. Function call should always contain function name followed by paranthesis even if there areno arguments. True/FalseBC0037- 4.4 Scope and Visibility of variablesin FunctionsScope and Visibility of variables in FunctionsFunctions 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 jumpto 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 saveexecution time of functions, one of the feature in c++ is inline functions. An inline function’scode is put with the code in the calling program for every function call. The inline function iswritten like any other function except that the function declaration begins with the keywordinline. 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 neatand less lengthy, at the same time the actual code is inserted in all the places where thefunction is called after compilation enabling faster execution of the program.
  47. 47. 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 Staticvariables.Automatic variables is default variable in C++. All the variables we have created and used inprograms are automatic variables. These variables can also be declared by prefixing the keywordauto. One of important characteristics of these variables are that they are created only when thefunction or program block in which they are declared are called. Once the execution of functionor module execution is over, the variables are destroyed and the values are lost. The reason forlimiting the lifetime of automatic variables is to save memory. When the variables are not beused by the function, they are removed from the memory. They can be accessed only within thefunction where they are declared. Beyond which they are not idenfiable. By default the automaticvariables are not initialized to any specific values unless and until specified. They contain junkvalue depending on the value stored in the memory. Therefore it is necessary to initializeautomatic variables to avoid problems in debugging.External variables are variables external to any function. Thus they can be accessed by multiplefunctions. This is the easiest way to share data among various functions. However too manyexternal variables can create problems in debugging as the programmer will have tough timefiguring out which function modified which data. Object oriented programming provides analternative to use external variables. This feature is just to support backward compatibility withC. 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 anyfunction.The following program shows the difference between an external variable and an automaticvariable.//external.cpp# include<iostream.h>int x;void f1();void f2();void main(){x=x+2;
  48. 48. 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 automaticallyinitialized to zero. The statement x=x+2; will store two in x. The function f1 will not have anyimpact on the value of the external variable as there is another local automatic variable x definedin the function which will be modified (Please note that when automatic and global variable havesame name, the local variable will override the global variable).The function f2 will increment global variable by one. Thus the final output of the aboveprogram 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 thefunction in which they are defined like automatic variables. But they can retain their values evenafter the function execution is over and are automatically initialized to zero like externalvariables. The following program shows the use of the static variables.// static.cpp# include <iostream.h>void main(){
  49. 49. 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 ofthe numbers till then. The static variables sum and n are intitialised to zero. They are updatedwhen user enters a new number and the function is called. The values of these variables areretained even after the function returns back to the main program.The summary of all three storage classes is shown below: Automatic Static ExternalVisibility Function Function ProgramLifetime Function Program Program
  50. 50. Intialised Junk value in Zero Zeroto memory Same as automatic but the value Variables used by Variables used byPurpose should be retained when function single function several functions terminatesSelf 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 thatare of different types but are logically related can also be grouped together. This can be donethrough structures. Structures are a group of dissimilar data that are related with each other. Forexample, 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 asshown 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 specifythe 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 datatypeand 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;
  51. 51. Structure variables can be initialized during declaration. The values for all the members shouldbe specified separated by comma and all the values enclosed within flower brackets as shownbelowemployee e1= {1234, “Ajay”, 12, 6900.00};Structure variables can be copied and assigned to another structure variable as shown belowemployee e2;e2=e1;To access the members of the structure variables, dot operators can be used. For example toaccess 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 dotoperators can be used. Let us suppose you have defined a structure named distance with twomembers 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 distancestruct room{ distance length;distance width;distance height;} bedroom;In the above definition, we have declared a variable bedroom of type room along with thedefinition.To access the members of the bedroom we can usebedroom.length.feet
  52. 52. bedroom.length.inchesbedroom.width.feetbedroom.width.inches and so onTo initialize nested structures you have to group together all the elements of the structureroom dining = {{12, 3},{13,0},{11,2}}In the above declaration, the values 12 and 3 refer to dining.length.feet and dining.length.inchesrepectively. Similarly the second and third set of values represent feet and inches of width andheight respectively.Array of structures can be created. The index number should be specified immediately after thestructure variable. For example, the statementemployee emp[50] ;will create a array of structure employee.To access the first array member, you can say emp[0].empidThe 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;
  53. 53. 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 thepoint. Along with the declaration we have also created two point variables p1 and p2. This is away to create variables along with the structure decalaration. This can be a separate statementalso as discussed earlier. The program accepts two points from the user and displays the distancebetween them.Structures are good mechanism of creating userdefined datatypes. C++ specifies another methodknown as enumerated data type to enable users create their own datatypes. Enumerated datatypes can store fixed set of values and you can perform arithmetic on them as well. They aredefined using the keyword enum. The following program creates an enumerated datatype whichstores 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”;
  54. 54. }In the above program enumerated datatype weekday is created. The first value (Sun) is assignedzero by default and so on. The variables day1 and day2 can be assigned only the values specifiedin the datatype declaration or their integer equivalent. They cannot be assigned any other value.Self Assessment Questions1. Structures group data of similar type. True/False2. ___________ keyword is used to create structures.3. Member data of the structure are accessed by ________ operatorBC0037-4.6 SummarySummaryFunctions provide good mechanism to organize data. Functions are given a name which can beused to call the function and execute the statements in the functions. Functions can also takeinput which are known as arguments which passed during function call. Arguments can bepassed either by value or by reference. They can also have return value which can return ancomputed value back to the main program. Inline functions enable programmers to saveprocessing time by reducing the overheads involved in function call.Programs can make use of automatic, external and static variables which have different types ofutility depending on the way the variable should be accessed and whether the value has to beretained.Structures and enumerated data types enable to users to create user defined datatypes. Structuregroup data items that have different datatypes. Enumerated datatypes create datatypes that canstore pre-defined and fixed set of valuesBC0037-5.1 IntroductionIntroductionThis 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
  55. 55. BC0037-5.2 Creating classes and objectsCreating classes and objectsIn the unit 1, we had a brief discussion of objects and classes. In this section, we will see how wecan implement them. Classes provide users a method to create user defined datatypes. We haveseen two types of user defined datatypes structures and enumeration in the last unit. Both areprimarily used for modeling data only. In several real life situation, you would require to modelfunctionality of the datatype along with the data. Classes enable you to bind data and functionsthat operate on data together. However, in C++ you can use structures same as classes by bindingfunctions with data. But usually the structures are only used when you want to group data andclasses 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 canmodel 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 instanceof a class. Class is a definition, objects are used in the program that enables you to store data anduse them.To understand the various syntactical requirements for implementing a class, let us take anexample.// distance.cpp#include<iostream.h>class distance{ private:int feet;int inches;public:void setdistance(int a, int b){ feet=a;inches=b;}
  56. 56. 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 andinches and two functions or methods setdistance and display (). Classes are defined with thekeyword class followed by the name of the class. The object of this class is d1. Every objects ofa class have their own copy of data, but all the objects of a class share the functions. No separatecopy of the methods is created for each and every object. Objects can access the data through themethods. To invloke a method, objectname.methodname is used. The methods defined in theclass can only be invoked by the objects of the class. Without an object, methods of the functioncannot be invoked.You can see in the above program, the data elements feet and inches are defined as private. Themethods are defined as public. These are known as access specifiers. Data and functions in aclass can have any one access specifiers: private, public and protected. Protected access specifierwe will discuss later in unit 7 along with inheritance. Private data and functions can be accessedonly by the member functions of the class. None of the external functions can access the privatedata and member functions. Public data and member functions can be accessed through theobjects 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 issometimes referred to as data hiding. The data is hidden from accidently getting modified by anunknown function. Only a fixed set of functions can access the data. In a class, the data andfunctions are private by default so private keyword can be omitted.Fig. 5.1: Access specifiers in a class
  57. 57. Certain object oriented programming languages refer to methods as messages. Thus d1.display()is a message to d1 to display itselfUsually, data are declared as private and functions as public. However, in certain case you mayeven 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 themember 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 whichimplements an add member function to the distance class. We can do this in two ways. Theprototypes of the function is shown below:void add(distance, distance);ordistance add(distance);The first function takes two distance objects as arguments and stores the result in the objectinvoking 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;
  58. 58. }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 theinvoking object’s data members. After adding the respective data of d1 and d2 it is stored in d3object.Alternatively, the above program can be implemented in a different way as shown below//adddist2.cpp
  59. 59. #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;}};
  60. 60. 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 andd2 is passed as an argument. Since the calling objects data are passed automatically, d1 objectsdata members can be accessed in the function. They are referred directly as feet and incheswithout the objectname (as it is implicit in the member function). The add function stores thesummed value in a temporary variable and then returns it to the calling program.Self Assessment Questions1. Private data members can be accessed only by the __________ of the class2. Public data members can be accessed directly in the main function without an object.True/False3. Every object of a class has its own copy of the data and functions. True/FalseBC0037-5.3 Constructors and DestructorsConstructors and DestructorsConstructors and destructors are very important components of a class. Constructors are memberfunctions of a class which have same name as the class name. Constructors are calledautomatically whenever an object of the class is created. This feature makes it very useful toinitialize the class data members whenever a new object is created. It also can perform any otherfunction that needs to be performed for all the objects of the class without explicitly specifyingit.Destructors on the other hand are also member functions with the same name as class but areprefixed with tilde (~) sign to differentiate it from the constructor. They are invokedautomatically whenever the object’s life expires or it is destroyed. It can be used to return thememory back to the operating system if the memory was dynamically allocated. We will seedynamic allocation of memory in Unit 7 while discussing pointers.
  61. 61. 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 invokedData=0Destructor invokedWhen object of sample class, obj is created, automatically the constructor is invoked and data isinitialized 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 returnvalue. However, constructors can have arguments and can be overloaded so that differentconstructors can be called depending upon the arguments that is passed. Destructors on the other
  62. 62. hand cannot be overloaded and cannot have any arguments. The following program implementsthe 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()}
  63. 63. In the above program, the setdistance function is replaced with the two constructors. These areautomatically 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 twoarguments are passed. Please note that to invoke a constructor with arguments, argument valueshave to be passed along with the object name during declaration.Self Assessment Questions1. 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 ________ sign3. Destructors can be overloaded. True/False4. Constructors can be overloaded. True/FalseBC0037-5.4 Static variables and Functions inclassStatic variables and Functions in classWe have seen that when an object is created, a separate copy of data members is created for eachand every object. But static data member in a class is an exception. Static data member of theclass is one data member that is common for all the objects of the class and are accessible for theclass. It is useful to store information like count of number of objects created for a particularclass or any other common data about the class. Static data member is declared by prefixing thekeyword static.We have learnt that to invoke a member function of a class, you need to have object. Suppose wehave a static data member which keeps track of the total objects created and there is a showtotalfunction which displays the total value. We will not be able to know the total if there are noobjects which is a serious limitation. Static functions are the solution for this. Static functions arespecial type of functions which can be invoked even without an object of the class. Staticfunctions are also defined by prefixing the keyword static. It is called using classname followedby scope resolution operator and function name. The following program implements the staticdata and functions//classstatic.cpp# include <iostream.h>class A {static int total;
  64. 64. 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();
  65. 65. }The output of the above program0212In the above program total is an static variable which is shared by all objects of the class A. Thestatic variables of the class have to be explicitly initialised outside the class using the class namefollowed by scope resolution operator (::) and static variable name.Please note that you have to specify the datatype but need not specify the keyword static duringinitialization. The variable total is incremented in the constructor which will increment the totalwhenever a new object is created. Similarly, it is decremented through the destructor when theobject is destroyed. The function showtotal is a static function which is invoked without theobject and using the classname.The fig 5.2 summarises member functions and data of a classFig. 5.2: Data and Functions in a classSelf Assessment Questions1. Static data member of a class can be modified by all objects of the class. True/False2. Static functions are accessed using __________3. Static data need not be initialized. True/FalseBC0037-5.5-Summary

×