0% found this document useful (0 votes)
28 views

Computer Programming in C SMPH52

C++ programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
28 views

Computer Programming in C SMPH52

C++ programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 150
GOVERNMENT ARTS AND SCIENCE COLLEGE NAGERCOIL — 629 004 [ Affiliated to Manonmaniam Sundaranar University, Tirunelveli — 12 ] DEPARTMENT OF PHYSICS NAME OF THE SUBJECT : COMPUTER PROGRAMMING IN C++ SUBJECT CODE : SMPHS52 YEAR : IILB.Sc. PHYSICS SEMESTER iy STAFF IN-CHARGE : Dr. G.M.CARMEL VIGILA BAI Head, Department of Physics Government Arts and Science College NAGERCOIL. Email : gmcarmelgasc@ gmail.com Mobile No.: 9487819696 PAPER HANDLED BY :Dr.G.N ‘ARMEL VIGILA BAI BOOK FOR REFERENCE: Object Oriented Programming with C**- E.Balagurusamy, Tata Mc Graw-Hill publishing company Ltd. New Delhi. ACKNOWLEGEMENT 1 express my thanks to the staff members, students and my family members who helped me in some way to make this course material. Also, I express my sincere thanks to the authors of various books, specially to Prof. E.Balagurusamy, Author of Object Oriented Programming with C*- Tata Me Graw-Hill publishing company Ltd., New Delhi. (Dr. G.M.CARMEL VIGILA BAT) CONTENTS S.No. Topic Page No. 1 | M.S.University Syllabus i 2 | UNITE 1 3 | UNIT. 7 4 | UNIT 34 5 |UNITIV 86 6 |UNITV 112 7 | Unit Test, Internal Test, Model Exam Question Papers | 137 8 | M.S. University previous year Question Papers 143 PAPER VII COMPUTER PROGRAMMING IN C+ Preamble: Objective of the course is to provide knowledge about the basics of Computer programming in C** and to solve problems by writing programs. The paper does not need any special prerequisite and the learners are expected to come out with the ability to apply the computer language C™ to solve problems . UNIT-I: WHAT IS C* Introduction - tokens - keywords - identifiers and constants - declaration of variables - basic data types - user defined data types-derived data types - symbolic constants - operators in C** -expressions and their type-hierarchy of arithmetic operators- scope resolution operator — declaring, initializing and modifying variables-special assignment operators - all control structures- structure of a simple C ++ program (IL) UNIT-II: ARRAYS AND FUNCTIONS IN C** Introduction - one dimensional and two dimensional arrays-initialization of arrays-array of strings Functions-introduction-function with no argument and no return values- function with no argument but return value - function with argument and no return values- function with argument and return values- call by reference- return by reference- function prototyping - inline functions - local, -global and static variables- -function overloading - virtual functions-main function-math library functions. (13L) UNIT-III: CLASSES AND OBJECTS Introduction - specifying a class - defining member functions-C"* program with class - nesting of member functions - private member functions - objects as function arguments - arrays within a class-array of objects-static class membersfriend functions-constructors - parameterized constructors-multiple constructors - constructors with default arguments - copy constructor. (15L) UNIT-IV: OPERATOR OVERLOADING, INHERITANCE AND POINTERS Introduction -defining operator overloading - overloading unary operators - binary operators. Inheritance - single inheritance - multiple inheritance - multilevel inheritance - hybrid inheritance - hierarchial inheritance-virtual base class-abstract class Pointers- definition-declaration- arithmetic operations. (12L) UNIT-V: MANAGING CONSOLE I/O OPERATIONS Introduction - C™* stream - C** stream classes - unformatted I/O Operations formatted console I/O operations - working with files - classes for file steam operations - opening and closing a file - file pointers and their manipulations. (9L) Books forstudy 1, Object oriented Programming with C**- E.Balagurusamy, Tata Me Graw- Hill publishing company Ltd. New Delhi Books forreference 1.Programming with C™ - D.Ravichandran, Tata Mc Graw-Hill publishing company Ltd. New Delhi . 2. Object oriented Programming in C*"4"" Edn.Robert Lafore-Macmilan publishing company Ltd. 3. Fundamentals of Programming with C”* -Richardl.Halterman DEPARTMENT OF PHYSICS, GOVERNMENT ARTS AND SCIENCE COLLEGE, NAGERCOIL, SMPHS2 - COMPUTER PROGRAMMING IN C++ -Dr.G.M.CARMEL VIGILA BAL UNIT WHAT IS C++: Introduction - tokens - keywords ~ identifiers and constants - declaration of variables - basic data types - user defined data types-derived data types - symbolic constants - operators in C++ -expressions and their type-hierarchy of arithmetic operators- scope resolution operator — declaring, initializing and modifying variables-special assignment operators - all control structures-structure of a simple C + program, Introduction to C++ C++ is an object oriented programming language. It was developed by Bjarne Stroustrup in 1979 at Bell Laboratories in Murray Hill, New Jersey. He initially called the new language "C with Classes." However, in 1983 the name was changed to C++. C++ is a superset of C. Stroustrup built C++ on the foundation of C, including all of C’s features, attributes, and benefits. Most of the features that Stroustrup added to C were designed to support object-oriented programming .These features comprise of classes, inheritance, function overloading and operator overloading. C++ has many other new features as well, including an improved approach to input/output (I/O) and a new way to write comments. C++ is used for developing applications such as editors, databases, personal file systems, networking utilities, and communication programs. Because C+ shares C’s efficiency, much high- performance systems software is constructed using C++. CH Tokens Smallest individual units in a program are known as Tokens. Tokens of C++ are keyword, identifiers, constants, strings, and operators. C++ keywords When a language is defined, one has to design a set of instructions to be used for communicating with the computer to carry out specific operations. The set of instructions which are used in programming, are called keywords. These are also known as reserved words of the language. They have a specific meaning for the C++ compiler and should be used for giving specific instructions to the computer. These words cannot be used for any other purpose, such as naming a variable. C+ is a case-sensitive language, and it requires that all keywords be in lowercase. C++ keywords are: asm auto bool break case catch char class const const_cast continue default delete do double dynamic_cast eke enum explicit export extern false float for friend goto if inline int long mutable namespace new operator private protected public register insert an assembly instruction declare a local variable declare a boolean variable break out of a loop a block of code in a switch statement handles exceptions from throw declare a character variable declare a class declare immutable data or functions that do not change data cast from const variables bypass iterations of a loop default handler in a case statement make memory available looping construct declare a double precision floating-point variable perform runtime casts alternate case for an if statement create enumeration types only use constructors when they exactly match allows template definitions to be separated from their declarations tell the compiler about variables defined elsewhere the boolean value of false declare a floating-point variable looping construct grant non-member function access to jump to a different part of the program execute code based off of the result of a test optimize calls to short functions declare a integer variable declare a long integer variable override a const variable partition the global namespace by defining a scope allocate dynamic memory for a new variable create overloaded operator functions declare private members of a class declare protected members of a class declare public members of a class request that a variable be optimized for speed reinterpret_cast change the type of a variable return short signed sizeof static static_cast struct return from a function declare a short integer variable modify variable type declarations return the size of a variable or type create permanent storage for a variable perform a nonpolymorphic cast define a new structure switch execute code based off of different possible values for a variable template create generic functions this a pointer to the current object throw throws an exception true the boolean value of true uy execute code that can throw an exception typedef create a new type name from an existing type typeid describes an object typename declare a class or undefined type union a structure that assigns multiple variables to the same memory location unsigned declare an unsigned integer variable using import complete or partial namespaces into the current scope virtual create a function that can be overridden by a derived class void declare functions or data with no associated data type volatile warn the compiler about variables that can be modified unexpectedly wehar_t declare a wide-character variable while looping construct Identifiers An identifier is a name assigned to a function, variable, or any other user-defined item. Identifiers can be from one to several characters long. An identifier is a name for a variable, constant, function, etc. It consists of a letter followed by any sequence of letters, digits, and underscores. Examples of valid identifiers: First_name, age, y2000, y2k Examples of invalid identifiers: 2000y Identifiers cannot have special characters in them. For example: X=Y, J-20, ~Ricky,*Michael are invalid identifiers. Rules for naming identifiers: + Variable names can start with any letter of the alphabet or an underscore. Next comes a letter, a digit, or an underscore. + Uppercase and lowercase are distinct. + C#+ keywords cannot be used as identifier. Data types Data type defines size and type of values that a variable can store along with the set of operations that can be performed on that variable. Data types are classified as + User Defined data types + Built in data types + Derived data types Data types in C++ int, char, float, double Function, Pointer C++ provides built-in data types that correspond to Structure, Union and Enumeration. C++ provides built-in data types that correspond to Array, Function and Pointer. CH provides built-in data types that correspond to integers, characters, floating-point values, and Boolean values. There are the seven basic data types in C++ as shown below: ‘Type Meaning Char wehart int float e000 ° Double © Bool © Void (character) holds 8-bit ASCII characters (Wide character) holds characters that are part of large character sets (Integer) represent integer numbers having no fractional part (floating point) stores real numbers in the range of about 3.4x10™* to 3.4x10™ with a precision of seven digits. (Double floating point) Stores real numbers in the range from 1.710 tol.7x10° with a precision of 15 digits. (Boolean) can have only two possible values: true and false. Valueless C+ allows certain of the basic types to have modifiers preceding them. A modifier alters the a ‘meaning of the base type so that it more precisely fits the needs of various situations. The data type ‘modifiers are: signed, unsigned, long and short Table 3.2. Size and range of C++ basic data types char 1 =128 to 127 unsigned char 1 0 to 255 signed char 1 ~128 10 127 int 2 — $2768 to 32767 unsigned int 2 0 to 65535 signed int 2 — 31768 to 32767 sshort int 2 — 31768 to 32767 unsigned short int 2 0 to 65595 ssigned short int 2 82768 to 32767 Jong int 4 ~2147489648 to 2147489647 ‘signed long int 4 2147489648 to 2147483647 unsigned long int 4 0 to 4294967296 float 4 34-38 to 3.4E+38 double 8 1.7E-308 to 1.7+308 long double 10 348-4932 to 1.1E+4932 This Table 3.2 shows all combinations of the basic data types and modifiers along with their size and range for a 16-bit word machine Variable A variable is a named area in memory used to store values during program execution, Variables are run time entities. A variable has a symbolic name and can be given a variety of values. When a variable is given a value, that value is actually placed in the memory space as ned. to the variable. All variables must be declared before they can be used. ‘The general form of a declaration is: type variable_ls; Here, type must be a valid data type plus any modifiers, and variable jst may consist of one or ‘more identifier names separated by commas. Here are some declarations: in ij short int si; unsigned int uis double balance, profit, loss; Constants Constants refer to fixed values that the program cannot alter. Constants can be of any of the basic data types. The way each constant is represented depends upon its type. Constants are also called literals. We can use keyword const prefix to declare constants with a specific type as follows: const type variableName = value; eg const int LENGTH = 10; Enumerated Types An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as values of the type. Each enumerator is a constant whose type is the enumeration. Creating an enumeration requires the use of the keyword enum. The general form of an enumeration type is: enum enum-name { list of names } var-list; Here, the enum-name is the enumeration's type name. The list of names is comma separated For example, the following code defines an enumeration of colors called color and the variable ¢ of type color. Finally, ¢ is assigned the value "blue". enum color { red, green, blue } =c; By default, the value of the first name is 0, the second name has the value 1 and the third has the value 2, and so on. But you can give a name, a specific value by adding an initializer. For example, in the following enumeration, green will have the value 5. enum color { red, green=5, blue }; Here, blue will have a value of 6 because each name will be one greater than the one that precedes it Operator An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in builtin operators. Generally, there are six type of operators: Arithmetical operators, Relational operators, Logical operators, Assignment operators, Conditional operators, Comma operator. Arithmetical operators Arithmetical operators +, -,*,/, and % are used to performs an arithmetic (numeric) operation. Operator Meaning + Addition : Subtraction * Muttiplication ! Division % Modulus ‘You can use the operators +, -, *, and / with both integral and floating-point data types. Modulus or remainder % operator is used only with the integral data type. Relational operators The relational operators are used to test the relation between two values. All relational operators are binary operators and therefore require two operands. A relational expression returns zero when the relation is false and a non-zero when it is true. The following table shows the relational operators. Relational Operators Meaning < Less than <= Less than ot equal to == Equal to > Greater than >: Greater than or equal to t= Not equal to Logical operators ‘The logical operators are used to combine one or more relational expression. The logical operators are Operators Meaning I OR && AND ! NOT Assignment operator ‘The assignment operator '=' is used for assigning a variable to a value. This operator takes the expression on its right-hand-side and places it into the variable on its left-hand-side. For example: m=5; ‘The operator takes the expression on the right, 5, and stores it in the variable on the left, m. 32; This code stores the value 32 in each of the three variables x, y, and z In addition to standard assignment operator shown above, C++ also support compound assignment operators. Compound Assignment Operators Operator Example Equivalent to +s At=2 A=A42 = A A=A-2 %= A% =2 A=A%2 Al=2 A=A/2 A*t=2 A=A*2 Increment and Decrement Operators C+ provides two special operators viz +4" and '~' for incrementing and decrementing the value of a variable by 1. The increment/decrement operator can be used with any type of variable but it cannot be used with any constant. Increment and decrement operators each have two forms, pre and post. ‘The syntax of the increment operator is: Pre-increment: ++variable Post-increment: variable H+ The syntax of the decrement operator is: Pre-decremen —variable Post-decrement: variable— In Prefix form first variable is first incremented/decremented, then evaluated In Postfix form first variable is first evaluated, then incremented / decremented, Conditional operator The conditional operator ?: is called ternary operator as it requires three operands. The format of the conditional operator is Conditional expression ? expression! : expression2; If the value of conditional expression is true then the expression! is evaluated, otherwise expression? is evaluated. int a=5,b= big =(a>b) 2a :b; ‘The condition evaluates to false, therefore big gets the value from b and it becomes 6. ‘The comma operator The comma operator gives left to right evaluation of expressions. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered. int a=1,b=2, i; #/ comma acts as separator, not as an operator i = (a, b); // stores b into i would first assign the value of a to i, and then assign value of b to variable i, So, at the end, variable i would contain the value 2. The sizeof operator ‘The sizeof operator can be used to find how many bytes are required for an object to store in memory. For example sizeof (char) returns | sizeof (float) returns 4 ‘Typecasting: ‘Typecasting is the concept of converting the value of one type into another type. For example, you might have a float that you need to use in a function that requires an integer. conversion: Impl Almost every compiler makes use of what is called automatic typecasting. It automatically converts, fone type into another type. If the compiler converts a type it will normally give a warning. For 9 example this warning: conversion from ‘double’ to ‘int’, possible loss of data. The problem with this is, that you get a warning (normally you want to compile without warnings and errors) and you are not in control. With control we mean, you did not decide to convert to another type, the compiler did. Also the possible loss of data could be unwanted. conversion: Expli The C++ language have ways to give you back control. This can be done with what is called an explicit conversion. Four typecast operators ‘The C+ language has four typecast operators: + static_cast + reinterpret_cast + const_cast + dynamic_cast ‘Type Conversion ‘The Type Conversion is that which automatically converts the one data type into another but remember we can store a kirge data type into the other. For example we can't store a float into int because a float is greater than int, When a user can convert the one data type into another,then it is called as the type casting. ‘The type Conversion is performed by the compiler but a casting is done by the user for example converting a float into int. When we use the Type Conversion then it is called the promotion. In the type casting when we convert a large data type into another then it is called as the demotion. When wwe use the type casting then we can loss some data. Control Structures Control structures allows to control the flow of program’s execution based on certain conditions C++ supports following basic control structures: 1) Selection Control structure 2) Loop Control structure 1) Selection Control structure: Selection Control structures allows to control the flow of program’s execution depending upon the state of a particular condition being true or false C++ supports two types of selection statements :if and switch. Condition operator (?) can also be used as 10 an alternative (o the if statement. A.1) IfStatement: ‘The syntax of an if statement in. C+ is: if(condition) { // statement(s) will execute if the condition is true 1 the condition evaluates to te, then the blk of code inside the ifttement will be executed it eValuates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed. ‘A.2) The if...else Statement The syntax is shown as: if(condition) { // statement(s) will execute if the condition is true } eke ( // statement(s) will execute if condition is false 1 If the condition evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed, A.3) it..else Ise Statement An if statement can be followed by an optional else if...clse statement, which is very useful to test various conditions using single if...eke if statement. ‘The Syntax is shown as: al if(condition 1) { (Executes when the condition 1 is true } ee if(condition 2) { (/ Executes when the condition 2 is true 1 eke if(condition 3) { // Executes when the condition 3 is true else { //executes when the none of the above condition is true. } Ad) Nested if Statement Itis always legal to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s), ‘The syntax for a nested if statement is as follows: if( condition 1) { // Executes when the condition 1 is true if(condition 2) 12 { 1/ Executes when the condition 2 is true } } B) Switch C++ has a built-in multiple-branch selection statement, called switch, which successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed. The general form of the switch statement is: switch (expression) { case constant! statement sequence break; case constant2: statement sequence break; case constant3: statement sequence break; default statement sequence } The expression must evaluate to a character or integer value. Floating-point expressions, for example, are not allowed. The value of expression is tested, in order, against the values of the constants specified in the case statements. When a match is found, the statement sequence 13 associated with that case is executed until the break statement or the end of the switch statement is reached. The default statement is executed if no matches are found. The default is optional and, if it is not present, no action takes place if all matches fail. The break statement is one of C:+'s jump statements, You can use it in loops as well as in the switch statement. When break is encountered in a switch, program execution "jumps" to the line of code following. the switch statement. 2) Loop control structures A loop statement allows us to execute a statement or group of statements multiple times. Loops or iterative statements tell the program to repeat a fragment of code several times or as long as a certain condition holds. C++ provides three convenient iterative statements: while, for, and do-while. while loop A while loop statement repeatedly executes a target statement as long as a given condition is true. It is an entry-controlled loop. ‘The syntax of a while loop in C++ is: while(condition) { statement(s); } Here, statement(s) may be a single statement or a block of statements. ‘The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true. After each execution of the Joop, the value of test expression is changed. When the condition becomes false, program control passes to the line immediately following. the loop. The do-while Loop The do-while loop differs from the while loop in that the condition is tested after the body of the loop. This assures that the program goes through the iteration at least once. It is an exit-controlled loop. do { statement(s); } while( condition); ‘The conditional expression appears at the end of the loop, so the statement(s) in the loop execute 14 once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again, This process repeats until the given condition becomes false, for Loop: A for loop is a repetition control structure that allows you (o efficiently write a Joop that needs to execute a specific number of times. The syntax of a for loop in C+ is: for (init; condition; increment ) { statement(s); 1 Here is the flow of control in a for loop: 1, The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears, 2. Next, the condition is evaluated. If itis true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. 3. After the body of the for loop executes, the flow of control jumps back up to the increment Statement, This statement allows you to update any C++ loop control variables. This statement can be left blank, as long as a semicolon appears after the condition, 4, The condition is now evaluated again. If it is true, the Joop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. Structure of A Simple C++ Program #include Hinclude int main) { cout<< “Simple C+ program without using class”; return 0; 15 1 Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the preprocessor. They are special lines interpreted before the compilation of the program itself begins. In this case, the directive #include , instructs the preprocessor to include a section of standard C++ code, known as header iostream that allows to perform standard input and output operations, such as writing the output of this program to the screen. The function named main is a special function in all C++ programs; it is the function called when the program is run. ‘The execution of all C++ programs begins with the main function, regardless of where the function is actually located within the code. The open brace ({) indicates the beginning of main’s function definition, and the closing brace (}) indicates its end. ‘The statement : cout<< “Simple C+ program without using class”; causes the string in quotation marks to be displayed on the screen. The identifier cout (pronounced asc out) denotes an object. It points to the standard output device namely the console monitor. The operator << is called insertion operator. It directs the string on its right to the object on its left. ‘The program ends with this statement: return 0; This causes zero to be returned to the calling process (which is usually the operating system). Returning zero indicates that the program terminated normally. Abnormal program termination should be signaled by returning a nonzero value. ‘The general structure of C++ program with classes is shown 1. Documentation Section 2. Preprocessor Directives or Compiler Directives Section (9 Link Section (ii) Definition Section 3. Global Declaration Section 4. Class declaration or definition 5. Main C++ program function called main () 16 UNIT-II: ARRAYS AND FUNCTIONS IN C++: ARRAYS Introduction: Anarray is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table Anarray is a collection of one or more values of the same type. Each value is called an clement of the array. The elements of the array share the same variable name but each element has its own unique index number (also known as a subscript) Anarray can be of any type, For example: int , float , char ete. An array is a variable that can store multiple values. For example, if we want to store 100 integers, we can create an array for it int data[ 100] Alll arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. First Element Last Element | | Numbers(0} | Numbers{1] | Numbers{2] | Numbers{3] Declaring Arrays: To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows — type arrayName [ arraySize |; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement — double balance[10}; 7 Here balance is a variable array which is sufficient to hoki up to 10 double numbers. Initializing Arrays: We can initialize an array in C either one by one or using a single statement as follows: double balance[5] = (1000.0, 2.0, 3.4, 7.0, 50.0}; The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. If we omit the size of the array, an array just big enough to hold the initialization is created, Therefore, if we write — double balance[ ] = {1000.0, 2.0, 3.4, 7.0, 50.0}; We will create exactly the same array as we did in the previous example. Following is an example to assign a single element of the array ~ balance{4] = 50.0; ‘The above statement assigns the 5" element in the array with a value of 50.0. Alll arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. ‘Shown below is the pictorial representation of the array we discussed above ~ balance include ‘int main () int n{ 10 J; /* nis an array of 10 integers */ int i / initialize elements of array nto 0 */ for (i =0; i < 10; i++ ) nf i]=i+ 100; /* setelement at location i toi + 100 */ } 18 /* output each array element's value */ for (j = 0: j < 10; j++) { printf("Element{%d] = %6a\n" j, nfl); } return 0; When the above code is compiled and executed, it produces the following result ~ Ekement[0] = 100 Element[1] = 101 Ekement[2] = 102 Ekement[3] = 103 Element{4] = 104 Element{5] = 105 Element{6] = 106 Element{7] = 107 Element{8] = Element[9] = 109 ‘Two Dimensional Arrays C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. Anarray of arrays is known as 2D array. The two dimensional (2D) array in C programming is also known as matrix. A matrix can be represented as a table of rows and columns. ‘This program demonstrates how to store the elements entered by user in a 2d array and how to display the elements of a two dimensional array. Hinclude- ‘int main() t ** 2D array declaration*/ int disp[2I(3): P*Counter variables for the oop*/ int i, js for(i-0; 2; i++) { for(-05<3;j+-4) { printf(’Enter value for displ%dl[%d}, i, Ds 19 scanf("%d", &displil{i)): I } ifDisplaying array elements printf(’"Two Dimensional array elements:\n"); for(i=O; i<2; i++) { for(j-053:j++) { printf("%d_", displilli): if(=2) { printf("\n"); Output: Enter value for disp{0]{0}:1 Enter value for displO}[1]2 Enter value for disp(0}(213 Enter value for disp{1}(0)4 Enter value for disp{1}(1):5 Enter value for disp[1][21:6 ‘Two Dimensional array elements: 123 456 Initialization of 2D Array There are two ways to initialize a two Dimensional arrays during declaration, int displ2][4] = { (10, 11, 12, 13), (14, 15, 16, 17) h 20 OR int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17}; Although both the above declarations are valid, better to use the first method as it is more readable, because we can visualize the rows and columns of 2D array in this method. ‘Things that you must consider while initializing a 2D array: We already know, when we initialize a normal array (or one dimensional array) during declaration, we need not to specify the size of it. However that’s not the case with 2D array, you must always specify the second dimension even if we are specifying elements during the declaration. Let’s understand this with the help of few examples — /* Valid declaration*/ int abe(2}[2] = (1, 2, 3.4} Valid declaration'/ int abe{ J[2] = (1, 2,34} Invalid declaration — you must specify second dimension*/ int abef I] = (1, 2.3.4} /* Invalid because of the same reason mentioned above*/ int abe(2]E] = (1, 2.3.4) Arrays of Strings Strings are actually one-dimensional array of characters terminated by a null character ‘0. Thus a null-terminated string contains the characters that comprise the string followed by a null, The following declaration and initialization create a string consisting of the word "Hello", To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello." TT, '0, 0}; If you follow the rule of array initialization then you can write the above statement as follows ~ char greeting|6] = {'H char greeting[] = "Hello"; Following is the memory presentation of the above defined string in C/C++ — 21 Index ° 1 2 3 4 s “rave Pete de fedefe| Adress [somes Toomer Tocnen | come ] sine | eee | Actually, you do not place the null character at the end of a string constant. The C compiler automatically plices the “\0' at the end of the string when it initializes the array. Let us try to print the above mentioned string ~ include int main () { char greeting[6] = {'H','e',"T, ', '0', 0}; printi(’Greeting message: %s\n", greeting ); return 0; 1 When the above code is compiled and executed, it produces the following result ~ Greeting message: Hello. 22 Functions Introduction: A function groups a number of program statements into a unit and gives it a name. This unit can then be invoked (called) from other parts of the program. The function's code is stored in only one place in memory, even though the function is executed many times in the course of the program’s execution. Functions help to reduce the program size when same set of instructions are to be executed again and again. Thus, a function is a block of statements that performs a specific task. If we are writing a C++ program and we need to perform a same task in that program more than once. In such case we have two options: a) Use the same set of statements every time we want to perform the task b) Create a function to perform that task, and just call it every time we need to perform that task. Using option (b) is a good practice and a good programmer always uses functions while writing code in C++. Why we need functions in C++: Functions are used because of following reasons — a) To improve the readability of code. b) Improves the reusability of the code, same function can be used in any program rather than writing the same code from scratch. c) Debugging of the code would be easier if you use functions, as errors are easy to be traced, d) Reduces the size of the code, duplicate set of statements are replaced by function calls. Types of functions: 1) Predefined standard library functions Standard library functions are also known as built-in functions. Functions such as puts(), gets(), printi(), scanf() etc are standard library functions. These functions are already defined in header files (files with .h extensions are called header files such as stdio.h), So we just call them whenever there is a need to use them. For example, printf() function is defined in header file so in order to use the printf() function, we need to include the header file in our program using #include . 2) User Defined functions The functions that we create in a program are known as user defined functions or in other words you can say that a function created by user is known as user defined function. 23 User Defined functions: Now we will learn how to create user defined functions and how to use them in C++ Programming, ‘A general function consists of three parts, namely, function declaration (or prototype), function definition and function call, Function declaration — prototype: ‘A function has to be declared before using it, in a manner similar to variables and constants. A function declaration tells the compiler about a function's name, return type, and parameters and how to call the function. The general form of a C++ function declaration is as follows: return-type function-name( argument-list ); The argument list contains the types and names of arguments that must be passed to the functions. Function definition: The function definition is the actual body of the function. The function definition consists of two parts namely, function header and function body. The general form of a C++ function definition is as follows: return-type function-name(argument-list) { body of the function } Here return-type: A function may return a value. The return-type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return-type is the keyword void. Function Name: This is the actual name of the function. Argument or Parameters: ‘A parameter is like a placeholder. When a function is invoked, we pass a value 24 to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body. The function body contains a collection of statements that define what the function does. Calling a Function = To use a function, we will have to call or invoke that function. To calll a function, we simply need to pass the required parameters along with function name, and if function returns a value, then we can store returned value. ‘Type of User-defined Functions in C++: There can be 4 different types of user-defined functions, they are: 1. Function with no arguments and no return value 2. Function with no arguments and a return value 3. Function with arguments and no return value 4, Function with arguments and a return value Below, we will discuss about all these types, along with program examples. 1.Function with no arguments and no return value: Such functions can be used to display information or they are completely dependent on user inputs. Below is an example of a function, which takes 2 numbers as input from user, and display which is the greater number. #include void greatNum(); _// function declaration int main() if greatNum(); _// function call return 0; y void greatNum() —_// function definition i int i, j; printf("Enter 2 numbers that you want to compare. scanf("%d%d", &i, &j); iti >)) { printf("The greater number is: %d", i); 25 } else it printf("The greater number is: %d", i); } y 2.Funetion with no arguments and a return valu We have modified the above example to make the function greatNum() return the number which is greater amongst the 2 input numbers. #include int greatNum(); _// function dectaration int main() { int result; result = greatNum(); _// funtion call printf("The greater number is: %d", result); return 0; J int greatNum() _// function definition { int i, j, greaterNum; printf("Enter 2 numbers that you want to compare. scant("%d%d", 8, &j); ifli> i) { greaterNum i else greaterNum } returning the result return greaterNum; y 3.Fun n with arguments and no return value: We are using the same function as example again and again, to demonstrate that to solve a problem there can be many different ways. 26 This time, we have modified the above example to make the function greatNum() take two int values as arguments, but it will not be returning anything. #include void greatNum(int a, int b); _// function declaration int main() { int i,j; printf(’Enter 2 numbers that you want to compare. scant("%d%d", 8, &j); greatNum(i,j); // function call return 0; } void greatNum(int x, int y) _// function definition i iflx > y) { printf("The greater number is: %d", x); } else { printf("The greater number is: %d", y); } : 4,Function with arguments and a return value: This is the best type, as this makes the function completely independent of inputs and outputs, and only the logic is defined inside the function body. #include int greatNum(int a, int b); _// function declaration int main() i! int i, j, result; printf("Enter 2 numbers that you want to compare.. scant("%d%d", &i, &j result = greatNum(i, j); —_// function call printf("The greater number is: %d", result); return 0; a7 int greatNum(int x, int y) _//funetion definition { if(x > y) { return x; } else { return y; } : 1) Function - Call by value method - In the call by value method the actual arguments are copied to the formal arguments, hence any operation performed by function on arguments doesn't affect actual parameters. 2) Function — Call by reference method — Unlike call by value, in this method, address of actual arguments (or parameters) is passed to the formal parameters, which means any operation performed on formal parameters affects the value of actual parameters. Function call by value is the default way of calling a function in C programming. Actual parameters: The parameters that appear in function calls. Formal parameters: The parameters that appear in function declarations. Inline Functions ‘An inline function is a function that is expanded inline at the point at which it is invoked, instead of actually being called. The reason that inline functions are an important addition to C++ is that they allow we to create very efficient code. Each time a normal function is called, a significant amount of overhead is generated by the calling and return mechanism. ‘A function can be defined as an inline function by prefixing the keyword inline to the function header. if a function cannot be inlined, it will simply be called as a normal function, One of the advantage of using function is to save memory space by making ‘common block for the code we need to execute many times. When compiler invoke / call a function, it takes extra time to execute such as jumping to the function definition, saving registers, passing value to argument and returning value to calling function. This extra time can be avoidable for large functions but for small functions we use inline function to save extra time. 28 Example: #includeciostream.h> inline int Add{int x,int y) { return x+y; } void main() { coute<"\n\tThe Sum is :" << Add(10,20); coute<"\n\tThe Sum is :" << Add(45,83); coute<"\nitThe Sum is :" << Add(27,48); } Output : The Sum is : 30 The Sum is : 98 The Sum is : 75 Reference variable A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable. To declare a reference variable or parameter, precede the variable's name with the & The syntax for declaring a reference variable is: datatype &Ref = variable name; Example int main() { int vart=10; ideclaring simple variable int &var2=vart; Jidectaring reference variable cout<<“\n value of var2 return 0; } << var2; 29 var? is a reference variable to vart.Hence, var2 is an alternate name to vart.This code prints the value of var2 exactly as that of var‘, Call by reference ‘Arguments can be passed to functions in one of two ways: using call-by-value or call-by-reference. When using call-by-value, a copy of the argument is passed to the function. Call-by-reference passes the address of the argument to the function. By default, C++ uses call-by-value, Provision of the reference variables in c++ permits us to pass parameter to the functions by reference. When we pass arguments by reference, the formal arguments in the called function become aliases to the actual arguments in the calling function. This means that when the function is working with its own arguments, it is actually working on the original data. Example #include #include void swap(int &x, int &y); J/tunetion declaration int main () if int a=10, b=20; cout << "Before swapping"< #include int sum (int p,int q,int r); double sum(int |\double m); float sum(float p.float q) int main() { cout<<'sum="<< sum(11,22,33); Nealls func cout<<'sum="<< sum(10,15.5); Uealls func2 cout<<'sum="<< sum(13.5,12.5); Wealls fune3 return 0; » int sum(int p,int q,int r) { tune’ return(a+b+c) } double sum(int I,double m) { dfunc2 return(l+m); } float sum (float p,float q) { sifune3 return(p+q); i Default arguments C++ allows a function to assign a parameter as default value when no argument 31 corresponding to that parameter is specified in a call to that function. The default value is specified in a manner syntactically similar to a variable initialization. All default parameters must be to the right of any parameters that don't have defaults. We cannot provide a default value to a particular argument in the middle of an argument list. When we create a function that has one or more default arguments, those arguments must be specified only once: either in the function's prototype or in the function's definition if the definition precedes the function's first use. Default arguments are useful if we don't want to go to the trouble of writing arguments that, for example, almost always have the same value. They are also useful in cases where, after a program is written, the programmer decides to increase the capability of a function by adding another argument. Using default arguments means that the existing function calls can continue to use the old number of arguments, while new function calls can use more. Example #include #include int sum(int a, int b=20) { retum( a +b); } int main () { int a = 100, b=200, result; result = sum(a, b); Mnere a=100 , b=200 cout << “Total value is :" << result << endl; result = sum(a); Iihere a=100 , b=20(using default value) cout << “Total value is :" << result << endl; return 0; } 32 bo Math Library Functions ‘The standard C++ supports many math functions that can be used for performing certain commonly used calculations. Most frequently used math library functions are summarized in Table 4.1. Table 4.1 Commonly used math library functions Rounds x to the smallest integer not lens than x ceil(8.1) ‘0 and ceiK-8.8) = 8.0 ‘Trigonometrie cosine of x (x in radians) ‘Trigonometric tangent of x (x in radians) note (‘me anrument varablon x and y are of type dowtle nd al he functions return cheats) ‘To use the math library functions, we must include the header file math.h in conventional (C++ and emath in ANSI C++. 33 Key Concepts aaah Using structures | Creating a class | Defining ae ae ce ‘anes | ie functions objects | Using objects | Inline member Storage of objects | Siatic data member functions | Arrays as class members | ‘ members | Static member functions | Using arrays of objects | Passing Ce 38 parameters | Making functions friendly to classes | Functions returning objects | member functions | Pointers to members | Using dereferencing operators | Local classes Introduction The most important feature of C++ is the “class”. Its significance is highlighted by the ‘Stroustrup initially gave the name °C with classes” to his new language. A class is an extens idea of structure used in C. It is a new way of creating and implementing a user-defined We shall discuss, in this chapter, the concept of class by first reviewing the traditioné found in C and then the ways in which classes can be designed, implemented and app __ C Structures Revisited 7 mange know that one of the unique features of the C la “Struct student { char name [20]; ~ int roll_number; float total marks; Scanned by TapScanner Classes and Objects 94 is re ‘welure name or structure tag, can be used to create variables of type student ble of type student and has three member variables as defined by the template. les can be accessed using the dot or period operator as follows: ble: A.roll_number = 999 lacks = 5) Structures can have arrays, pointers or structures as members, tions of C Structure Standard C does not allow the struct data type to be treated like built-in types. For example, sider the following structure: struct complex struct complex cl, c2, ¢3; @ complex numbers ct, c 2, and c 3 can easily be assigned values using the dot operator, but ‘cannot add two complex numbers or subtract one from the other. For example, cl + c2; in C. other important limitation of C structures is that they do not permit data hiding. Structure mem- can be directly accessed by the structure variables by any function anywhere in their scope. In words, the structure members are public members. to Structures orts all the features of structures as defined in C. But C++ has expanded its capabilities to suit its OOP philosophy. It attempts to bring the user-defined types as close as possible to data types, and also provides a facility to hide the data which is one of the main principles Inheritance, a mechanism by which one type can inherit characteristics from other types, is = civctire'GEaPS GEN Varistledarc!"inlEtPesT mates: h cance dectore some ie as ‘private’ so that they cannot be accessed directly by the external functions, structure names are stand-alone and can be used like any other type names. In other ve yond cise bacon to cise if euch varabis, For example, we tie cassedetanetiNes — e feudent ar // C#¥ declaration i ca lll Scanned by TapScanner 92 Object Oriented Progrannming with Cr’ this is an error in C. cei cnr en Feb detessty wr incr modticatons. Since class is Lane ad - ae oF most of the C++ programmers tend to use the structures eee on oe both the data and functions. Therefore, we will not discuss S tensions in another us || 53 Specifying a Class ‘A class is a way to bind the data and its associated functions together. It allows the data (and fing tions) to be hidden, if necessary, from external use. When defining a class, we are creating abstract data type that can be treated like any other built-in data type. Generally, a class speci has two parts: 1. Class declaration 2. Class function definitions The class declaration describes the type and scope of its members. The class function def describe how the class functions are implemented. The general form of a class declaration is: class cl { s_name private: variable declaration function declaration: Public: a variable declarations; function declaration; re public. The keywords py are followed by a colon, Scanned by TapScanner Classes and Objects 93 by default, all the members are private. Such a class is completely hidden from the Qulside world and does not serve any purpose. The variables declared inside the class are known as data members and the functions are known member functions. Only the member functions can have access to the private data members and te functions. However, the public members (both functions and data) can be accessed from ide the class. This is illustrated in Fig. 5.1. The binding of data and functions together into a le class-type variable is referred to as encapsulation Class No entry to Private area See ese Entry allowed to Public area Data hiding in classes iple Class Example I class declaration would look like: class item ‘ int number; // variables declaration float cost: // private by default public: void getdata(int a, float b); // functions declara void putdata (void): // using prototype ie W ends with semicolon usually give a class some meaningful name, such as item. This name now becomes a new identifier that can be used to declare instances of that class type. The class item contains two members and two function members. The data members are private by default while both the are public by declaration. The function getdata() can be used to assign values to the variables number and cost, and putdata() for displaying their values. These functions pro- only access to the data members from outside the class. This means that the data cannot be by any function that is not a member of the class item. Note that the functions are declared, 1ed. Actual function definitions will appear later in the program. The data members are usu- as private and the member functions as public. Figure 5.2 shows two different nota- by the OOP analysts to represent a class. Objects that the declaration of item as shown above does not define any objects of item but only wnaviney conta, Once ass hasbeen decea wecan crete verabiescrimany, the class name (like any other built-in type variable). For example, Scanned by TapScanner 24 Object Oriented Programming with C** ———_——_ i ee Class : ITEM [sets number | on putdata() DATA FUNCTIONS getdata() L putdata() (a) (b) [BEER] Representation ofa class item x; // memory for x is created creates a variable x of type item. In C++, the class variables are known as objects. Th called an object of type item. We may also deciare more than one object in one statement. x Ye Ze The declaration of an object is similar to that of a variable of any basic type. The memory space is allocated to an object at this stage. Note that class specification, like a provides only a template and does not create any memory space for the objects. Objects can also be created when a class is defined by placing their names it closing brace, as we do in the case of structures. That is to say, the definition class item ban D xvas Would create the objects x, y and z of type item. This practice is seldom followed Accessing Class Members As pointed out earlier, the private data of a r ony of that class. The main() cannot contain a sone pare 9 is the format for calling a member function: af " Scanned by TapScanner Classes and Objects 95 Similarly, the statement x.putdata(); would display the values of data members, Remember, a member function can be invoked only by using an object (of the same class). The statement like getdata (100, 75.5); has no meaning. Similarly, the statement x.number = 10} is also illegal. Although x is an object of the type item to which number belongs, the number (declared private) can be accessed only through a member function and not by the object directly. Itmay be recalled that objects communicate by sending and receiving messages. This is achieved through the member functions. For example, sends @ message to the object x requesting it to display its contents. A variable declared as public can be accessed by the objects directly. Example: class xyz "twee int yz public: int 2; ne // error, x is private // OK, z is public nore: The use of data in this manner defeats the very idea of data hiding and therefore should be avoided. — | 5.4 Defining Member Functions || Member functions can be defined in two places: * Outside the class definition. + Inside the class definition. Scanned by TapScanner 96 Object Oriented Programming with ** that, irrespective of the place of defini , the code for the function body would be i difference in the way the function header is define in this section. tion, the function should perform the s identical in both the cases. However, 14, Both these approaches are discu Outside the Class Definition lared inside a class have to be defined separately outside the tions. They should have a function header, like the normal funct a rt the old version of function definition, the ANS/ n header. ‘Member functions that are dec! ‘Their definitions are very much function body. Since C++ does not SUPPO' form must be used for defining the functio stween a member function and a normal function is that a label’ in the header. This ‘label’ tells the co | form of a member function definition is: An important difference bet tion incorporates a membership ‘identity class the function belongs to. The general [eturn-type class-name :: function-name (argument declaration) oe label class-name :: tells the compiler that the function class-name. That is, the i ae hens ee Saal cea aps econ falls aa For instance, consider the member functions getdata() and putdata() as discussed ab may be coded as follows: % using namespace std; class item "int number; // private by default : float cost; // private by default publi . void getdata(int a, float b); // prototype declaration, // to be defined // Function defined inside class void putdata (void) { “\n" cout << “number :” << number << “\n"; " << cost << “\n"; cout << “cost // use membership labe} (Conta.) Scanned by TapScanner ir I) private variables ear 1) directly used mb ae Main Program. ind c 1/ create object x » ee Agra cout << “\nobject x x-gerdata(100, 299.95); x.putdata(); item yy cout << “\nobject y” << *\n"; sot pale’ Y-getdata(200, 175.50) ; y-putdata(); rotund to both the variables. Note the use of statements such as number = a; function definition of getdata(). This ‘hows that the member functions can have d data items, The member functi ion putdata inline function. This \) has been defined inside the class ang therefore b unction displays the values of the private variables number and ¢ "/ Gteates' a ttee oe objects Of Program 5.4: Scarined by TapScanner Classes and Objects 99 | For the sake of illustration we have shown one member function as inline and the other as an | ixternal’ member function, Both can be defined as inline or external functions. 5.6 Making an Outside Function Inline | Ine of the objectives of OOP is to separate the details of implementation from the class definition. It s therefore good practice to define the member functions outside the class. fe can define a member function outside the class definition and still make it inline by just using 3@ qualifier Inline in the header line of function definition. Example: class item { public: void getdata(int a, float b); // declaration \y dnline void item : { getdata(int a, float b) // definition number = a; cost = ‘operator. However, there is an exception to this. A member function can be called by name inside another member function of the same class. This is known as nesting of functions, Program 5.2 illustrates this feature. ‘ Nesting of Member Functions Scanned by TapScanner 5 Biuary seebers 126K Soe nt of the above bi: ‘nary number Scanned by TapScanner Scanned by TapScanner 102 Object Orfenteet Programming with C++ Serfay Variable af } deciared as a private member of the class array can be used Init (RENEE functions, like any other array variable. We can perform any operations on it For i Inthe above class definition, the member function setval() sets the values of elements of the may Al], and display() function displays the values. Similarly, we may u other member functions tg perform any other operations on the array values * Letus consider a shopping ist of items for which we place an order with a dealer every month. Tha: Istincludes details such as the code number and price of each item. We would like to perform: such a8 adding an iter to the list, deleting an item from the list and printing the total value of the Program 5.3 shows how these operations are implemented using a class with arrays as data : int tm) 7 float itemPrice[m}; b> -intlcomma! at ‘public: d CNT (vo: = 07 i i haan, 0) // initializes count to 0 splaySum (void) ; (void); SsplaylItems (void) ; Scanned by TapScanner Classes and Objects 103 Scanned by TapScanner Delete an item + Display all items + Quit What is your option?! Enter item code :111 Enter item cost :100 do the following; Enter ‘Add an item : Display total value 1 Delete an item 4: Display all items 5: Quit What is your option? item code :222 “item cost :200 an do the following; Enter app an item s total value ete an item splay all items Scanned by TapScanner Classes and Objects 105 an do the following; appropriate number Add an item Display total value 3: Delete an item Display all items What is your option?4 Price 100 rs ° Display all items + What is your option?5 Srore: The program uses two arrays, namely itemCode[ ] to hold the code number of tems and itemPricef } to nold tne pnces. A third data member count is used to keep a record of items in the list The program uses 2 totai of ifour functions to implement the operations to be performed on the list. The statement const m= 50; defines the size of the array members. The first function CNT() simply sets the variable count to zero. The second function getitem() gets the item code and the item price interactively and assigns them to the array members itemCode[count] and itemPrice[count]. Note that inside this function count is incremented after the assignment operation is over. The function displaySum( ) first evaluates the total vaiue of the order and then prints the value. The fourth function removes) deletes a given item from tne ist. It Uses the item code to locate it in the list and sets the price to zero indicating that the item is not ‘active’ in the list. Lastly, the function displayltems( ) displays all the items in the list The program implements all the tasks using a menu-based user interface. | 5.10 Memory Allocation for Objects | We have stated that the memory space for objects is allocated when they are declared and not wnen the class is specified. This statement is only partly true. Actually. the member functions are created and placed in the memory space only once when they are defined as a part of a class specification Since all the objects belonging to that class use the same member functions, no separate space is allocated for member functions when the objects are created. Only space for member variables is allocated separately for each object. Separate memory locations for the objects are essential, because the member variables will hod diferent data values for different objects. This is shown in Fig. 5.3 Scanned by TapScanner 06 Object Oriented Programming with C+* ‘Common for all objects member function 1 member function 2 ———] memory created when functions defined Object 1 Object 2 Object 3 member variable 1 member variabie 1 member variable 1 member variable 2 member variable 2 member variable 2 memory created when objects defined Object of memory : oR tpa me, | 5.11 Static Data Members — A data member of a class can be qualified as static. The : . The properties of a static member ‘similar to that of a C static variable, A i Of a C static variable. static member variable ‘has certain special ae gee + Its initialized to zero when the first. * Only one copy of that member is created that class, no matter how many objects a * {tis visible only within the class, but its i Object of is class is created. No other for the entire class anid is. re created, Shared by Scanned by TapScanner Scanned by TapScanner 408 Object Oriented Programming with C** tbe defined outside the : ic member variable must ‘ ition. Soar ae stored separately rather than, Mie see ny because the static data members ae st on sonar r Pec eres ty are associated with the class itself ra of an object. Since they ject, fare also known as class variables. ols are created, The count is ariable count is initialized to zero when the Pte peptic | Be ces the data is read into an object. Since the 0 Oo ae ene ee Cinceriented three times. Because there ce ts i ihieyed. Fea ct pci iI| the three output statements cause the value three objects, al how a static variable is used by the objects ee Object 2 Object 3 Be number number n wn 200 300 (common to all three objects) Sharing of a static data member variables are like non-inline member fur , j inctions as they are declared in a class 1ed in the source file. While defining a static variable, some initial value can als Variable. For instance, the following definiti ion gives count the initial value 10, int item count = 10; smember variable, we can also have statle member functions. has the following properties: : Scanned by TapScanner Classes and Objects 5 tlustrates the implementation of these characteristics. The statie func ent) splays ne number of objects created til thal moment. A count of number of objects created intained by the statie variable count, a ; function shewcede() displays the code number of each object. Static Member Function Scanned by TapScanner Programming with C++ @bject number: @bject 1 object // code is not static |) 5.13 Arrays of Objects We know that an array can be of any data type including struct. Similarly, we can also of variables that are of the type class. Such variables are called arrays of objects. Jowing class definition: lass employee ehar name (30); float age; publi data (void); ata (void); 7 identifier employee is a user-defined data type and can be used to create categories of the employees. Example: manager [3]; // array of manager // array of foremai iimexe ogee r 2 Scanned by TapScanner Classes and Objects 140 _ wil display the data of the ith element of the array manager. That is, this statement requests the [object manager{i] to invoke the member function putdata() __Anarray of objects is stored inside the memory in the same way as a multi-dimens ray manager 's represented in Fig. 5.5. Note that only the space for data items of t led. Member functions are stored separately and will be used by all the objects. name ‘manager{0] age name manager{1}, age pe name manager[2} age cs *, Storage of data itemis of an object array am 5.6 illustrates the use of object arrays. (Contd Scanned by TapScanner it << “Age: ” << age << “\n”; const int size=3; int main() ‘ employee manager (size); for(int in0; i using namespace std; class ABC; // Forward declaration int x; public: void setvalue(int i) {x = i} friend void max (XYZ, ABC); class ABC { int a; publ void setvalue(int i) {a = i;} friend void max (XYZ, ABC); Mf = iy Woid max (XYZ m, ABC n) // Definition of friend ‘ if (m.x >= n.a) cout << m.x; else cout << nay } Me r int main) t ABC abc; abe.setvalue (10); XYZ xyzi xyz.setvalue (20); kh k max(xyz, abc); cd return 0; , Scanned by TapScanner 118 Object Oriented Programming wih Co is ‘of Program 5.9 would be: has arguments from both XYZ and ABC. Wher the funalon aga .dge the presence of ABC, first time, the compiler wil not acknowler elass ABC; ‘Tiss known as Yorward' declaration, ‘As pointed out earlier, a friend function can be called by reference. In this case, local cop object is passed and the called objects are not made. Instead, a pointer fo the address of thi irectly works on the actual object used in the call. This method can be used to alter the values of the private members of a class. Ri ing the values of private members is against the basic principles of data hiding, It should be when absolutely necessary. Program 5.10 shows how to use a common friend function to exchange the private valli classes. The function is called by reference. ean eden int valuel; oid indata(int a) (valuel = a;} | displé Scanned by TapScanner Scanned by TapScanner Scanned by TapScanner Scanned by TapScanner dject Oriented Programming with C++ mul(int, int) const; le get_balance() const; = get) he qualifier const is appended to the function prototypes (in both declaration and definition), Ty ‘compiler will generate an error message if such functions try to alter the data values. 5.18 Pointers to Members | Itis possible to take the address of a member of a class and assign it to a pointer. The address of member can be obiained by applying the operator & to 2 ‘fully qualified” class member name. A member pointer can be declared using the operator ::* with the class name. For example, given class class A { private: int m public: void show(); We can define a pointer to the member m as follows: nt Ar:® 5 a The ip pointer created thus acts like a class member in that it must b e invoked with a class object, In the statement above, the phrase A::* means “pointer-to-member of A class". The phrase &A:m ‘means the “address of the m member of A class”. Remember, the following statement is not valid: // won't work This is because m is not simply an int type data. It has ‘the class to which it bel meaning only when it is associated longs. The scope operator must be applied to both the pointer // display // same as above << ‘/ ap is pointer to op. arr to object a ~~ tp: 4! display m.. a // same as above Scanned by TapScanner Sign pointers to member =a ree +* pointer-to-member function) bject ->* pointer-ro-member func Scanned by TapScanner 424 Object Oriented Programming with C** The output of Program 5.12 would be | 5.19 Local Classes j Classes can be defined and used inside a function or a block. Such classes are callled local .ed and used inside a functior lock, Such clas: lasses can be defi Examp nae local class class student I Toca ( lent sia); rota! lasses can use global variables (declared above the function) and static variables ded inside the function but cannot use automatic local variables. The global variables should be used with the scope operator (::). Member functions must be defined insi members of a local class. However, ae Scanned by TapScanner Classes and Objects 125 LJ Tne memory space for the objects is allocated when they are declared. Space for member variables 's allocated separately for each object, but no separate space is allocated for mem- ver functions. Gi A data member of a class can be declared as a static and is normally used to maintain val- tues common to the entire class, The static member variables must be defined outside the class. 1 Asiatic member function can have access to the static members declared in the same class and can be called using the class name. U C++ allows us to have arrays of objects. C1 We may use objects as function arguments. 1 A function declared as a friend is not in the scope of the class to which it has been declared as friend. It has full access to the private members of the class. 2 A function can also return an object. 2 Ifa member function does not alter any data in the class, then we may declare it as a const member function, The keyword const is appended to the function prototype. C Itis also possible to define and use a class inside a function. Such a class is called a local class Key Terms abstract data type | arrays of objects | class | class declaration | class members | class variables | const member functions | data hiding | data members | dereferencing operator | dot operator | elements | encapsulation | friend functions | inheritance | inline functions | local class | member functions | nesting of member functions | objects | pass-by-reference | pass-by-value | period operator | private | prototype | public | scope operator | scope resolution | static data members | static member functions | static variables | struct | structure | structure members | structure name | structure tag | template Review Questions | $1 How do structures in C and C++ differ? 82 What is a class? How does it accomplish data hiding? 53 How does a C++ structure differ from a C++ class? 54 What are objects? How are they created? 55 How is a member function of a class defined? Scanned by TapScanner 126 Object Oriented Programming with C++ 58 59 540 sat 52 Debugging Exercises ‘a member function of a class and an outside funetion they distinguished? If no, give reasons member functions in the following) tuse the same function name for same program file? If yes, how are the mechanism of accessing data members and cases: {a} Inside the main program. {b) Inside a member function of the same class. (6) Inside a member function of another class. When do we declare a member of a class static? What is a friend function? What are the merits and demerits of using friend functions? Can we pass class objects as function arguments? Explain with the help of an example. State whether the following statements are TRUE or FALSE. {a} Data items in a class must always be private. (b) A function designed as private is accessible only to member functions of that class. (c)_ A function designed as public can be accessed like any other ordinary functions. (@) Member functions defined inside a class specifier become inline functions by dt (e) Classes can bring together all aspects of an entity in one place. (Class members are public by default. (9) Friend functions have access to only public members of a class. (h) An entire class can be made a friend of another class. ()) Functions cannot return class objects. () Data members can be initialized inside class specifier. \dentify the error in the following program. finclude struct Room j on int width; int length; wold setValue(int w, int 1) width = w; length = 1; ) iB void main() { Room ob3Room; objR etval : jRoom.setValue (12, 1,4); Ic Kent the error in the following program, Winelude class Room ( Scanned by TapScanner 53 54 id width, height; setValue(int w, int hy width = ws height = Me void main() ( Room objRoom; objRoom.width = 12; ) Identify the error in the following program. #include class Ttem { private: static int count; public: Ttem() ( count++; ) int getCount() ( return count; ) int* getCountaddress () ( .return count; + ) 3 int Item::count = 0 void main() { Item objItem1; Item objItem2; cout << objIteml.getCount() << \'F cout << objItem2.getCount () << ° 'F cout << objIteml.getCountaddress() << * "7 cout << objitem2.getCountAddress() << ‘+ ) \dentify the error in the following program. finclude class staticFunction Classes and Object| Scanned by TapScanner "void displayCount () : { cout << count; } Me int staticFunction::count = 10; void main() include class Length 4 int feet; float inches; public: seat) Scanned by TapScanner Classes and Objects 4 at getInches () return inches; d main) Length objLengthi; Length objLengthi(5, 6.5); objLengthi = objLength1 addLength (objLength2) ; cout << objLengthl.getFeet() << * '; cout << objLengthl.getInches() <<‘ "; 56 _ Identify the error in the following program. #include class Room; void Area() { int width, height; class Room ( int width, height; public: void setValue(int w, int h) { width = height = h; , void displayValues() { cout << (float)width << ‘' << (float)height; ; Ve Room objRoom! ; objRooml.setValue(12, 8); objRooml .displayValues () 7 ) void main() ( Area(); Room objRoom2; Programming Exercises 51 Define a class to represent a bank account. Include the following members: Data members 1. Name of the depositor 2. Account number Scanned by TapScanner 130 52 53 54 55 56 Object Oriented Programming with C++ 3. Type of account 4. Balance amount in the account Member functions 4. To assign initial values 2. To deposit an amount 3, To withdraw an amount after checking the balance 4, To display name and balance Write a main program to test the program. (eed) Write a class to represent a vector (a series of float values). Include member functions te pee form the following tasks (a) To create the vector (b) To modify the value of a given element (c) To muttiply by a scalar value (d)_ To display the vector in the form (10, 20, 30, ...) Write a program to test your class. Modify the class and the program of Exercise 5.11 for handling 10 customers. (Eia) Modify the class and program of Exercise 5.12 such that the program would be able to add twe vectors and display the resultant vector. (Note that we can pass objects as function arse ments.) Create two classes DM and DB which store the value of distances. DM stores distances & metres and centimetres and DB in feet and inches. Write a program that can read values for the class objects and add one object of DM with another object of DB. ele} Use a friend function to carry out the addition operation. The obj t ject that stores the results be a DM object or DB object, depending on the units in which the results are required a The display should be in the format of feet and inches : sos cea or metres and centimetres depending 9° j that receives two mat je relums a new matrix object containing their multiplication result os a? oe ‘ Scanned by TapScanner itsett when ts creme + that oe membor function called the destructor / constructors | 6.2 to Initialize the objects of ig | oso isk is 10 Initiale He eee OF Sag say mem tana" WOE ET, “re constructor is Invoked veg A constructor is a ‘speck ras HB Myo Hecause HL COMSKUCK hy od i name Is the special bec nse te na vs cl its associated ¢ of the class. 98 is cre abject of data members 5 follows: a constructor is dectared and defined as follo ith a constructor class integer int m nF an }/ constructor declared integer (void) defined }/ constructor \e defined above, it is guaranteed that an op, the declaration When @ class contains a constructor like the on created by the class will be initialized automatically. For example, intl; // object intl created ales the object int of type integer but also initializes its data members m and ntoz: .ed fo write any statement to invoke the constructor function (as we do with the nom tions). If a ‘normal’ member function is defined for zero initialization, we would nest nvoke this function for each of the objects separately. This would be very inconvenient, ifthe 2 large number of objects A constructor that accepts no parameters is called the default constructor. The default consivt* for class A is A::A(). Ifno such constructor is defined, then the compiler supplies a default construc Therefore a statement such as ievokes the default constructor ofthe compiler to create the-object i" — Constructors and Destructors 133 the consttucior functions have some spectal charactaristica, These are + They should be dectarnd iy the public section + They ato invoked automatically when the objects ara created They do No! have vetul types, not even vold and therefore, and they cannot return values, + They cannot be inhentod, though # derived class can call the base class constructor. Line offer Cr¢ functions, they ean have default arguments. Consttuclors Cannot be virtual. (Meaning of virtual will be discussed later in Chapter 9.) + We cannot refer to their addressos, Av chest wilh @ eonsttuctor (or destructor) cannot be used as a member of a union. Tey make implicit calls to the operators new and delete when memory allocation is required Jemember, when @ constructor is declared for a class, initialization of the class objects becomes: mandatory | 63 Pararmstetized Constructors q =r integer(), defined above, initializes the data members of all the objects to zero. Mey Ge necessary to initialize the various data elements of different objects when they are created. C++ permits us to achieve this objective by passing swructor funetion when the objects are created. The constructors that can take integer %, dnt yhe /1 parameterized constructor been parameturized, the abject dectaration statement such as Mey Oot work, Wee ener pass thes iil vale sas arqumonts, ‘Rivet is declared. This * othe constructor function when an an be don in two ways * By calling the constructor exphcily * Byccaliing the constructor implicitly 134 Object Onentod Programming will! C*" J yethod: The following declaration tustrates the frst Do integer int) rnteger (Or Wore a he values 0 an This statement creates an integer abject intt and passes | F100 10 it thy My is implemented as follows: a Ae ita // implicit call integer int1(0, Z This method, sometimes called the shorthand method, is used very often as itis shogy, , better and is easy to implement. 3 Remember, when the constructor is parameterized, we must provide appropriate argue, funti, the constructor. Program 6.1 demonstrates the passing of arguments to the constructor // constructor define HE, 1943 5 a ints 1 her BSE roe se GNEL dic eet Np pp OF Called implicit Y ici! a a constructor called lL non t int2.dicn : ay Ole display); \nes return 0; SF 496 Odject Onented Programming wil!" sictors ina Class | 64 Yptultiple Constr | So far we have used two kinds of constructors They are Ue aegunent jos tho data values and NO VAIUES ATE pagen, > constructor itself suppl ase, the funcl ors i se, the srogram In the second ci to use both these construc! Hon cal passes the Appropriate Vales frpy ys io same ass. FOr &xAmIO, we cou gu 4 yi constructor 1 // constructor 2 // constructor 3 nese constructors for an Integer object. The first constructor receives no ap vos two integer arguments and the third receives one integer object asx s. the second receiv the declaration ‘oke the first constructor and set both m and n of I1 to zero. The statement ly Inve second constructor which will initialize the data members m and n of 12 to 20 and ely. Finally, the statement ¢ the third constructor which copies the values of 12 into 13. In other words, it sets the ve clement of [3 to the velue of the corresponding data element of 12. As mentioned ea < the copy constructor. We leaned in Chapter 4 that the process ofS by two or more functions is referred to as function overloading. Similarly, wher uclor function is defined in a class, we say thal the constructor is overloaded. tor is calle us¢ of overloaded constructors. “Constructors with Default Arguments ble to define constructors with default arguments. For example, the constructor com, iared as follows: real, float imag=0)+ {t value of the argument imag is zero. Then, the statement to the real variable and 0.0 to imag (by default). However, the statement real and 3.0 to imag. The actual parameter, when specified, overrides the dela! e¢ out earlier, the missing arguments must be the trailing ones. en! to distinguish between the default constructor A::A() and the default argument (int = 0). The default argument constructor can be called with either one argument” VCopy Constructor | ay mentioned about the copy constructor in Sec. 6.3. We used the copy constructor metly yererence Noni abu. =a as one of the overloaded constructors. < eariier, a copy constructor is used to declare and initialize an object from another object. ‘atement . uncaton call > Maina uUNcti On: odject [2 and at the same time initialize it to the values of 11. Another form of this 142 Object Onented Programming with C1" cay Po ) epryyg yp, OP) sonstrie The process of initializing through @ copy ¢ nstrt the statement ctor Is know 08 COPY Iiliatzoiny, ae) he mobo prerr a wera ceey cond 6 objects, 3 will not myoke the copy consinuctor, However, if 1 and ae rae jiatemeny 18 i simply assigns the values of 11 to 12, member-by-member, is is the task of the Over aden men: operator(=) We shail see more about this later. «4. com conetryctor takes a reference to an object of the same class a6 ilSelf 88 an argu, wpe of constructing and using a copy COnstTUCIOT aS SHOWN in Progra, Oran er @ simple @) Program 6.4 ‘ * UNIT IV—- OPERATOR OVERLOADIN¢ , INHERITANCE AND POINTERS OPERATOR OVERLOADING Introduction: We can redefine or overload most of the built-in operators in C+. Overloaded operators are functions with special function name, with keyword operator followed by the symbol for the operator already exist Defining Operator overloading ‘The general form of an operator function is : Return type class name :: operator op (arg list) { Function body } Here return type is the type of value returned by the specified operation and op is the operator being overloaded. The op is preceded by the keyword operator. Operator is the function name. Operator functions must be either member functions or friend functions. A basic difference between them is that a friend function will have only one argument for unary operators and two for binary operators, while a member function has no arguments for unary operators and only one for binary operators . Arguments may be passed either by value or by reference. Operator functions are declared in the class using prototypes as follows: vector operator (vector); / vector addition vector operator (); unary minus friend vector operator (vector, vector); _//vector addition friend vector operator- (vector unary minus vector operator- (vector &a); J/subtraction int operator==(vector); comparision friend int operator==(vector, vector) //comparision ‘The process of overloading involve the following steps: 1. Create a class that defines the data type that is to be used in the overloading operation. 2, Declare the operator function operator op() in the public part of the class. It may be either a member function or a friend function. 3. Define the operator function to implement the required operations. Overloaded operator functions can be invoked by expressions such as opx for unary operators -x 86 and x op y for binary operators. x-y op x would be interpreted as operator op (x) for friend functions. Overloading unary operators: Operators that operates with single operand (valies or expressions) are unary operators. eg + Let us consider the unary minus operator. A minus operator when used as a unary, takes just one operand.. This operator changes the sign of an operand when applied to a basic data item, ‘The unary minus when applied to an object should change the sign of each of its data items. Program for Overloading unary minus +Hinclude class space { int x; int y; int 7; public: void getdata(int a, int b, int c); void display; void operator —();//overload unary minus k void space : getdata(int a, int b, int c) y=b; Z=6 } void space = display ) { cout<< x << coute< yc 75 couts< 2 <<" \n" 5 } void space : operator — () { X=-X ,: } int main( ) t space S; S. getdata( 10, -20, 30); 87 couts< “S S. display( ); -8; 1 activates operator ~ () function cout<<"-$ : 8. display( ); return 0; } Output S: 10, -20, 30 $ 5-10, 20, -30 Overloading Binary Operators: ‘The functional notation can be expressed as C=A+B; // arithmetic notation by overloading the + operator using an operator+() function. Overloading + operator Hinclude class complex { float x; real part floaty; imaginary part public: complex() —_// constructor 1 } complex (float real, float imag) —_// contructor 2 { x=real y= imag; } complex operator (complex ); void display; k complex. comple! { complex temp; /I temporary temp. x = x+0.x; Jifloat additions temp. y =ysc.y; return (temp); } operator +(complex c) 88 void complex =: display() { COUK< x << 47" class B { int a; Liprivate, not inheritance publie: int bs // public, ready for inheritance set_ab(); int get_a(void); show_a(void); class D : public B public derivation { int 3 publ void mul(void); void display(void); k void B :: set_ab(void) return a; } void B :: show_a() { cout<<“a=“< class B t int a; private, not inheritance public: int b; ——_// public, ready for inheritance 96 void get_ab0; int get_a(void); void show_a(void); h class D : private B (iprivate inheritance { int ¢; public: void mul(void); void display(void) k void B :: get_ab(void) { cout<<“Enter values fora and b: cin>>a>>b; 3 int Bs: get_a() i return a; } void { show_aQ) cout<<“a=“< class student { protected: int rollnumber; public: void getnumber(int); void putnumber(); k void student :: getnumber(int a) { rollnumber = } void student :: putnumber() { cout<<*Roll Number: “ < class M i protected: int m; public: void getm(int); protected: int n; public void getn(int); k class P : public M, public N 1 public: void display(); } void M :: getm(int x) void N :: getn(int y) { n=y; 102 Void P :: display) { cout<<“m=“< class student { protected: int rollnumber; public: void getnumbertint); void putnumber(); k void student :: getnumber(int a) { rollnumber = 3; } void student :: putnumber() { cout<<*Roll Number: “< ‘Hinclude int main() ( int myarray(5] = {2, 4,6, 8,10}; int® myptr; myptr = myarray; cout<<"First element in the array: <. 111 UNIT V- MANAGING CONSOLE I/O OPERATIONS C++ Streams A stream is a sequence of bytes. It acts either as a source from which the input data can be obtained or as a destination to which the output data can be sent. The source stream that provides data to the program is called the input stream and the destination stream that receives output from the program is called the output stream. A program extracts the bytes from an input stream and inserts bytes into an output stream as illustrated in Fig, INPUTSTREAM Extraction from: input stream Ceca OUTPUTSTREAM Cd Insertion into ‘output stream Data streams ‘The data in the input stream can come from the keyboard or any other storage device. Similarly, the data in the output stream can go to the sereen or any other storage device. A stream acts as an interface between the program and the inpul/ output device. Cin represents the input stream connected to the standard input device(keyboard) and cout represents the output stream connected to the standard output device(screen) C++ Stream classes The C++ VO system contains a hierarchy of classes that are used to define various streams to deal with both the console and disk files. These classes are called stream classes. Fig shows the hierarchy of the stream classes used for input and output operations with the console unit. These classes are declared in the header file iostream. This file should be included in all the programs that communicate with the console unit 112 Stream classes for console I/O operations input IOS is the base class for istream(input stream) and ostream(output stream) which are inturn, base classes for iostream(input/output stream). The class IOS is declared as the virtual base ‘class so that only one copy of its members are inherited by the stream. Unformatted I/O operations Overloaded operators >> and << ‘The >> operator is overloaded jin the istream class and << is overloaded in the ostream class. The following is the general format for reading data from the keyboard. cin>>variable 1>>variable2>>....>>variableN; variablel, variable2.... are valid C++ variable names that have been declared already. This statement will cause the computer to stop the execution and Jook for input data from the keyboard. The input data for this statement woul be datal data? ........datan 113 ‘The input data are separated by white spaces and should match the type of variable in the cin list, ‘The operator >> reads the data character by character and assigns it to the indicated location. The reading for a variable will be terminated at the encounter of a white space or a character that does not match the destination type. For eg. Int code; cin>>code; Suppose the following data is given as input: 4258D ‘The operator will read the characters upto 8 and the value 4258 is assigned to code. The character D remains in the input stream and will be input to the next cin statement. ‘The general form for displaying data on the screen is cout<< item1< int main() t int count= char ¢; cout<<“INPUT TEXT\n”; cin.get(c); while ( { cout.put(c); not equal to count++; cin.get(c)s } cout<<“\nNumber of characters="< This input will be read correctly and assigned to the character array name. Let us suppose the input is as follows. Object Oriented Programming In this case, the input will be terminated after reading the following 19 characters. Object Oriented Pro ‘The two blank spaces contained in the string are also taken into account, #include int main() { int size=20; char city{20}; cout<<“Enter eity name: \n"; cin>>city; New Delhi cout<<“city name:”< #include int main() { char* string char* string2="Program int m=strlen(string1); string length ofstr1 3 int n=strlen(string2); for(int i=1; i0; i { cout. write (string2,i); cout<<*\n"; y Heoncatenating, strings cout. write (string 1 ,m).write(string2, n); cout<<“\n"; return 0; } P pe pro prog progr progra program programm programm programmin programmin programmin programm programm program progra progr prog pro 17 pe P C++ Programming Formatted console I/O operations C++ supports a number of features that could be used for formatting the output. These features include: * fos class functions and flags * Manipulators * User-defined output functions ‘The ios class contains a large number of member functions that would help us to format the output in a number of ways. 10s format functions Funetion Task width) | To specify the required field size for displaying an output value precision() | To specify the number of digits to be displayed after the decimal point of a float value fill) To specify a character that is used to fill the unused portion of a field setf) To specify format flags that can control the form of output display (such as left- justification and right-justification) ‘unsetf) | To clear the flags specified Manipulators are special functions that can be included in the I/O statements to alter the format parameters of a stream. Table shows some important manipulator functions that are frequently used. To access these manipulators, the file iomanip should be included in the program. Manipulators Manipulators Equivalent ios function Setw() Width) Setprecision(), Precision() Set fill Fill, Setiosflags() Setfl) Resetiosflags() Unset i) 118 Defining Field Width: width() ‘The width() function can be used to define the width of a field necessary for the output of an item. Since, it is a member function, an object can be used to invoke it, as shown below: cout.width(w); where w is the field width(number of columns). The output will be printed in a field of w characters wide at the right end of the fiekl. The width function can specify the field width for only one item. After printing one item, it will revert back to the default. For eg, the statements cout.width(S); cout<<543<<12<<\n"; will produce the following output: Is ja [3 fa f2 The value 543 is printed right justified in the first five columns. The specification width(5) does not retain the setting for printing the number 12. cout.width(5); cout<<543; cout.width(5); cout<<12>>>"\n"; This produce the following output: 5 |4 [3 es C++ never truncates the values and therefore, if the specified field width is smaller than the size of the value to be printed, C++ expands the field to fit the value. #include int main() 10.8,12,15}; '75,100,60,99}; cout.width(5); cout<< “ITEMS”; cout. width(8); 119 cout<< “COST”: ‘cout. width(15); cout<< “TOTAL VALUE” <<“\n"; int sum=0; for(int i=0; i<4; i++) { ‘cout. width(5); cout<< items{i]; ‘cout.width(8); cout<< cost[il; int value=items[i}*cost[i}: cout.width(15); cout< ‘include int main() { cout<<“Precision set to 3 digits \n\n"; cout.precision(3} 121 cout.width(10); cout<<“Value”; cout.width(15); cout<<*SQRT_OF_VALUE"<<“\n"; for(int { m+) cout.width(8); cout< int main() { cout.fill<); 123 cout.precision(3); for(int n=1; n<=6; n++) if cout.width(5); cout<"); } cout<<“\nPadding changed \n\n”; cout.fill(#”); /fil) reset cout.width(15); cout<<12.145678<<*\n"; return 0; } The output of the program < |< |< |< /1 |< |< |< |< |< |< <|1 < |< |< [Ss [2 |< I< |S |< [<< I< OFS oe |e me [oe |S [oe ioe [oe [ce fe (0 3 3 ce > lm | (4 le [ae | le | |& 10 2. |5 > [> [> [> 15 [> |> [> [> [> |> 0 2 me los [ee [Se (G6 |e lee [oe lee lee (0 |. 11 16 17 Padding changed HH HHH) A) 1/2 124 The output of the program ee eee ee ee ee ee 5 SS Od 3 > >>> 4>>>>>>0 5 Se Seo 2 See Oe eee ee Oe Gia yy Padding changed HHHHHH#HH#HHHHHI12. 3 Formatting Flags, Bit-fields and setf() When the function width() is used, the value is printed right-justified in the field width created. The setf{), a member function of the ios class, can be used to print the text left- justified . The setft) (set flags) function can be used as follows: cout setf(argl, arg2); The arg] is one of the formatting flags defined in the class ios. The formatting flag specifies the format action required for the output. Another ios constant, arg2, known as bit field specifies the group to which the formatting flag belongs. 3004.5732 13.0045732x1043 /3.0045732e+03 Flags and bit fields for setf{) function 125 Right justified output Padding after sign(+##20) Scientific notation Fixed point notation Decimal base Octal base Ios :: basefield Jos :: basefield Hexadecimal base Jos :: basefield Table shows the bit fields, flags and their format actions. There are three bit fields and each has a group of format flags. cout.setflios :: left, ios :: adjustfield); cout.setftios :: scientific, ios :: floatfield); Consider the following segment of code: cout.fll(*"); cout.setitios :: left, ios :: adjustfield); cout.width(15); cout<<“TABLE 17<<*\N”; This will produce the following output: The statements cout fill"); cout. precision(3); cout.setitios :: internal, ios :: adjustfiekd); cout.setf(ios :: scientific, ios «: floatfield); cout. width(15); cout<<-12,34567<<"{n"; will produce the following output: ‘The sign is left-justified and the value is right justified. The space between them is padded with stars. The value is printed accurate to three decimal places in the scientific notation, 126 Displaying Trailing zeros and plus sign If we print the numbers 10.75, 25.00 and15.50 using a field width of eight positions, with two digits precision, then the output will be as follows: eee 2S, U1). The trailing zeros in the second and third items have been truncated, Certain situations, such asa list of prices of items or the salary statement of employees, require trailing zeros to be shown. The above output would look better if they are printed as follows: 10.75 25.00 18.50 The setf() can be used with the flag ios :: showpoint as a single argument to achieve this form of output, For example, cout-setftios :: showpoint);, //display trailing zeros would cause cout to display trailing zeros and trailing decimal point, Similarly, a plus sign can be printed before a positive number using the following statement: cout.setflios :: showpos); For example, the statements cout.setftios :: showpoint); cout.setftios :: showpos); cout.precision(3); 1 fixed, ios :: floatfield); internal, ios :: adjustfield); cout.width(10); cout<<275.5<<\n"; will produce the following output: Ce 127

You might also like