Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
25 views
35 pages
Oop CH-1
an introduction to c++ language
Uploaded by
sanskrutigaikwad2307
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save OOP CH-1 For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
25 views
35 pages
Oop CH-1
an introduction to c++ language
Uploaded by
sanskrutigaikwad2307
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save OOP CH-1 For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 35
Search
Fullscreen
Principles of Object Y ay Oriented Programming Principles of Object Orented Programming 11 Procedure Oriented Programming (POP) verses Object Oriented Programming (OOF) 12 Features of Object Oriented Programming, Examples of Object Oriented languages, Applications of COP Data types, Type compatiblity, Declaration of variable, Dynamic initialization of variable, Reference variable, Type casting, 1 14. Special Operators in C+#: Scope resolution operator, Memory management operators, Manipulators 15. Structure of C++ program, Basie Input /Qutput operators and functions in C++, Simple C++ Program 16 Class & Object : Introduction, Specifying a class, Access specifiers, Defining member functions: Inside class and ‘Outside clas, Creating objects, Memory allocations for abject, 3 : [wf 2 fo % The computer as seen by you can be as illustrated In the Fig. 14a. Fig, 1.1.2 : Hardware structure of a computer oy Monitor = Asa programmer, the computer can be seen as a programmable system. It is a system that can be programmed by the programmer. 1.1 Computer t 1.2 Programming and Programming Languages = Programming is to give the machine a list of steps to perform a particular task. Keyboard = _ If the system to which the programming is done is a computer than it is called as Computer Programming. = The programming of any system has to be done in the language understood by that system, Fig, 1.2.1 : Computer Hesides other units, it Is made of a monitor (standard display unit), CPU (Central Processing Unit) and keyboard (standard input device). A computer can be visualized as a system with Input / Output (1/0) devices, Central Processing Unit (CPU) and the memory interconnected as shown tn the Fig. 1.1.2, This is the hardware view of a computer = A digital system like computer understands only binary language (which consists only of Os and 1s), also called as machine language. But, programming in machine language Is almost impossible for a human being,Obiect Crsented Programming using Co* Hence, the manufacturers of the processor develop 4 language called as assembly language. ~ Assembly language is simpler than the machine language, bat making huge software using this is again very it It includes the following : An English language word that specifies the ‘operation to be performed and 2 The operands, which are the data on which the ‘operation is to be performed. — Machine language and assembly language are called as low level languages. To remove the complenity of programming, which was there because of low level languages, High Level Languages (HLL) were developed. HLL are simplest for programming the processors. Some of these languages are FORTRAN, BASIC, COBOL C Cos JAVA net ete. ~ HLL programming languages like C / C++ are structured programming languages and hence are quite easy for the programmers. C / C++ are sometimes also referred to 2s middle level languages as they are not fully high level languages and neither are they low level languages. In this subject we have to leam these two programming languages viz. C and C++. Also we have to make some small programs using these languages. 1.3 _ Binary Number System = Asseen above that a computer can understand only binary language, let us first see what is this binary language? = Binary number system can have only two representations namely ‘0’ and ‘I’ ~All numbers and characters are to be represented uusing’0' or ‘I’ only. ~The conversion from binary to decimal and decimal to binary can be done as shown below with examples, ~ Decimal to binary : The steps to be followed for converting a decimal number to a binary number are © Divide the decimal number by 2. Note down the quotient ang shownintheewample below. 8 Repeat the above procedure tl the zero, © Thelast remainder is the MSB (Moge Bit ie. the bit with highest weight) ana, remainders the LSB (Leas Sitcom Ez @n = Ch zo means the number 5 in decimal (hase number system Base 10 means 19 representations 0 to9. @)z means the number in binary (base 2) system, Base 2 means 2 different represensaons andl. Fig. 13.1 Binary to decimal : The steps to be followed converting a binary number to a decimal are: Multiply the binary digits (bits) with powers of according to their positional weight. The position the first bit (going from right to left) is 0 and & keeps on incrementing as you go towards let every bit Eg. (11100)2: Cho = 1x244 1x 2341x2402 +02 = 16+8+4+0+0 = (28)0 = This is how your decimal data is stored ia computer. You store §, but it stores 101 in binary form. = Let us see some bitwise logical operations that are performed on binary data. = There are various operations that are performed binary data like AND, OR, EXOR and NOT. These operations are explained below. 1. AND: The output i 1ifand only A AND B(ASB being the inputs) are 1.‘vject Oriented Programming using C++ ing Cr 13 Principles of Object Oriented Programming PUT) | BaNPUT) | yeourPUT | Note: We can prefix 0's to a number in binary as in decimal, Here, (011)2 is written to make it 3 digit 0 0 0 e 1 0 data, a8 (8}10 = (101) is 3 it. - a 0 Now, 5&3 Z Z 1 (101)2 Pon nen ee co (001) [agweun | sawrun, | yeoureum | 0 0 Note: {is bitwise AND operator Le. it works on each bit as shown in the above example. 2 0 0 “E 1 a 0 1 (001)2 = 0«22+0x2!+1%29 7 7 ; = (tho (S)10& (3)io= M0 43, NOT: The output Is NOT A (A being the input) ie complement of A. put) Le. | 2, 13 AND10 aqnput) | Y(ourTPuT) ae 0 1 2/6 2 it 0 2/3 0 | (3)0=(10%2 4, EXOR: The output is 1 ifand only If EXCLUSIVELY aj. ‘AORB (A&B being the inputs) are 1. ont FT ‘ACINPUT) | BONPUT) | ¥(OUTPUT) 0 0 0 2| 10 0 i 1 2/5 0 1 1 | G0)0= 5 (1010), Some examples of performing these operations on Ziad the binary data are given below: 01 1. 5AND3 Now; 13 and 10 a (10m in’ programming this is writen as 5 &3. &(1010)2 ee (1000)2 — (1000)2 = x74 0x24 0x2) 0 2/5 2/2 aia 1 4 (@i0= (1002(r= (111)2 (6)10= (110). Now; 7 0R 6 (11), 1110). ain, (111), = 12241 2141%20 = M10 Mol (60 = (ro 4 SORZ (S)1o= (101)2 2]1 0 01 Now, 5 OR2 (2)10= (010), (10 1). 1010), 11), (111), 1x 22eix2te1x20 = (M0 @hol@10 = (10 5. 6EXOR3 ING, thisis written as 6 * 3 Orsay, oto, Now; 6 EXOR 3 (ton, * 11) (101), —— (O12 = 1224047144, = Oo ¥ 10" Bro = (Sig 4 6 NOT3 InC, this is written as ~3 2/3 2j1 4 0 1} @)o=(01n), Now;~3is 00011 1.4 History of C / C++ Programming Languages C programming language was developed by D Ritchie at the Bell Laboratories of AT & T. developed a complier that can convert the: namely C to the machine language that cam understood by the processor or the computer: his compiler could understand only if ertala ‘were followed while writing the program.ject Oriented Programming using Co 5 Principles of Object Oriented Programming © We need to understand and know these rules to | ~ ‘A procedure oriented programming language program OUF computers using this programming | follows top bottom approach. language. C was the most popular programming | - Top bottom approach refers to approaching to @ language. problem as a big task or as a whole. Then dividing some other languages had become popular after | hs task into small instructions ot operations ie: some time of evolution of C, This was because thee Hence, initially the task is broken into small tasks cxher programming languages were object oriented | 2%4¢H@N these smaller ass are writen in detl ie. more siglficance was given to abject. ~The disadvantage of such type of programming is that itis difficult to trace which functions are using a ~ While ‘C’ was a procedure oriented language i.e. data and also error correction is difficult. more significance was given to the procedure to ~ C programming language is an example of perform a task. procedure oriented language. _ C++ which is an object oriented programming language was then developed again at Bell Laboratories by Bjarne Stroustrup. Earlier, this language was called as C with classes, but was later renamed as C++ in 1983, = Object oriented and procedure oriented concepts of «a programming language will be gradually seen in this book. Some of these concepts will be cleared in this chapter itself, while some will come as you reach towards the end of this book. 15 Procedure Oriented Programming (©, What are the features of procedure oriented Fig. 1.5.1: Structure of a procedure oriented Programming? - Programming language In procedure oriented programming all data are shared by all functions, 1s this statement TRUE? || 1.6 Basics of Object Oriented Justify your answer. Programming (OOP) and - Aprocedure oriented programming language is one OOP Languages in which procedure ie. method or functions are given more significance. Here, one function calls another. ~ There can be global variables and local variables to each function. ~ Fig 151 shows how a procedure oriented programming operation. ~ In this type of languages the task is divided into smaller tasks or sub tasks called as procedures or functions or methods. Any function can be called at any instant There are global and Jocal variables as seen in the Fig. 5.1, The global variables can be accessed by all the functions, while the local variables are local to the corresponding function,Object Oriented Programming using C++ a 2. Fig. 1.6.1 shows the structure of a object oriented programming language. Object A Object 8 + Structure of an Object Oriented Programming Ces, Java, Python, Visual Basic, NET are examples of object oriented programming languages. There are few important terms related to Object Oriented Programming that we need to understand, First the concept of objects and classes and then the specialties of OOPs viz. Data Abstraction, Encapsulation, Inheritance, Polymorphism, etc, Let us understand them one by one. 1. Class 2. Object 3. Dataabstraction 4. Data encapsulation 5. Inheritance 6. Polymorphism Class It is a type or a category of things, Its similar to a structure with the difference that it can also have functions besides data items. A structure, we have seen, can have only data variables but a class can have data members as well as function members. Object Ie is an instance or example of a class. You can imagine it to be similar to a variable of class like we havea variable ofa structure, Data abstra ion Data abstraction is like defining or abstracting the object according to the required parameters. For example; if there is a class for circle we need to just define the radius of the object ofthis class. We need not bother about anything else of that object. Data encapsulation The data ofan obec is hidden trom other gy This is called as encapsulation. Encapsul achieved by putting data and functions associ with itinto a class. 5. Inheritance The mechanism of deriving the properties of ong class into another class is known as inheritance, will see in detail about this concept in a specay chapter dedicated on Inheritance. 6. Polymorphism Poly refers to multiple and morph refers to different forms, Hence, polymorphism means multiple forms of the same thing. This topic will also be covered in detail in the later chapters. 1.6.1 Procedure Oriented Versus Object Oriented Programming Language or ‘C’ Language versus ‘C++’ Language Q. Differentiate between POP and OOP (eny four points) S-14, W-14, S-15, S-16, S17, W-17,W-18, 4 Marks . * State the difference between OOP and POP. “ee TERI ‘Sr.| Procedure Oriented | Object Oriented No | Programming (POP) | Programming (00P) 1. | Inthis case emphasis is given on method or procedure, In this case emphasisis on data or objects rather than procedure. | Programs have clases | and objects. Only the functions in a class can access the data ina given object, | Large programs are divided into smaller parts using functions. 3, | Datacan beaccessed | Data canbe accessed byany function, and | only by functions of hence there sascope | that class and hence it of unexpected change | cannot be changed of data. unexpectedly. 4, | Global data is allowed. Hence data is not No global data, Data is ‘encapsulated, [ hidden, | TechXnewiedgeajec oriented Programming using C++ procedure Orlented Programming (POP) Object Oriented Programming (OOP) Ifchanges are done in | Adding of new data or some data, the changes in the data corresponding changes | requires to change are to be implemented | only the functions of inallthefunctions | the class, using the data It follows top-down, approach in program design. 7. | Itcannot model the real world problems precisely. precisely ‘Applications of Object Oriented Programming Language (Q. Write any four applications of OOP, It follows bottom-up approach in program design. Itis used to model the real world problems 1.6.2 OOP finds wide applications in the IT industry. OOP models the real world problems quite precisely and hence it is more used today than the procedure oriented programming languages. The areas for application of OOP include : - Real-time systems, = Simulation and modelling, = Object-oriented databases. Hypertext, hypermedia and expertext. = Aland expert systems, ~ Neural networks and parallel programming. Decision support and office automation systems, ~ CIM/CAM/CAD systems. 17 _ Features of C Programming Language ~ C programming language as already discussed has one major feature of being a structured Programming language and hence itis very easy for the programmer, ~ _ Itisa procedure oriented language and hence has all features discussed in section 1.5, © programming language has become popular because of its major features like reliable, simple and easy to use, Principles of Object Oriented Programming, 1.8 C++ asa Superset of C Programming Langu: ~ Cr+ was earlier called as C with classes, since it @ ‘superset of C with addition of classes. ~ Ct+ supports all features of C with few exceptions that will be discussed in the further chapters. = C¥+ Is an object oriented programming language with most of the programming rules same as that of C. 19 Tokens of C/C++ ~ Before going for programming let us see a very important thing required for programming Le. the tokens ofa programming language. - The C / C++ programs are made up of different things termed as tokens, ~The different tokens of C/C++ are its character set keywords identifiers constants and variables data types operators — We will see these tokens in the sections, Character Set of C/C++ 20020000 19.1 contain, Character set in digs and spectal processor, When we willbe will be found of C/o cha TableObject Onented Programming using C++ 18 Principles of Objec ee sr. Characters List included Symbol | Name of Symbol No. SSE le Back lash 2 | Digts (numbers) | 012,..9 ao [ et Seu i 8 3. | Special symbols (OU itt /+ haat macket fallthoseseenona |*=%@|\~°S*_ Ride keyboard, nothing —_| Bracker besides that) (The names used for pa | etBre these symbols are given Quotes the Table 19.2 ~_| tide in ) 1 Teens 4. | ober special | Blank Space, Tab, =| underscore [+ Phage characters Carriage Return eles ; (Enter Key) Dollar % _ | Percentage Table 1.9.2 : Special Symbols and their names - Each of i Symbol] Nameof | symbot | Name ofsymbol ach of these special symbols may hay ‘Symbol significance which wil be dca forthcomi Comma & _| Ampersand freee [Period ordot | + | asterisk 1.9.2 Keywords j_| Semicolon ~_| Minus sign What are keywords? Ut any melon + | Plussign Cir. es 7 | Question < | Opening Angle ~ These are some special words that Mark (Less than sign) Predefined meaning forthe C/C++ compe ! | Exclamation | > — | Closing Angle these words cannot be used as Mark (Greater than sign) (identifiers are discussed in section 1.93), ne (| LefeParenthosis ] ~ These.are a set of words which ae reseryell certain operations and hence are also 1 | Forward }__| Right Parenthesis referred as reserved words. Slash ~ _Allkeywords are in lower case. ~The keywords used in C / C++ are as given below: asm default float operator ‘Static_cast union auto delete for private struct unsigned |__ break do friend | protected switch using | boot double goto public template | virtual case dynamic if register this void catch else inline reinterpret.cast throw volatile char enum int return true wehar.t class explicit long short ty. while const export mutable signed typedef constcast_ | extern namespace sizeof typeid [E continua | false oo Wl | a areovject Oriented Programming using Cr+ These keywords will be used in different places in programming, Their significance and use will be studied wherever required in the forthcoming chapters. = These Keywords include all those keywords also as declared by ANSI (American National Standards Institute) C. This institute has published the standards to be used in C programming language. 19.3. Identifiers - Identifiers are names given to different user defined things like variables, constants, functions, classes, objects, structures, unions, etc. While making these identifiers we need to follow some rules. These rales are stated below: 41, The identifier can consist of alphabets, digits and a special symbol ie. (underscore). 2. An identifier cannot start with a digit. It can start either with an alphabet or underscore. 3. It cannot contain any special symbol except underscore, Blank spaces are also not allowed. 4. Itcannot bea keyword, 5. It is case sensitive ie, an alphabet capital in one identifier with same name in another identifier with that alphabet small case will be considered different (for more detalls see examples inthis section). 6. Earlier; there was a limit of the length of the identifier to be 32 characters, but now this limit {s removed. Hence, an identifier can be as long as required and minimum of one character, tp Principles of Object Oriented Programming Exampl ‘Alist of valid and invalid identifiers is given below with reasons wherever required, 4. simple interest : Valid char: Invalid because tis a keyword. friends : Invalid, because starts with a digit _Bftiends : Valid Simple interest : Invalid, because blank spaces are not allowed. 6. #3friends : Invalid, because no special symbol except underscore is allowed. 7. void : Invalid, because keyword not allowed. 8. Void : Valid, case sensitive. 1.9.4 Data Types and Type Compatibility ~The data type decides the type of data and the ‘memory locations required for storing that type of data in the memory. — The data types of C / C++ can be divided into three types : Primitive, Derived and User defined data types - The different primitive types of data that can be used in C / C++ are integer, character, fraction type ‘numbers, ete. = Table 1.9.3 shows the different primitive data types and the memory space required for storing them. Table 1.9.3 : Data types ‘sr. | Datatype — | Type of datato be stored Range Space required in No. memory (bytes) 1. | char character in ASCI form = 12710 128 1 | signed char 1 character in ASCII form = 12710128 1 3. | unsigned char ‘A character in ASCII form Oto 25S 1 4. | int Integer numbers ~ 32768 to 32767 2 5. | signed int Integer numbers ~ 32768 to 32767 2 6. | unsigned int Integer numbers 0 t0 65535 2 7. | short int Integer numbers ~ 32768 to 32767 2‘Some examples of data to be stored are listed below with the data types that willbe best suited for them 1. Age in years: int type data must be used, as years is aan integer value. 2. Rate of interest : float data must be used, as rate of interests a fraction type value, 3. Alphabet : char type of data {s to be used, as a characteris to be stored 4. Principal amount: float type data must be used, as principal is in rupee and paisa 5. Runs made by a batsman : int type data must be used, 2s no. of runs will always be integer. 6. Factorial of a number : int type data must be used, as the factorial is always an integer. 7. Radius of a circle : float type data must be used, as radius will mostly be a fraction number. 8. Area of a circle : loat type data must be used, as area is radius? « 3.14, which has to be fraction number. 9. User input as’Y” or ‘N'; char type data must be used, 4s there is only a character to be taken from the user as yes or no, Boolean type of data may also be used for this. Note : The arithmetic operations can be done even on char ‘Yp@ of data. This is because tne processor stores ASCII (American Standard Code for information Interchange) to store the characters, ~ The ASCII value for capital ‘A’ is 65, B' is 66, C'is 67 and so on. While the ASCII values for small Object Oriented Programming using C++ rinciples of Object Orientey Sr] Datatype | ‘Type of data to be stored No, 8. | long int Integer numbers - 21474836480 2147483647 9. | signed short int Integer numbers ~ 32768 to 32767 10, | signed tong int | Integer numbers = 21474836480 2147483647 11, | unsigned short int | Integer numbers 0t0 65535 {.12, | unsigned long int | Integer numbers 0 to 4294967296 13, | float Fraction numbers 3.40" 34 to 3.40% 14, | double Fraction numbers 176-208 to 1.76308 15. | long double Fraction numbers 3.407 4932 to 1164932 Example : 19.5 Example : shown in the examples below: 7 a alphabets are 97 for, 98 for, 99 fog on. The user defined data types are strucure, class and enumeration, The derived data array, function, pointer and reference, The derived and user defined data types studied In the subsequent chapters wherever needed. Declaration of Variables and Constants are values given to the identifiers not change their values throughout the the program. Constants can be defined either by writing Keyword const before the data type or by define. Constants are used to declare the values that) constant, for eg. value of pi ‘The use of constants in program will be di later wherever required, Variables are values given to identifiers that change their values during the execution of program, A variable can be defined with the data (ype For declaring age as an integer type data the (grammar or method of writing) is: int age: For declaring rate of interest as float data YP syntaxis: lot rate; For declaring a character data type element ‘syntax Is: char x;onented Programming sing Coe sia) Reference Variabl 49: i: is @ variable with different name but same emoty location allocated. A reference variable is geclared using the ‘8’ sign, sample of reference variable declaration : int 8 ij the contents of reference variable fs changed the ual parameter value is also changed, ‘the value is passed in a simple manner, while ~pted in a function using °&’ symbol. 196 Escape Sequences scape sequence is a character followed by a lash (\), ‘hey are used especially to perform some special operations like going to new line, providing a horizontal tab, vertical tab ete, The following isa list of escape sequences, 1. \n Newline 2, \t Horizontal Tab 3, \v Vertical Tab 4, \b Backspace 5. \r Carriage Return 6. \f Form feed 7, \a Audible Alert (bell) 8. \\ Backslash 9. \? Question mark 10. \" Single quote 11, \" Double quote 19.7 Operators Operators are different special symbols used for cating an operation to be performed. The operators will be dealt in detail in section 1.12, 110 Structure of C++ Program Describe structure of C++ program with dlagram. Explain the structure of C++ program with suitable erp Principles of Obie Prograrm ‘The Fig 1.10.1 shows the structure of a C++ program Member funetions definition ‘Main funetion Fig, 1.10.1; Structure of C++ Program Program 4.10.1; Write le a slmplo program to display @ ‘statement "Hello TESA Soin. : sis is simple program to display a statement 1/ "Hello Friend” #includesiostreamh> #includesconioh> void main () t i coutse"Hello Friends getch(); } Output Hello Friend Explanation of the above program ~The first line that starts with *//*, indicates that this is a comment line. The comments are written in a program for future reference ofa programmer. = The comments are neglected by the compiler (compiler is a software tool that converts the C / C++ program to the machine language). = In comments you can write anything, it may be helpful to understand your program by somebody else or by yourself after you see the program after a long period. - Any statement that begins with the ‘#’ sign is meant for the preprocessor (preprocessor is a tool that works on the program before the compiler, discussed in section 1.11), - The next statement ie. “#include
, {indicates the preprocessor to include a header file name iostream.h with the program written by the user, TechKnowlObject Oriented Programming using C++ Our programs will definitely have some data to be taken from the user and to display some data on the monitor. The ‘cin’ and ‘cout’ are the statements to handle the input and output operations respectively. ~ The meaning of these words and the process Tequired to be performed for taking the input and displaying the output is mentioned in the header file namely iostreamh, In this program we have used the statement cout, hhence we have included this header file in our program, Any program of C / C++ should have a main function (function is a set of statements to perform a given task), In the statement void main (), the word “void” Indicates that this function is not going to return any data to its caller function. The word “main” is ‘identifier which identifies the function, The brackets at the end of this statement, isa place where parameters can be passed to this function, ‘We will see more about the return type of a function and its parameters in Chapter 3, The curly braces ({ and }) indicate the start and end of the function, The “{" indicates beginning of function, while the "indicates end of the function. “cout” statement is used to display a data on the standard output device ie, the monitor. The "<<" associated with the cout statement is called as the insertion operator. ~The statements given on the right of the insertion operator are displayed on the monitor, ~ If the data written on the right of the insertion operator is in double quotes, then the data will be displayed as itis fit is not in double quotes then it must be name of a variable whose value is to be displayed, : ~The getch() function is an inbuilt function used to accept an input from the user. This makes the computer to wait for the user and hence, makes to output screen available for the user until he presses akey. 1.10.1 Dynamic Initialization of Variables @. Demonstrate the static and dynamic inialization of variables, EET Principles of Object Oriented Program, ‘The initialization of variables is said to be in C++ ie, the value of a variable can be initiating when itis declared. Foreg,intiz5; ~ A program example for the same can be as gy below: / This i a program to multiply two numbers and //the resuit ‘#includeciostream.n> #include
void main () elt coutes"Productis:"
,
..); ~ For example an enum of the week days can be as shown below: TechKnowledgeOurput It is responsible for performing ensin operations before the compiling, like including header files, declaring constants, et. It “always begins with the '# sign. eg Fincludeciostreamh> sdefine pi 3.14; Compiler : tis used to convert the C/C++ program to machine language. As the processor cannot understand the language of C / C++, we need to convert it into a machine understandable language ‘Le. machine language. Linker : It is responsible for linking (connecting) the different functions in a program. We may write multiple functions in the program = or conditional/loop operations in our program. These kinds of operations are to be handled by the linker, Loader : It loads the binary file from the memory and gets is executed by the processor. The binary file that the loader loads is the machine language program understood by the processor. The above program 1.10.1 in section 1.10 can be executed using the following steps: 1. Double click TCexe to get the editor window. 2. Type the program in the editor window, 3. Save the program as.cpp foreg, proglO1.cpp. 4 Compile the program by pressing Alt + F9 ie. press the Alt and F9 key together. S._ Execute the program by pressing Ctrl + F9 6. See the output on the screei n and press enter ‘come back to editor window. 5 Preprocess For ‘The operators are one of the tokens of C/C++, ae different types of operators classified based their functions, ae 2Object Oriented Programming using C++ Ifan operator requires one operand, itis called as Unary operator. If an operator requires two ‘operands, then it is called as Binary operator and if it requires three operands, it is called as Ternary operator. 1.12.1 Unary Operators a. How address of (&) operator is used in pointers, ‘explain with example. : ‘Stale soope resolution operator “and memory Management operator in C++, Give significance of ‘&’ and ™ operators, 5-16, S-17, 2 Marks} Explain use of scope resolution operator. W-17, S-19, W-19, W-22, 2 Marks Q. State the use of scope resolution ‘operator and explain it with example, These are operators that require only one operand. Let us discuss these operators one by one. 1. Unary Operators 4, Unary minus 2. Casting operator (()) 3. Logical Not operator (1) 4. Address of operator (8) '5. Value of operator (*) 6. Scope Resolution operator) 7. Size of operator 8, Bltwise not operator (=) 9. Increment aparator (++) Unary minus (-) The symbol shown in the bracket is used as unary minus operator. Itreturns the negative value of the variable to which it is preceded. For eg. ifx=3 and y=6 then will make the value of yas ~ 3. Principles of Object Oriented Progra Casting Operator (()) Tels many a times required to convert one data tpg to another. The casting operator is used for type conversion jg it can be used to convert a data of one type ty another data type. Foreg.ifwehave intx float y=5.6; then the statement, x=(Int) y; will result in the value of xas 5. The above method of casting is used in C. In C+, the casting is to be done in a slightly different manner i.e. we need to mention x=int(y). We will see the use of this operator in the programming Logical Not operator (!) ‘The symbol shown in the brackets ie. the exclamation mark is used as a logical not operator, It is used to check certain conditions in a condition statement. It performs the logical not of the result obtained from the expression on its right. Foreg. —ifx= then y=tx;, will result with y having the value 0. We will see some more logical not operator based expressions and program followed by this section. Address of operator (8&) This operator returns the address of the variable associated with it. It will be studied more deeply in the chapter on Pointers. For eg if we write y=&x; then the memory address allocated to the variable x will be copied into the variable y. For this the variable y must be pointer variable. Indirection operator or value of operator (+) ‘This operator returns the value of the data at the given address, This operator will also be studied in more details in the chapter on pointers. Foreg 2 will give the value of the data stored at the address given by y. TechKnowledgebecararomning, wing Co “cope Pasolutlon operator (:) ives the scape of a variable to be inside the nor outside the function. This operator wl ye studied in a later chapter, eg fan external variable x is to be accessed the tame can be accesed using the scope operator by the statement, yen, pomple* _jote ORE pepecconioh> char a='Ss costee “The value global variable bis: The value of local vartablea 0: A 7 : 1. Size of operator s used to know the size of a variable red to store its value in memory. It can also 4 to find the size of a data type. the section 1.94, the space required to rent data type fs different ranging from 1 ype to 10 bytes. ¢ statement size of (int); rn the value 2, as int requires 2 bytes. eg: intxy; char a; nx will have 1, and y will have 4 itwise not operator (~) operator is used to perform bitwise NOT on as discussed in the section 1.3, We have en some examples of NOT operations. bitwise NOT operator can be used to perform 7 NOT operation. This operation can be “'med by using the operator given In brackets 9. 10. x22, theny=~% wil revit in y having 2 vatue h-4 Increment Operator (++) It retarns the value of the variable added wich one and somes the result in the variable itself. #x=5, Foreg. Foreg then ++; will make the value fxequal to 6. This “xe+/ (also called as post increment operator) can also be written as “sex (also called as pre increment operator). It can also be used to store the result in anocher variable. But in this case the post increment and pre increment statements will have diferent bebavior 2s explained below with examples. In post increment case, foreg ifx=5, theny=ae4, will make the value of y equal to 5 and x equal to 6. As the name says post increment, it frst gives the previous value and then increments In pre increment case, for eg ifx=5, then y= vx: will make the value of y equal to 6 and x equal to 6. As the name says pre increment, it first increments and then gives the incremented value. More such examples will be seen with programs. Decrement Operator(—) It returns the value of the variable subtracted with ‘one and stores the resuit in the variable itself. Foreg ifx=5, then x~; will make the value of x equal to 4. This “x--;" (also called as post decrement operator) can also be written as “~x:" (also called as pre decrement operator). It can also be used to store the result in another variable. But in this case the post decrement and pre decrement statements will have different behavior as explained below with examples. In post decrement case, for eg ifx= theny =x~; will make the value of y equal to S and x equal to 4.Object Oriented Programming using C++ As the name says post decrement, it first gives the Previous value and then decrements. ~ _ Inpre decrement case, for eg. ifx= 5, then y =—-x; will make the value of y equal to 4 and x equal to 4. As the name says pre decrement, it first decrements and then gives the decremented value. ~ More such examples will be seen with programs. 1.12.2 Binary Operators ~ Operators that require two operands are called as binary operators. ~ These operators are further classified into various ‘types namely the Arithmetic ‘operators, Logical operators, Bitwise. operators and Relational operators, ~ We will see these operators one by one in this section. 1) Atthmetic operators ree 1) Biwise operators i) Logical operators —————— 1) Relational operators Fig. 1.12.2 : Binary operators © Arithmetic operators — This set includes the basic arithmetic operators to perform basic arithmetic operations like addition, subtraction, multiplication and division, There are five operators in this set. They are: 1. * tofind the produet 2, / tofind the quotientafter division 3. % toffind the remainder after division 4. + tofindthesum 5. - tofind the difference ~ One important thing to be noted here is that the ‘/' operator returns only the quotient, while the '%6' operator (also called as MOD operator) returns the remainder after division. The sign of the remainder is always the same as that ofthe dividend, = MOD operator i possible only forint or chap Principles of Object Oriented data It doesn't work on float and double ype data. For example of each of these operators 1929224 2. Forint type of data, 5 / 3 =: For float type of data, /3= 1.67 3 5% 4. 24224; 5. 3-2=1; Bitwise operators ‘These operators work bitwise on a data, ‘They perform different operations on bits of a data like AND, OR, EXOR and NOT. These operations work in the manner as explained in section 13, The operators are listed below: 1, ~ toperform bitwise NOT operation. 2, & toperform bitwise AND operation. 3. | toperform bitwise OR operation. 4. * to perform bitwise EXOR operation. 5. << to perform bitwise left shift operation, 6. >> to perform bitwise right shift operation. ‘These operators are use to perform bitwise binary operations on the data, ‘As we have addition, subtraction operations in decimal data for performing arithmetic operations; similarly AND, OR, NOT are basic bitwise operations onthe binary data. The result of these operations can be understood from the following examples and referring the section 1.3 of binary operations : 5&3= Bo = @ 1 0 12 @io = @ 0 1 1, (0 0 th=(1)io 12|9= (20 = @ 1 0 dy Mw =O 0 0 1p a 0 1o=(13)0 TechkaouledgeUT “001g : flava, WS Of DRS anal henge ssa IN Section 1.3}, Hences “ cases ualteteeyy a vethe data tobe charie 8 bit = (00002020), 01000)3=(40)a9 ‘Wren: The frst! st nagthe data to be charte. 8 bit data (13)9 = (00001012): sleR once(00000102), ‘ong left for the second time(0.0.0000.10)2 for the third time(00.000001)z=(1)i0 D) Logical operators | operators follow the same truth table as for “e bvvise operators as seen in section 1.3; but they sv used to check conditions instead of performing rations on a data. ep The logical operators are AND and OR, The symbols sed for these operators aps I pectively, example a statement y>5 88 ye10; will result in true ‘han § AND Tess 2.0, of Object Oriented Programming Principles Another example a statement yo] yee2: will result in “true” Le, 1 ifthe value of y is greater than $ OR equal to 2, else i will result in false Le. 0, = Logical operators will be understood in more detalls with the expressions and program examples followed by this section, (V) Relational operators = The relational operators are used to test the relation between two variables or a variable and constant, ~The operators like ‘<' (less than) and >’ (greater than) used in the above examples are relational operators, We have seen the example also of the “as (equality operator) in the above logical operators, = Alistofall the relational operators is given below: 1,» used to check ifthe two things are equal, 2, ts used to check ifthe two things are not equal 3. < used to check if the first data is less than the second one, > used to check if the first data is greater than the second one, 5, <= used to check if the first data is less than or. equal to the second one. 6, >= used to check if the first data is greater than or equal to the second one, ~ The examples of these relational operators are as shown with the logical operators above. 112.3 Ternary Operator = An operator that requires three operands is called asa ternary operator, = There is only one ternary operator in C / C+. This, operator Is used to check a condition and accordingly do one of the two things based on the condition being true or false, = The syntax (way of writing) of this operator is as given below: (condition)?
:
y is true, Else; the value of y will be put into 2, Hence, the value of the greater variable will be put into ~ _ Asslightly complicated use of this operator is to find the greatest of three numbers as shown in the example. B= (xy) ?((x>2)2:2)):((y>2)?y:2); This statement will give the largest of x,y and z into the variable g. 1.12.4 Assignment Operators ~ _ These operators are used to assign the value of the expression or variable on the right of the assignment operator to the variable on its left, ~The simple assignment operator is ‘=’ But there are some more assignment operators called as composite assignment operators. Fig, 1.12.3 : Assignment Operators ay 6 8 9. 10. 1. Principles of Object Oriented Pro The different assignment operators are ag lad below: This operator assigns the value of expression or variable on its right tp variable on its left For eg y=x+2; This operator adds the variable on its left ang right and the result is put into the variable gq its left For eg. y+= x; is sameasy =y +, -=1 This operator subtracts the variable on jg right from the variable on its left and the result is put into the variable on its left Fop eg. y-= x; is same as y=y-x; ‘=: This operator multiplies the variable on its left and right and the result is put into the variable on its left. For eg. y*= x; is same as vey's; This operator divides the variable on its right from the variable on its left and the result is ut into the variable on its left. For eg. y/=x, is same as y=y/x; This operator finds the remainder by dividing the variable on its right from the variable on its left and the result is put into the variable on its left. For eg y%=x; is same as y=y%x; This operator ANDs the variables on its left and right and the result is put into the variable on its left. For eg. y&=x; is same as yaya; This operator ORs the variables on its left and right and the result is put into the variable on its left. For eg. yl=x; is same as yey: ‘st This operator EXORs the variables on its left and right and the result is put into the variable on its left. For eg. y*=x; is same as yey" This operator shifts in left direction the variable on its left for the number of times indicated by the variable or value on right and the result is put into the variable on its left. For eg. yeesx; is same as y=y
>=x; is same as y=y>>x; TechKaouledge doe the_L—————— rd Frogramming using, 5 Selection Operators ese operators are to of set of elem cg ase Semen He a een alist cperators when we ar detailed use aie the re these operators ae equa Poms ole ferent operators in this set are lis = ted below: Fig. 1.12.4 : Selection operators O: Ts ae is used to select an element of Array. We will understand more about this in the chapter on Array. This is called as period operator and is used to ct an element of a structure, union or class. This will be studied in detail in the chapter on structure and union. This is used to select an element of a structure, union or class pointed by a pointer, This will be studied in detail in the chapter om structure and union. (): This Is called as a funetion call operator and is «to call or select a function. Ths will be crudied in detail in the chapter on function ‘The comma () operator Is used to separate the different values ete gement Operators Memory Manat 19 Principles of Object Oriented Programming = The new operator is used In C++ for allocating memory dynamically. In the © programming language we used malloc() function for the same. The differences between the new operator and the tmalloc() function are listed in the Table 1.12.1: Table 1.12.1 ‘malloc() function Sr. | newoperator No. Itisan operator. _| It is function. It returns the void type data which is to be type casted to the required data type It does not call the constructor. 2. | It returns the exact data type. 3. [it calls the constructor and can also be used to define the primitive datatypes. = The delete operator is used in C++ for deallocating memory dynamically allocated by new operator. — The programs based on the new and delete operators will be seen in chapters 5 and 7. 4.13 Precedence and Associativity of Operator The precedence of the operators means the sequence in which the operators will be operated ase of multiple operators in a statement on, in ind which. Le. which operator ‘will be executed first ar operator willbe executed later ty of operators refers to the direction = Theassociativit e of {In which the operation will be performed in cas equal precedence operators Le. f multiple additions are there in a statement then {twill be performed from leftto right We will see more about this In the ‘examples followed by this section. The precedence and associativity table sas given in Table 1.13.1.Object Oriented Programming using C a Principles of Object Oriented Program Table 1.13.1 : Precedence and Associativity of operators Operation Precedence |Operators| Operation |Associativity| 1 Equality L {Function call |Leftto right = | Inequality OQ Jarray element] 8 & _[Bitwise AND _[Lefttoright <> |select 9, * _[Bitwise EXOR |Lefttoright Structure Bitwise OR Left to ri element select 20, ! ent | Structure . [element select 114 Expressions 2 + [Unary plus Right to left Let us see some examples of how the processor - |Unary minus performs operations when some statements are given tp “+ |Inctement us in the following examples. We will also see some eo examples wherein an expression is to be written in 1 Decrement C/C++, so how are they written. Semis (Determine the value of the following expressions if an enor 227, b=3 and Bitwise NOT 1 a%b & {Pointer value of| operator = 7%3 Pointer address = 1 (since the remainder after dividing 7 by sizeof 0 of operator 3is1) Size of al 2 ase variable or data =7/4 ‘ype = 1 (Since the quotient after dividing 7 by Type cast 4is1) operator 3 atb/ . ¢ 3. + | Multiply Left to right = 7°3/4 Divide and ger| “ aes eo = 21/4 (since; the associativity of arithmetic Die gute operations is left to right first operation is *) Sorat = 5 (since; quotient is 5) 4. + Tadd Leftto right 4 a*(c%b) 2 Subtract = 7*(4%3) eI << |Left ——shift|Leftto right = 7*1 (since; bracket opening is to be done >> [operator first, and remainder of 4 divided by 3 is 1) Right shift a operator 5. 2*b+ 3° (ac) 6 < — |Lessthan —_Lefttoright = 2*34+3°(7-4) <= Less than or| = 6+3*(3) > ‘equal to = 6+9 (since precedence of multiply is more >= | Greater than than add, first multiplication is done) ‘Greater than or = 15 equal toate%b 7*4%3 28%3 1 atb-c 7+3-4 121 se the following statements are written ; 5 1 oat x=0.5, ¥=0.1; char i ci rind the valUes of the following expresstong 1 Gti-2*%@*anby 6 " (27 - 12) % (2* 97 ~ 98) ...{since; the Asc values stored in char type y, case ‘ype variables is 97 for = (15) % (96) = 18 *O/5) + (4* 0-3)) % (i+j—2) 2° (6/5) + (4*(6-3)) % (946 +2) = 2*(1) * (4*(3))% (13) 2 +(12)%13 = 14 (x>y) && (i> 0) &&G>5) 1&& 1 && 1 ..... if condition is 1 else it is 0) is true its result = 1 4 (&
0)) [1 (j>3y 9 ee yi = (0 && 1) ||) ¢ = (1G) aaa x 5. m since; condition given is false, | s the value of a is 97 as discussed in section 1.13) 6. 44 z = 10 .-(since; it is pre increment it will return the value after incrementing ie. 10) 7 ine 2 = 9 ‘since; this is post increment it value will return the incrementing Le. 9) before (IN Write the following : Principles of Object Oriented Programming Since; the condition given is true b=98) ~( since; after performing NOT operation the value becomes 0) C assignment expressions for the Als greater than B and greater than C (A>B) aa (A>¢) Als .either less than B or greater than C @
c) Side is equal to square root of (a? + b2 + 2ab) Side Pow ((a*a+ b*b+2*a*b), 0.5) CY +2° (&/y)+2*y) /(e+y+2); =b+b?— aac 2a Cb+pow((b*b-4*a*c),0.5))/(2*a); Gb-pow((b*b-4*a*e),0.5))/(2%a); 1 ail kea w+ a+i(1+(k+a)/2); Inbuilt 10 functions are available in C for displaying data on the standard output device i.e, monitor and accepting the input from the standard input device Le. keyboard.Object Oriented Programming using C++ These 10 functions are classified as formatted and unformatted functions based on the formatting Permitted or not These are discussed in more details in the following sub sections. 1.15.1 Formatted 10 Functions There are two formatted 10 functions in C namely PrintfQ) to display a data on monitor and scanf() to accept data from keyboard. 1. printf Syntax : printf{"Format string’, list of variables or expressions) The format string can contain the following : a) Character set ( A-Z, a-z, 0-9, al special symbols on the keyboard) b) Blank spaces ©) Escape sequences (as discussed in section 1.9.6) @) Field width The width of a value can be fixed by specifying the field width. Examples of such case are given below. ©) Format specifiers Format specifiers specify the format of the variable data whose value is to be displayed. The format specifiers for different types of data Principles of Object Orlented Programm printf("The simple interest is %P,, s!); This statement will print the output where format specifier %f will be replaced with the float ! type value of the variable si 3, printf("The simple interest is %5.2f', si); The format specifier in this statement accompanied with a field width ie. 5.2 ( 945.99, which indicates five digits before the fraction poine and 2 digits after the fraction point. This ‘statement will display the output wherein the value of si wy be displayed with five digits before the fraction point and only two digits after the fraction point 4. scanf() ‘Syntax: scanf{“format String’, address of variables) Here, format string can contain format specifier, field width and assignment suppression character, ‘The assignment suppression character (*) is used to discard one of the user entered value. ‘The address of the variable is obtained with the help of the address of operator (&). Examples 1. scanf("96d", &x); This statement is used to accept a int type value from user in the variable x 2. scanf("%d %d %f", &x, &y, &2); This statement is used to accept two int type data into variables x and y, Italso accepts a float type data into the variable z, 1.15.2 Unformatted 10 Functions The unformatted 10 functions do not have any format specifier. They are mostly used to accept and display only one character or a string (string is a set of characters to make a word or: ‘sentence). is given in the Table 1.15.1, Table 1.15.1 : Format specifiers Sr. Format Data type No. | _ specifier 1_ | %dor% i _| Forinteger type of data 2, %E For float type of data 3. ee For char type of data 4. %IE For double type of data 5. Lt For long double type of data Examples 1. printf("The number of buildings Is %d",b); This statement will print the output with the format specifier replaced with the value of b, Fig, 1.15.1: Unformatted 10 Functions Tech)sale oviented Programming using C+ Tne diferent unformatted 10 functions are inven as follows : This function { etchO IS used accey 8 character from the user, a getcheQ+ This function is useq accept character from tigatisdtand "eet OHie (display it on the screen), getcharO:This function is used to accept one character from the user and echo {t (display it on the screen} ) and also wait after that for the user to press the enter key. 4. getsQ# This finetion is used to accept a string from the user. We will see in details of this when studying the chapter on strings. putch(): These functions are used to display a character on the monitor. putchar(), This function is used to display a string on the monitor, 6. putsQ: 116 Basic Input / Output Operators in C++ Which are the input-ou Suitable example. The cin and cout are available di iostreamh. The ferent 10 functions seen in section 1.15 are of C Programming language. The C++ techniques of accepting input from keyboard is with the help of and displaying output is with the help of cout. The cin is always associated with an extraction °perator (>>), This operator extracts the Input from ‘he standard input device fe. the keyboard and Bives it to the variable on the right of it. For eg. cin>>x; will extract the Input from the Keyboard and the user entered value will be put in ‘© the variable x, The user has to press the enter key “Her the user has entered the input. 23 Principles of Object Oriented Programming Multiple extraction operators can be concatenated in a single statement and hence, multiple values taken from the user and given to different variables. For eg, cin>>x>>y; The cout statement is used for displaying an output on the monitor. It is always associated with the insertion operator. We have already seen the use of this statement in the program 1.10.1. The concatenation of insertion operators make it Possible to combine multiple things and display on the monitor. If a particular statement is written in double quotes then it indicates that is to be displayed as it is. While if it is not written in double quotes then it must be the name of a variable whose value is to be displayed. 1.17 Manipulators eer Manipulators are used to perform certain special operations like moving the cursor to new line, fixing the width of a data value, etc. These are used to specify certain formats of the output to be displayed when using the cout statement. ~The different manipulators used in C++ are endl, setw, setprecision) and setfill. These manipulators are available in the header file “iomanip.h”, ~ The manipulator endl is similar to the escape Sequence “\n’, It is used to bring the cursor to the next line, For example: cout<<"Hello”<
#include
main () c t a clrscrQ); | ints, y; 4 cout<<"Enter a number:"; cin>>x; yeetx, cout<<"The square of "
>), which indicates that the cin statement extracts the input from the standard input device and provides it in the variable x. ‘The standard input device is keyboard. ~The next statement assigns the value of x multiplied by itself to provide the square in the variable y, ~ The next cout statement is said to have concatenated insertion operators. ‘The insertion operator is used along with the cout statement to display a data on the monitor, Program 4.18.2: Write aC / C++ program to accept two ‘numbers and display its product, Soin. : #includesiostreamhs #include
‘void main () Cane elrser(); Aint x,y,2; coute<"Enter two number:"; einz>x>2y; zexty; couts<"The product is “<
yoid main () { clrserOi rie tice, float rateOfinte! : To calculate HRA we cannot write hra=40/100 * si basic; as the division 40/100 will return the cin>>principal>>rate quotient of this division which is 0 and hence the simpleInterest : hra will become 0. 100; Once 40 is multiplied with basic the result is coutce"The simple! automatically type casted (upgraded) to the type of getchO) a . _ higher size ie. float as one of the data was float (the variable basic is float type). a a a ; Program 1.18.5: Write a program to swap two integers. ‘Soin, : Enter the prinelpal years:1000 95 10 The simple interest &xplanation All the variables are Parameters are normally with Principal has rupees and pObject Oriented Programming using Cr+ Output Enter two numbers:3 & After swapping the values are a=4 and b=: Explanation For swapping two numbers we need to use a temp Variable and store one of the values in that temp variable, The other value is to be then copied as shown in the program abov een eee eee Program 1.18.6: Write a program to shift a number three bits left and display the resut. Soin. : #includeciostream.h> ‘include
void main Q) { drser); inta,b; cout<<"Enter a number to be shifted left cin>>a; brace3; cout<<"After shifting three times left the value is "<
Hinclude
void main () E : drser(}; intnt; float n2, result; coute<"Enter one integer and one float type number each: cin>>n1>>n2; result=n1*n2; cout<<"The product getch(); : + a Output Enter one integer and one float type number each:2 39 ‘The productis:7.8 3 Explanation ~The two number being multiplied are of int type and float type respectively. ~ Hence the result is automatically type casted (upgraded) to the type of higher size ie. float. Hence the result variable is taken as float. Program 1.19.2: Write a program to accept a float number and display the integer part using type casting operator. Soin. : #includeciostream.h> #include
void main () { cirser(); Inta; float b; cout<<"Enter a float number:"; cin>>b; a=(int)b; cout<<"The integer part of the number is:"<
sineude
oid main O a variable is to be accessed by multiple functions ; then such a variable is known as global variable. arserQi Difference between structure and class inta; coute<"Enter a nu cin>>ay coute<"This is ASCII getchO; Class is a reference | Structure is a value type and its object is | type that is why its created on the heap | variable is created on ) memory. the stack memory. a 2, | Class caninheritthe | Structure does not pr another class. support the intera number : 65 inheritance. Thisis ASCII value of: A bplanation types of constructor | have constructors or and destructor. Og 5 casting operator to go Wate: 3. | Class can have the all | Structure doesn’t destructors This program also uses type ‘oalower data type size. The member variable | The member variable of class can be | of structure cannot initialized directly. be initialized directly. Program 1.19. ‘lass student { int roll no; char name [14]; Is19}; Void main( ) ( Soutc
12L1 Internally Defined Functions or Inside the dass Give syrtax for astning a merber trcton ewes and nesting of functors m a cass wh sE7H%6. les of object oriented defined functions. We will st of the concepts $0 as to of the concept s Program 121.1: Wee 2 progam to find area of cide ushg Object Oriented Proganming such thet the class circle must have three member functions namely = (@) read) to accept the radius from the user. (b) computes) for calculating the area. (0) dsplay() for csplaying the result EAT Soin. # includeciostreamb> # includecconioh> dass circle { float ra; public: void read{) { cout<<"Enter radiu cin>>r; I void compute() { as3.14°rr; void display0) { coute<"Area="<
Htion are called. the display) ence, the FeadQ) function accepts the input from eyras seen in the output and the display() function displays the result calculated by the compute() function. Write a program to calculate the of using intemal | - The logic and way of writing the program is same as the previous one. the following seri salt. sp ineudesiostreat pincudeccontoun> cass series intn, 1, Sum; public: void read() ( cout<<"Enter th cin>>n } void computeQ) ; 4 for(i=1, sum = O;l { ‘ sum=sum: } ) void display() { cout<<"Value of the } ) Noid main() { clrsce(): series s; sread()s Scompute| Sdisplay(s setchQ;Program 1.21.4: Wte a pager © oecise a cass “Studect having data mevbers as name and percentage, Wite a constuctor © -ntalze hese data merbers accept end ospey cats one stucert peace: ear came]; ‘int pervemmage; pubic voidecxcer) { costes’ Enter name and percentage"; cinponamep>percenteee: BBE. void main) Principles of Object Oriented char Name[20]; int Roll No; float percentage; inti; drser); forfi=QsicSie4) { cout
>sfi] Name; coutc<"Enter Roll Number of sa cin>>s[i]-Roll No; cout<<"Enter percentage of student cin>>s[i] percentage; 4 } coutce"\nStudents data is:"; forli=0;i
r; ~ When the member functions of a class are defined |) outside the class they are called as externally | Yoldcircle:computeQ) defined member functions. t ~The functions when defined outside must use scope | #=314°r*r, Z Tesolution operator to define the scope of the | } function to be within the class. The syntax of | void circlessdisplayQ. a defining a function outside the class using the scope | ¢ resolution operator is as given below: ‘Return type Class_name :: Function name( argument list) { ‘Statements; Also in this case the prototype declaration has to be done inside the class for the externally defined functions. Let us see these in details, =a Program 1.21.8: Write a program to find area of circle using Object Oriented Programming such that the class circle must have three externally defined member functions namely: (@) read) to accept the radius from the user, (6) compute() for calculating the area. (6) display() for displaying Soln. # include
# include
class circle cout<<"Area="<
; dass series aa gu 1.21.3 Inline Functions ntnsum j Itwill be discuss in chapter 2. public: void readQ); hae void compute(); : rH void displayQs ae {| @.1 List any four features of POP. @.2 Write any two characteristics of procedure oriented . programming. © | @.3 Describe any four basic concepts of OOP. oid series:xreadQ) coute<"Enter the value of"; 0.4 — With suitable diagram describes structure of C++ >on; : program. @.5 Explain the structure of C++ program with suitable ss:compute() example @.6 Differentiate between POP and OOP (any four sum = 01 ey ; @.7 What are keywords. List any 5 keywords are used in sum=sumsi"t; Sia tier @.10 Write a short note on: Enumerated Data type. ies:display) +] 2.11 Explain diferent operator used in C++, + | @.12 Explain pointer operator and address operator with Cout<<"Value of the series="<
You might also like
C++ Semester1
PDF
No ratings yet
C++ Semester1
59 pages
Rai Business School: Assignment
PDF
No ratings yet
Rai Business School: Assignment
10 pages
Lect 1 FoP PDF
PDF
No ratings yet
Lect 1 FoP PDF
48 pages
Cc101 Reviewer For Midterms
PDF
No ratings yet
Cc101 Reviewer For Midterms
12 pages
CIT392
PDF
No ratings yet
CIT392
206 pages
CPR GM 22025
PDF
No ratings yet
CPR GM 22025
14 pages
Programming Concepts With C++
PDF
100% (1)
Programming Concepts With C++
134 pages
EE-123 OOP Spring 2017 Lect 1-4
PDF
No ratings yet
EE-123 OOP Spring 2017 Lect 1-4
41 pages
Combine (Computer Software and Binary Numbers)
PDF
No ratings yet
Combine (Computer Software and Binary Numbers)
52 pages
C and C++ Programming
PDF
No ratings yet
C and C++ Programming
89 pages
Object Oriented Proramming Notes 1
PDF
No ratings yet
Object Oriented Proramming Notes 1
56 pages
Chapter 1 3
PDF
No ratings yet
Chapter 1 3
44 pages
2-1 OOP-Through C++ R19
PDF
No ratings yet
2-1 OOP-Through C++ R19
105 pages
Chapter 02
PDF
No ratings yet
Chapter 02
19 pages
C Basopr Ref
PDF
No ratings yet
C Basopr Ref
35 pages
C Lecture1
PDF
No ratings yet
C Lecture1
25 pages
C++ Report File
PDF
No ratings yet
C++ Report File
32 pages
Programming Fundamentals Lec 1,2.3,4
PDF
No ratings yet
Programming Fundamentals Lec 1,2.3,4
36 pages
BSC Notes Latest
PDF
No ratings yet
BSC Notes Latest
31 pages
Pic 1 To 3 Chaptersslide Shows 1-59
PDF
100% (1)
Pic 1 To 3 Chaptersslide Shows 1-59
59 pages
Unit 1 INTRODUCTION
PDF
No ratings yet
Unit 1 INTRODUCTION
62 pages
C++ Programming: From Problem Analysis To Program Design: Fifth Edition
PDF
No ratings yet
C++ Programming: From Problem Analysis To Program Design: Fifth Edition
88 pages
Davija CP and Ds Notes-Eee 2nd Year
PDF
No ratings yet
Davija CP and Ds Notes-Eee 2nd Year
340 pages
SPA Ebook PDF
PDF
No ratings yet
SPA Ebook PDF
375 pages
Sessions - DS Using C++ (14EC55) - 5th Semester BE (ECE) - Units 1
PDF
No ratings yet
Sessions - DS Using C++ (14EC55) - 5th Semester BE (ECE) - Units 1
58 pages
C++ Upto 23
PDF
No ratings yet
C++ Upto 23
222 pages
Week - 01-Learn Dsa With C++
PDF
No ratings yet
Week - 01-Learn Dsa With C++
38 pages
Oop PDF
PDF
No ratings yet
Oop PDF
67 pages
INTERNSHIP REPORT Niki
PDF
No ratings yet
INTERNSHIP REPORT Niki
16 pages
N Acknowledgement
PDF
No ratings yet
N Acknowledgement
32 pages
OOPC Part1
PDF
No ratings yet
OOPC Part1
25 pages
Computer Programming
PDF
No ratings yet
Computer Programming
53 pages
Programming Fundamentals Lec 1,2.3
PDF
No ratings yet
Programming Fundamentals Lec 1,2.3
34 pages
Day 1 Getting Started
PDF
No ratings yet
Day 1 Getting Started
95 pages
Internship Report C and C++
PDF
No ratings yet
Internship Report C and C++
31 pages
CP-II (Week1-9)
PDF
No ratings yet
CP-II (Week1-9)
208 pages
Studentnotes C
PDF
No ratings yet
Studentnotes C
29 pages
Chapter - 2
PDF
No ratings yet
Chapter - 2
16 pages
Final Programming in C
PDF
No ratings yet
Final Programming in C
325 pages
Computer Programming
PDF
No ratings yet
Computer Programming
53 pages
Programming Reviewer 2
PDF
No ratings yet
Programming Reviewer 2
10 pages
1, 2. Introduction and Overview of Programming
PDF
No ratings yet
1, 2. Introduction and Overview of Programming
63 pages
Chapter 1
PDF
No ratings yet
Chapter 1
13 pages
I BSC I Sem C Language
PDF
No ratings yet
I BSC I Sem C Language
137 pages
LECTURE 2 - Introduction To C Programming
PDF
No ratings yet
LECTURE 2 - Introduction To C Programming
53 pages
Lecture 1
PDF
No ratings yet
Lecture 1
36 pages
P1 (Programming)
PDF
No ratings yet
P1 (Programming)
4 pages
Algo Notes S4
PDF
No ratings yet
Algo Notes S4
44 pages
Women 00852
PDF
No ratings yet
Women 00852
82 pages
Lecture 2
PDF
No ratings yet
Lecture 2
35 pages
Overview of Computers and Programming Languages
PDF
No ratings yet
Overview of Computers and Programming Languages
19 pages
C Language Overview
PDF
No ratings yet
C Language Overview
35 pages
C
PDF
88% (8)
C
418 pages
Programming in C++ For BCA BIT BE
PDF
No ratings yet
Programming in C++ For BCA BIT BE
129 pages
COMP 103 L5-ProgTechniques
PDF
No ratings yet
COMP 103 L5-ProgTechniques
38 pages
CSC 201 New Lecture Note
PDF
No ratings yet
CSC 201 New Lecture Note
36 pages
Lecture 1
PDF
No ratings yet
Lecture 1
57 pages
Programming Week 1: Shankar Balachandran, IIT Madras
PDF
No ratings yet
Programming Week 1: Shankar Balachandran, IIT Madras
98 pages
What Is A Computer Program?: Chapter One
PDF
No ratings yet
What Is A Computer Program?: Chapter One
10 pages
DBMS Microproject
PDF
No ratings yet
DBMS Microproject
28 pages
Microproject Dbms
PDF
No ratings yet
Microproject Dbms
28 pages
DBMS CH-1
PDF
No ratings yet
DBMS CH-1
30 pages
AI (Sans)
PDF
No ratings yet
AI (Sans)
5 pages