You are on page 1of 100

Q. 1 Give in brief the History of C and C++ Language. Ans.

History of C Language The C programming language was designed by Dennies Ritchie in the early 1970s at Bell Laboratories. It was first used system implementation language for the nascent Unix operating system. The main reason to devised C was to overcome the limitations of B. It was derived from the type-less language BCPL ((Basic Combined Programming Language). C was the evolution of B and BCPL by incorporating type checking. It was originally intended for use in writing compilers for other languages. History of C++ C++ was devised by Bjarne Stroustrup in 1983 at Bell Laboratories. It is an extension of C by adding some enhancements to C language. Bjarne combined the simulas(a language designed for making simulations, created by Ole-Johan Dahi and Kristen Nygaard) features of object oriented and the efficiency of C. The new features added to language are templates, namespaces, exception handling and use of standard library. Q. 2. Give Differences between C and C++. Ans. C++ is an extension of C language. This means that you can not only use the new features introduced with C++ but can also use the power and efficiency of C language. C and C++ are no more language for writing compilers and other languages, these general purpose languages are used worldwide in every field. The main difference between C and C++ is that C++ is object oriented while C is function or procedure oriented. Object oriented programming paradigm is focused on writing programs that are more readable and maintainable. It also helps the reuse of code by packaging a group of similar objects or using the concept of component programming model. it helps thinking in a logical way by using the concept of real world concepts of objects, inheritance and polymorphism. It should be noted that there are also some drawbacks of such features. For example using polymorphism in a program can slow down the performance of that program. On the other hand, functional and procedural programming focus primarily on the actions and events, and the programming model focuses on the logical assertions that trigger execution of program code. C++ is flexible in declaration of variables. You can define them any where when u need. C++ use top-down approach while C bottom-up. Memory allocation/deallocation is done by two keywords malkc and free in C while we use new and delete.in C++.Some Other differences O structs dont copy in C. That is, if a and h are structs then the line a = h; doesnt work. Nor will structs be fed into functions as arguments. The only way to deal with theni sensibly is to use pointers to them, or to write functions to copy their elements explicitly, classes (with private members) dont exis in C. C) There is no operator and function overloading in C. It a function has a name, then thats it- you cant have another ersion with the same name that does the same thing with different arguments, as you can in C++. The fact that << and >> (left and right shift) do output and input in C++ is a consequence of the ability of the language to overload those operators. Output and input in C ar handled by functions called printt and scant respectively (these also work in C++ if you want, of course). O In (2 storage allocation and deallocation are not handled by new and delete but by a function called ma 11cc. In general, the whole process is a bit more messy in C, but is not too had once you get the hang of it.

Q. 3. What is a friend class? Ans. C++ provides the friend keyword to do just this. Inside a class, you can indicate that other classes (or simply functions) will have direct access to protected and private members of the class. When granting access to a class, you must specify that the access is granted for a class using the class keyword: friend class a Class; Q. 4. Give standard C and C++ data types in detail. Ans. Information that is processed with computers is known as Data, The Data may contain integers or simply Alphabets. It is therefore necessary to specify the data type so that computer can represent the daLi correctly in its memory. The different data type supported by C are given as follow.

Q. 5. Why we use C++? Ans. C++ is a powerful general-purpose programming language. It can be used to create small programs or large applications. It can he used to make CCI scripts or console- only DOS programs. C++ allows you to create programs to do almost anything you need to do. The creator of C++, Bjarne Stroustrup, has put together a partial list of applications written in C++.

Q. 6. What is Object-Oriented Programming? 2

Ans. Object oriented programming is essentially building a program around self- contained collections of data arid code to modify that data; this programming model is in contrast to a model that uses function that act on data scattered throughout a program. Object-oriented programming (or coding, as programming is commonly referred to) is an organizational style, hut it helps programmers create reusable code because the code to do a specific thing is entirely contained within a single section of code, and to use the code to perform tasks - for instance, creating a menu - involves using only a small number of functions to access the internals of the class. Think of it as a black box that can be easily carried from place to place, and that performs complex actions simply at the press of a button: for instance, a microwave lets you heat food for a specified time limit - say, two minutes - by typing in the time and pressing the heat button. You do not need to know how the microwave operates or why the physics works. In the same way that self-contained appliances simplify life for the consumer, object-oriented programming simplifies the transfer of source code from one program to another program by encapsulating it - puffing it all in one place. Q. 7. What do you need to program in C or C++? Ans. In order to make usable programs in C or C++, you will need a compiler. A compiler converts source code - the actual instructions typed by the programmer - into an executable file. Numerous compilers are available for C and C++. Listed on the sidebar are several pages with information on specific compilers. Q. 8. What are enumerated Constants? Ans. In C and C++, enum types can be used to set up collections of named integer constants. (The keyword enum is short for enumerated.) The traditional C way of doing this was something like this:

An alternate approach using enum would be enum { SPRING, SUMMER, FALL, WINTER }; Enumerated types, or enums are used to name (i.e. enumerate) the elements of a finite set, and you can declare variables that can be represented by that set. This can greatly reduce the code required to define and work with a long list of constants. For instance, we could use the preprocessor to assign a numerical value to eacWof the months of the year: #define JAN 0 #define FEB 1 // #define DEC 11 /1... mt themonth=OCT; this could be replaced by an enumerated type: 3

enum month {JAN, FEB, MAR, APR, MAY, JUN. JUL, AUG, SEP, OCT. NOV. DEC); I!... enum month the_month=OCT; Using an enumerated type ensures that the variable the_month can only take on values equivalent to JAN-DEC. unlike the integer in the first code fragment- which can have values that are nonsensical in this context. A particularly important implication of this is that switch statements do not need a catch-all default: branch, as all of the possible outcomes are known in advance. Q. 9. What is the difference between char and short data type? Ans. The type char is used to store a single character of information and takes one byte. As with int, char is the actual name of the data type, and must be written as such in the declaration. The short data types take two bytes and used to store number. Q. 10. What are 1/0 streams? Ans. The I/O stream classes view the flow of data from your program to the screen as being a stream of data, one byte following another. If the destination of the stream is a file or the screen, the source is usually some part of your program. If the stream is reversed1 the data can come from the keyboard or a disk file and be poured into your data variables.One principal goal of streams is to encapsulate the problems of getting the data to and from the disk or the screen. Q. 11. What is recursion? Ans. A function can call itself, This is called recursion, and recursion can be direct or indirect. It is direct when a function calls itself; it is indirect recursion when a function calls another function that then calls the first function. Some problems are most easily solved by recursion, usually those in which you act on data and then act in the same way pn the result. Both types of recursion, direct and indirect, come in two varieties: those that eventually end and produce an answer, and those that never end and produce a runtime failure. Q. 12. What do you understand by Ivalue? Ans. An object is a named region of storage; an lvalue is an expression refer to an object. An lvalue is an expression to which a value can be assigned. The ivalue expression is located on the left side of an assignment statement, whereas an rvalue is located on the right side of an assignment statement. Each assignment statement must have an lvalue. and an rvalue. The lvlue expression must reference a storable variable in memory. It cannot be a constant. An Ivalue is a way of describing the term on the left hand side of an assignment. It is usually an address or variable. In this declaration and initialization of the mt variable a, the lvalue i a. mt a 9*7+c; An lvalue is a vaiue that can be modified i.e. a value that can appear on the left of an assignment (hence Ivalue). Mylnt = 3; 4

is O.K because Mylnt is an lvalue, but 3 = Mylnt; isnt because 3 isnt. In C++ all manner of expressions, including function calls, can yield Ivalues that can be assigned to Example to demonstrate Ivalue V #define CONSTANT_VAR 10 V mt var=1; V int* pntr_int5;

CONSTANT_VAR = 15; The variable var is an integer, which is a storable location in memory. Therefore, the. statement var = 1 qualifies var to be an Ivalue. Notice the second assignment statement, *pntr_int = 5. By using the * modifier to reference the area of memory that pntr_int points to, *pnr_int is qualified as an lvalue. In contrast, observe the CONSTANT variable: V In this statements, the left side of the statement evaluates to a constant value that cannot be changed because constants do not represent storable locations in memory. Therefore, this assignment statements do not contain lvalues and will be flagged by your compiler as errors. An identifier is a modifiable I-value if it refers to a memory location and if its type is arithmetic, structure, union, or pointer. For example, if ptr is a pointer to a storage region, then *pfr is a modifiable 1-value that designates the storage region to which ptr points. Any of the following C expressions can be I-value expressions O An identifier of integral, floating, pointer, structure, or union type o A subscript (11) expression that does not evaluate to an array o A member-selection expression (_> or O A unary-indirection (*) expression that does not refer to an array o An 1-value expression in parentheses o A const object (a nonmodifiable I-value)

Q. 13. What is compile time? Ans. Compile time is the time when you run your compiler, as opposed to link time (when you run the linker) or run time (when rurming the program). This is just programmer shorthand to identify the three times when errors usually 5 surface.

Q. 14. What does #include do? Ans. This is a directive to the preprocessor, which runs when you call your compiler. This specific directive causes the file named after the word include to he read in, as if it were typed in at that location in your source code. Q. 15, What is the difference between /7 comments and 7* style comments? Ans. The double-slash comments (//) expire at the end of the line. Slash-star (/*) comments are in effect until a closing comment (*/). Remember, not even the end of the function terminates a slash-star comment; you must put in the closing comment mark, or you will get a compile-time error. Q. 16. What differentiates a good comment from a bad comment? Ans. A good comment tells the reader why this particular code is doing whatever it is doing or explains what a section of code is about to do. A had comment restates what a particular line of code is doing. Lines (>1 code should he written so that they speak for themselves. Reading the line of code should tell you what it is doing without needing a corn ment. Q. 17. What is the role of this pointer? Ans. Every class member function has a hidden parameter: the this pointer, this points to the individual object. Therefore, in each call to GetAge() or SetAgeQ, the this pointer for the object is included as a hidden parameter. I/Using the this pointer. #include <iostrearn.h> class Rectangle

Rtangle theRect; cout << theRect is << theRect.GetLength() << feet long.\n; cout << theRect is << theRect.GetWidth() << feet wide.\n; theRec t.SetLength(20); tlieRect.SetWidth(i 0); cout << theRect is << theRect.GetLengthQ<< feet long.\n; cout << theRect is << theRect.GetWidthQ<< feet wide.\n; return 0; Output : theRect is 10 feet long. theRect is 5 feet long. theRect is 20 feet long. tileRect is 10 feet iohg. Trw SetLength() and GetLength() accessor functions explicitly use the this pointer access the member variables of the Rectangle object. The SetWidth and GetWidth cessors do not. There is no difference in their behavior, although the syntax is easier to derstand. If that were all tilere was to the this pointer, there would be little point in hering you with it. Tile tills pointer, however, is a pointer; it stores the memory address an object. As such, it can be a powerful tool.

Q, 18. What is Data Abstraction? Ans. It is the selective examination of certain aspects of a problem. The goal of traction is to isolate the important aspect of a problem and suppressing the unimportant 1. Many different abstractions are possible for the same problem, depending on the purpose for which they are made. 2. All abstractions are incomplete and inaccurate e.g. all human words and language are abstractions incomplete description of the real world. 3. The purpose of an abstraction is to limit the universe so we can do things. In building models, therefore, you must not search for absolute truths but for adequacy of some purpose. There is no single correct module for a problem, only adequate and inadequate ones their identity their relationship with other objects, their attributes and their operations. In other words, it provides a framework within which the functional and dynamic models are placed; you must not search for absolute truth but for adequacy for some purpose. There I no single correct model for problem only adequate and inadequate ones. Q. 19. If a short mt can run out of room and wrap around, why not always use long integers? Ans .Both short integers and long integers will run out of room and wrap around, but a long integer will do so with a much larger number. For example, an unsigned short mt will wrap around after 65,535, whereas an unsigned long mt will not wrap around until 4,294,967,295. However, on most machines, a long integer takes up twice as much memory every time you declare one (4 bytes versus 2 bytes), and a program with 100 such variables will consume an extra 200 bytes of RAM. Frankly, this is less of a problem than it used to be, because most personal computers now come with many thousands (if class derived-class-name : visibility-mode base-class-namenot millions) of bytes of memory. Q. 20. What is the difference between private and protected members? Ans. Protected means Allows access to the class member only within the same class and from inherited classes. Private: Access modifier that renders members of a class invisible to components outside of that class. Variables that are visible only to the script in which they are declared or Allows access to the class member only in the same class. We use these keywords to specify access levels for member variables, or for member functions (methods). .Public variables are variables that are visible to all classes. Private variables are variables that are visible only to the class to which they belong..Protected variables are variables that are visible only to the class to which they belong, and any subclasses. Deciding when to use private, protected, or public variables is sometimes tricky. You need to think whether or not an external object (or program), actually needs direct access to the information. If you do want other objects to access internal data, but wish to control i, you would make it either private or protected, but provide functions which can manipulate the data in a controlled way. Q. 21. What does public, protected and private inheritance mean? Ans. Defining Derived Classes; Visibility Modes In order to define a ilass having name derived-clas-name from a class having name base-class-name, the following syntax is usedThe colon indicates that the derived-class-name has been derived from base-classLern, name. It is important to learn about visibility modes while inheriting from a class. REMEMBER THAT PRIVATE DATA MEMBERS OF BASE CLASS WILL NOT BE 8

INHERITED IN ANY CASE. When a class is privately inherited, its effect is that all public members of base class become private in the derived class, such that they are inaccessible to the objects of the derived class. On the other hand, when a class is publiclyinherited into another class, the public members of base class remain public in the derivedclass, such that they are accessible to the objects of derived class. Thus the derived class has data member b and functions return_a( ), show_a() and get_ab(), which it has acquired through public inheritance from base.

Protected : To Make a Private Member Inheritable A major problem that remains unsolved is how to inherit a private data member, if it is needed in derived class. The private label does not allow to break the walls of encapsulation whereas making such a data memberpublic would make it accessible to outside world besides imparting it inheritance capability. The answer is protected data member. The visibility label protected ensures that the members declared under it are accessible to the derived class through inheritance. Further, protected members cannot be accessed by the functions outside the class. In a way, they combine the functionality of private and public members into one label. It is important to learn that behavior of protected data members in derived class depends upon visibility mode of inheritance. The table given in summarizes the inheritance rules: -

Q. 22.What is Operator Overloading? Ans. Operating overloading allows you to pass different variable types to the same inction and produce different results. In this article Ben gives us the low-down on operator overloading in C++.Operator overloading is common-place among many efficient C++ programmers. It allows you to use the same function name, but as different functions.

Q. 23,What are Dynamic Link Libraries (DLL) ?

Ans. (Dynamic Link Library) A librar of functions stored on your hard drive that allows programs to use its resources, memory, disk drive etc., more efficiently. Dynamically Linked Library, a library linked to an executable program at runtime. An executable code module for Microsoft Windows that can he loaded on demand and linked at run time, and then unloaded when the code is no longer needed. Q. 24. What is Function ? What is the use of function? Ans. A function is a small program developed by the user or manufacturer of C language. The basic purpose of a function is to do a task. There are two types of functions are available in C and they are Library Functions Or Ready-Made Functions and User Defined Functions. Uses of functions 1. By using functions, we can use top down modular approach of programming. 2. Functions reduce the program size. 3. Users can develop their own library. 4. The functions are very useful for debugging and testing of programs. 5. The functions are also useful for modifications in the program by the original programmer or a new programmer. 6. Functions are very simple to understand and use. Q. 25. State the scope of local and global variables. Ans. Local Variable: A local is visible to a function in which it is declared, but not to other fuctions. It is declared inside the function. It also called an auto variable, because it is automatically created when a function is called and destroyed when execution of function is complete or when function exited or when function returns value. Global Variable: A global variable is visible to all functions and it is declared outside the function. The proper place of global variables is before the main function or before the function declaration. In other words we can say that global variables are declared before all the function declarations. Q. 26. What is the need of recursion? Write a program to find the factorial of a number using recursion. Ans. n C, it is possible for the Functions to call themselves. A function is called recursive. If a statement within the body of a function calls the same function. Sometime called circular definition, recursion is thus the process of defining something in terms of itself. This is an example of recursion. Try to understand it on your own. Let us repeat that C functions may be used recursively; that is, a function may call itself either directly or indirectly,

10

Q. 27. What happens if I assign a number with a decimal point to an integer rather than to a float ? Consider the following line of code: mt aNumber = 5.4; Ans. A good compiler will issue a warning, hut the assignment is completely legal. The number youve assigned will be truncated into an integer. Thus, if you assign 5.4 to an integer variable, that variable will have the value 5. Information will be lost, however, and if you then try to assign the value in that integer variable to a float variable, the float variable will have only 5. Q. 28. Why not use literal constants; why go to the bother of using symbolic constants ? Ans. If you use the value in many places throughout your program, a symbolic constant allows all the values to change just by changing the one definition of the constant. Symbolic constants also speak for themselves. It might he hard to understand why a number is being multiplied by 360, but its much easier to understand whats going on if the nuniber is being multiplied by degreeslnACircle. Q. 29. What happens if I assign a negative number to an unsigned variable? Consider the following line of code : unsigned mt aPositiveNumber = -1; Ans. A good compiler will warn, hut th assignment is legal. The negative number will be assessed as a bt pattern and assigned to the variable. The value of that variable will then be interpreted as an unsigned number. Thus, 1, whose bit pattern is 11111111 11111 111 (Oxl+ in hex), will be assessed as the unsigned yalue 65,535. Q. 30. Can I work with C++ without understanding bit patterns, binary arithmetic, and hexadecimal ? Ans. Yes, but not as effectively as if you do understand these topics. C++ does not do as good a job as some languages at protecting you from what the computer is really doing. This is actually a benefit, because it provides you .with tremendous power that other languages dont. As with any power tool, however, to get the most out of C++ you must understand how it works. Programmers who try to program in C++ without understanding the fundamentals of the binary 11 system often are confused by their results.

Q.31. Illustrate the use of continue statements in C++.? Ans. The continue statement causes the program to skip the rest of the ioop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown: // continue loop example #include <iostream> using namespace std; mt main 0 { for (mt n1 0; n>0; n ) { if (n==5) continue; cout<<n<<,; ) cout << FIRE!; return 0; 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE! Q. 32. Discuss the various types of operators in detail, also discuss he precedence of operators. Ans. An operator is a symbol that causes the compiler to take an action. Operators act on operands, and in C++ all operands are expressions. In C++ there are several different categories of operators. o Assignment operators. o Mathematical operators. o Logical Operators Assignment Operator : The assignment operator () causes the operand on the left side of the assignment operator to have its value changed to the value on the right side of the assignment operator. The expression assigns the value that is the result of adding a and b to the operand x. An operand that legally can be on the left side of an assignment operator is called an Ivalue. That which can be on the right side is called (you guessed it) an rvalue. Constants are rvalues. They cannot be 1-values. Thus, you can write 35 ,// ok but you cant legally write 35 // error, not an Ivalue! An Ivalue is an operand that can be on the left side of an expression. An rvalue is an operand that can be on the right side of an expression. Note that all 1-values are r-values, but not all r-values are I-values. An example of an rvalue that is not an Ivalue is a literal. Thus, you can write x 5;, but you cannot write 5 = x;. Mathematical Operators: There are five mathematical operators: addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). Addition and subtraction work as you would expect, although subtraction with unsigned integers can lead to surprising results, if the result is a negative inamber. You saw something much like this yesterday, when12

variable overflow was described. Below program shows what happens when you subtract a large unsigned number from a small unsigned number. A demonstration of subtraction and integer overflow. / / demonstrates subtraction and // integer overflow #include <iostream.h> mt main() unsigned mt difference; unsigned mt higNumber 100; unsigned mt smallNumber 50; difference = bigNumber - smaliNumber; cout << Difference is: <<difference; difference = smaliNumber - bigNumber; cout << \nNow difference is: <<difference <<end!; return 0; Output: Difference is: 50 Now difference is: 4294967246 The subtraction operator is invoked on line 10, and the result is printed on line 11, much as we might expect. The subtraction operator is called again on line 12, but this time a large unsigned number is subtracted from a small unsigned number. Integer Division and Modulus Integer division is somewhat different from everyday division. When you divide 21 by 4, the result is a real number (a number with a fraction). Integers dont have fractions, and so the remainder is lopped off. The answer is therefore 5. To get the remainder, you take 21 modulus 4 (21 % 4) and the result is 1. The modulus operator tells you the -remainder after an integer division. Finding the modulus can be very useful. For example, you might want to print a statement on every 10th action. Any number whose value is 0 when you modulus 10 with that number is an exact multiple of 10. Thus I % 10 is 1, 2 % 10 is 2, and so forth, until 10 % 10, whose result is 0. 11 % 10 is back to 1, and this pattern continues until the next multiple of 10, which is 20. Many novice C++ programmers inadvertently put a semicolon after their if statements: if(SomeValue < 10); SomeValue = 10; What was intended here was to test whether SomeValue is less than 10, and if so, to set it to 10, making 10 the minimum value for SomeValue. Running this code snippet will show that SomeValue is always set to 10 Why? The if statement terminates with the semicolon (the do-nothing operator). Remember that indentation has no meaning to the compiler. This snippet could more accurately have been written as: if (SOineValue < 10) 7/test /7 do nothing 13

SomeValue = 10; // assign Removing the semicolon will make the final line part of the, if statement and will make this code do what was intended. Combining the Assignment and Mathematical Operators It is not uncommon to want to add a value to a variable, and then to assign the result back into the variable. If you have a variable myAge and you want to increase the value by two, you can write: mt myAge 5; mt temp; temp = myAge 2; /7 add 5 + 2 an.d put it in temp myAge temp; 7/ put it back in myAge This method, however, is terribly conyoluted and wasteful. In C+, you can put the same variable on both sides of the assignment operator, and thus the preceding becomes myAge myAge + 2; which is much better. In algebra this xprssion would be meaningless, but in C++ it is read as add two to the value in myAge and assign the result to myAge. Even simpler to write, but perhaps a bitliarder to read is myAge+ 2; The self-assigned addition operator (+=) adds the rvalue to the ivalue and then reassigns the result into ti-c Ivalue. This operator is pronounced plus-equals. The statement would be read myAge plus-equals two. If myAge had the value 4 to start, it would have 6 after this statement. There are self-assigned subtraction (-j, division (/=), multiplication (*=), and modulus (%j operators as well. Increment and Decrement The most common value to add (or subtract) and then reassign into a variable is 1. In C++, increasing a value by 1 is called incrementing, and decreasing by 1 is called decrementing. There are special operators to perform these actions. The increment operator (++) increases the value of the variable by 1, and the decrement operator () decreases it by 1. Thus, if you have a variable, C, and you want to increment it, you would use this statement: C++; / / Start with C and increment it. This statement is equivalent to the more verbose statement CC+1; which you learned is also equivalent to the moderately verbose statement C+=1; Prefix and Postfix Both the increment operator (+) and the decrement operator(.) come in two varieties: prefix and postfix. The prefix variety i written before the variable name (++myAge); the postfix variety is written after (myAge++). 14

In a simple statement, it doesnt much matter which you use, but in a complex statement, when you are incrementing (or decrernenting) a variable and then assigning the result to another variable, it matters very much. The prefix operator is evaluated before the assignment, the postfix is evaluated after. The semantics of prefix is this: Increment the value and then fetch it. The semantics of postfix is different: Fetch the value and then increment the original. This can be confusing at first, but if x is an integer whose value is 5 and you write inta++x; you have told the compiler to increment x (making it 6) and then fetch that value rnd assign it to a. Thus, a is now 6 and x is now 6, If, after doing this, you write mtb = x++; you have now told the compiler to fetch the value in x (6) and assign it to b, and then go back and increment x. Thus, b is now 6, but x is now 7. A demonstration of prefix and postf ix operators. / / demonstrates use of prefix and postfix increment anddecrement operators #include <iostream.h> mt main() mt myAge = 39; // initialize two integers mt yourAge = 39; cout << I am: <<my Age << years old.\n; cout << You are: <<yourAge << years old\n; myAge++; // postfix increment ++yourAge; // prefix increment cout << One year passes...\n;

cout << 1 am: <<myAge << years old.\ni cout << You are: << yourAge << years old\n; cout << Another year passes\n; cout << I am: <<myAge++ <<years old.\n; cout << You are: <<++yourAge << years old\n; cout << Lets print it again.\n; cout << I am: <<myAge << years old.\n; cout << You are: <<yourAge << years old\n; 15

return 0; Output: I am 39 years old You are 39 years old One year passes I am 40 years old You are 40 years old Another year passes I am 40 years old You are 41 years old Lets print it again I am 41 years old You are 41 years old Relational Operators The relational operators are used to determine whether two numbers are equal, or if one is greater or less than the other. Every relational statement evaluates to either 1 (TRUE) or 0 (FALSE). If the integer variable myAge has the value 39, and the integer variableyourAge has the value 40, you can determine whether they are equal by using the relational equals operator: myAge == yourAge; // is the value in myAge the same as in yourAge? This expression evaluates to 0, or false, because the variables are not equal. The expression myAge > yourAge; // is myAge greater than yourAge? evaluates to 0 or false. Many novice C++ programmers confuse the assignment operator () with the equals operator (==). This can create a nasty bug in your program. There .are six relational operators: equals (=), less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), and not equals (!=). Table below shows each relational operator, its use, and a sample code use.

16

DO remember that relational operators return the value I (true) or 0 (false). DONT confuse the assignment operator (=) with the equals relational operator (==). This is one of the most common C++ programming mistakesbe on guard for it. V Logical Operators. bften you want to ask more than one relational question at a time. is it true that x is greater than y, and also true that y is greater than z? A program might need to determine that both of these conditions are true, or that some other condition is true, in order to take an action. Imagine a sophisticated alarm systern that has this logic: If the door alarm sounds V AND it is after six p.m. AND it is NOT a holiday, OR if it is a weekend,.then call the police. C++s three logical operators are used to make this kind of evaluation. These operators are listed in Table below.

Logical AND A logical AND statement evaluates two expressions, and if both expressions are true, the logical AND statement is true as well. If it is true that you are hungry, AND it i true that you have money, THEN it is true that you can buy lunch. Thus, if ( (x == 5) && (y == 5) ) would evaluate TRUE if both x and y are equal to 5, and it would evaluate FALSE if either one is not equal to 5. Note that both sides must be true for the entire expression to be true.

17

Logical OR A logical OR statement evaluates two expressions. If either one is true, the expression is true. If you have money OR you have a credit card, you can pay the bill. You dont need both money and a credit card; you need only one, although having both would be fine as well. Thus, if((x5) I (y==5)) evaluates TRUE if either x or y is equal to 5, or if both are. Note that the logical OR is two symbols. A single I symbol is a different operator, discussed on Day 21.

Logical NOT A logical NOT statement evaluates true if the expression being tested is false. Again, if the expression being tested is false, the value of the test is TRUE! Thus if(!(x==5)) is true only if x is not equal to 5. This is exactly the same as writing Conditional (Ternary) Operator The conditional operator (?:) is C++s only ternary operator; that is, it is the only operator to take three terms. The conditional operator takes three expressions and returns a value: (expressioni) ? (expression2) : (expressionS) This line is read as If expressioni is true, return the value of expression2; otherwise, return the value of expression3. Typically, this value would be assigned to a variable. Precedence In the complex statement x5+38; which is performed first, the addition or the multiplication? If the addition is performed first, the answer is 8 * 8, or 64. If the multiplication is performed first, the answer is 5 + 24, or 29. Every operator has a precedence value, and the complete list is shown in Appendix A, Operator Precedence. Multiplication has higher precedence than addition, and thus the value of the expression is 29. When two mathematical operators have the same precedence, they are performed in left-to-right order. Thus x5+38*9+6*4; is evaluated multiplication first, left to right. Thus, 8*9 = 72, and 6*4 = 24. Now the expression is essentially x= 5+ 3 + 72 + 24; 18

Now the addition, left to right, is 5 + 3 = 8; 8 72 =80; 80 + 24 104. Be careful with this. Some operators, such as assignment, are evaluated in right-to- left order! In any case, what if the precedence order doesnt meet your needs? Consider the expressiori TotalSeconds NumMinutesTolhink + NumMinutesToType * 60 In this expression, you do not want to multiply the NumMinutesToType variable by 60 and then add it to NumMinutesTo1 hmk. You want to add the two varables to get the total number of minutes, and then you want to multiply that number by 60 to get the total seconds. In this case, you use parentheses to change the precedence order. Items in parentheses are evaluated at a higher precedence than any of the mathematical operators. Thus Total Seconds (NumMinutesToThink + NumMinutesToType) * 60 will accomplish what you want. Q. 33. What do you mean by Operator Overloading and Operator function? Or Define overloading. Can all the operators in C++ can be overloaded? Ans. Operator Overloading One of the most interesting features of C++ is that it makes the user-defined data types behave as in-built data type. In this context, it should be permitted to perform operations on user-defined data types (objects) just like they are performed on basic data types. This is possible if special meaning is given to the operator. Thus, the mechanism in which an operator performs ADDITIONAL TASK, apart from doing its normal operition, is known as OPERATOR OVERLOADING. It is important to remember the following points about operator overloading (a) Only the semantics of an operator are extended, its syntax cannot be changed. The syntax includes the grammatical rules that govern the use of operator such as the number of operands, precedence and associativity. b) The operators, which cannot be overloaded, are class member access operator (. and. *), scope resolution operator (::), size operator (size of) and conditional operator (?) c) The original meaning of operator is not lost for e.g. the operator + cannot be used to multiply two objects. Operator Function Operator overloading is done with the help of special function, called Operator function. Operator function can be either MEMBER FUNCTIONS OR FRIEND FUNCTIONS. The syntax for defining an operator function as a member of class is returntype operator op (argument list) function body 19

where operator is a keyword and op is the name of operator. The number of arguments passed to a member operator function is one for overloading binary operator and no argument for overloading unary operator. This is because the object used to invoke the member function is passed implicitly to the function. Consider an example of overloading negation unary operator - #include<iostream.h> class integer mt i, j; public: void getdata (mt a, mt b); void display 0; void operator-a; /*prototype of oper,ator function*/ 3; /*end of class declaration*/ void integer:: getdata (mt a, mt b) ia; jb; void integer:: display() cout<<\n i = COUt<<fl j void integer:: operator 0 j = - j; /*negafive value of j */ j = -j; /* negative value of j*/ void main () integer ii; /*create object of integer*/ il.getdata (10,20); i1.display /*this will display 10 and 20*/ - ii; ii display 0; /* this will display 10 and _20*/ / *end of main*/ To perform an operation such as 20

i3 ii + i2; /* i3 = il.operator (i2) */ where ii, i2 and i3 are objects of class integer, the following member function is required integer integer:: operator + (integer i2) integer temp; tempi=i+i2.i; temp.j = j + i2.j; return temp; /*return temporary object*/ Here, the operator+ function creates a temporary object temp of type integer (class). It adds the i member of ii object (implicitly available) with the i member of 12 (passed as argument) and return the result to i of temp. Similarly, j members of ii and i2 are added and returned to j member of temp. Finally, the temporary object is returned, so that it .is captured into i3. Q. 34. How can we overload Arithmetic Assignment Operators? Discuss using suitable example. Ans. Arithmetic assignment operators such as += combine arithmetic operation and assignment into one operator (example addition and assignment in this case). Such operators can also be overloaded using operator function. Following is an example of overloading + = operator. # include <iostream.h> class distance mt m; /* for metre / - float m; /* for centimetre */ public: distance o m0;

21

Q. 35. Can we overload Increment and Decrement Operators ? How? Ans. Increment and Decrement operators can also be overloaded. These operators may or may not return value. Consequently, the operator function may return void or any value. Consider the example of increment operator overloading, given below: # include<iostream,h> 22

# include<stdlib.h> class counter

In this example, there are overloaded operator functions for ++ operator. In the first call to operator++, no value is returned. In the second call to operator++, an object is returned. In the operator function returning counter type of value, a temporary anonymous (nameless) object is created, initialized with the incremented value of count and returned to main, where that object is captured into the object C2. Q. 36. Write a program to show the Overloaded Assignment Operator. Ans. #include<iostream.h> class alpha private: 23

dataa.data; cout<<\n Assignment operator invoked; return alpha(data); alpha al (37); alpha a2; a2=al; cout<<\n a2= a2.display0; The alpha class is very simple; it contains only one data member. Constructors initialize the data, and a member function can printout its value. The new aspect of ASSIGN is the function operator =0 which overloads the = operator. In main 0 we define al and give it the value 37, and define a2 but give it no value. Then we use the assignment operator to set a2 to the ialue of al: public: mt data; alphaO() I*no..argument constructor / alpha(int d) /*oneargument constructOr / (datad;) void display() / *display data*/ {cout<<data;} alpha operator = (alpha &a) void main() /*invoke overloaded =iQ. 37. What do you mean by Dereferencing Operators? Ans. C++ permits us to define a class containing various types of data and functions as members. C++ also permits us to access the class member through pointers. In order to achieve this, C++ provides a set of three pointer-to-member operators. Table given below shows these operators and their functions. Member Dereferencing Operators a1a2; /*assignrnent statement / This causes our overloaded operator = function to be invoked. Here is the output from ASSIGN: a2=37 a337

24

Q. 37. What do you mean by Dereferencing Operators? Ans. C++ permits us to define a class containing various types of data and functions as members. C++ also permits us to access the class member through pointers. In order to achieve this, C++ provides a set of three pointer-to-member operators. Table given below shows these operators and their functions. Member Dereferencing Operators

The dereferencing operator ?* is used to access a member when we use pointers to both the object and the member. The dereferencing operator * is used when the object itself is used with the member pointer. #include<iostream.h> class M mt x; mt y; public: void set_x(int a,int b) xa; yb; friend mt sum(M rn); mt sum(M m) mt m::*px &M::x; /* pointer to member x */

25

Q. 38. What do you mean by storage classes? Discuss the various types of storage classes. Or What are registers and extern storage classes used in C/C++ ? Or Explain different storage class specifiers in C/C++. Ans. Storage Class : In C-language every variable has its own behavior. For example the variables of main program and sub programs behave differently. Some of the variables works only within a program i.e. locally in a program and some of the variables works globally i.e. Inside and outside the programs. Also the variables are stored in memory differently by using functions. From this discussion we conclude that each variable has properties execution period/life time and scope or visibility. using a special feature of C we can assign life time and scope to a variable. This special feature is called Storage Class or Storage Variable. Basically there are two types of variables : Local Variable & Global Variable, Another definition: The storage class or storage variable indicates the scope & longevity [life] of a variable. Scope means a variable may have different values at different instance of a program. Longevity means the time period for which a variable get alive.

1. Local Variable: A local is visible to a function in which it is declared, but not to other Functions, it is declared inside the function. It also called an auto variable, because it is automatically created when a function is called and destroyed when execution of function is cmplete or when function exited or when function returns value. 26

2. Global Variable: A global variable is visible to all functions and it is declared outside the function. The proper place of global variables is before the main function or before the function declaration. In other words we can say that global variables are declared before all the function declarations. In every program we need variables and constants. The variables store the values like Input values, intermediate resuitsand final results. Ihe variables are nothing but scratch pads, whose values are incremented, decremented or assigned to other variables. The variables are different from constant whose values remain the same. We further classify the variables on two bases 1. Scope or visibility: It means which function can use the variable and which can not? 2. Life time: It is the time for which a variable stores the value. There are four storage classes in C & they are:

AUTO, EXTERNAL/GLOBAL,REGISTER & STATIC STORAGE CLASSES or VARIABLEs. (a) Auto/Local The properties of an auto or local variable/storage class are: 1. It is the default storage class i.e. all the variables we usually use are local or auto. 2. It is defined and accessed within the function in which they are declared. 3. They have no value until that function is not called where that auto variable is defined. 4. The lifetime of an auto variable is limited to the time fo which the function is executed. When function return value or function completes its execution or function is exited - such variables get destroyed. 5. The auto variables are stored on stacks. The stacks provide temporary memory to variables. 6 Its default initial value is the garhae value, To define an integer variable a as auto we can write mt a; or auto mt a;. Following program example shows complete role of an auto variable. In this program value of n i.e. 100.00 and k i.e. 3 are supplied or passed to function mul. In function mul, we store the value n to x and value of k toy. The local variable z of function mul stores the result i.e. sqrt(x) t y i.e. sqrt(100)+3 = 10+3 = 13. Then value of z is returned back to calling prog main to variable j. The value of j is then printed using printfQ. it means variables n,k and j are local variables of function main() and variable z is the local variable of function mul. If we write z1 0; in mainO, it will give error undefined symbol Z. 27

(b) ExternaVGlobal The features or properties of such variables are 1. When there is a need of a variable that is required in all functions, so such variables are defined as global. So the external or global variables serves this purpose. 2. The scope of these variables is global i.e. available in all functions. 3. Such variables are defined once [outside the main function ] and remains active & alive in all functions. 4. The initial default value of a global variable is zero. 5. Such variables do not die at the start or end of any program, but die at the end of whole program. 6. No fresh memory is provided to such variables. Following examples shows the use of external variables.

28

29

(c) Static Storage Class The features of static storage class or variable are 1. It is quite similar to an auto variable, but they are defined once and do not die till program ends. 2. The static variables are defined within the functions as auto variables. The difference between auto & static is that auto variables are defined in the function again & again. The old value of auto variables destroyed again & again. But static variables are defined only once and retains it old value. 3. These variables can not be accessed by other functions but can only be ccessed by the function in which the static variables are defined. 4, The default initial value of a static variable is zero. 5. Static variables have global lifetime (i.e. their value do not die even controls comes out of a function) but have local visibility Le. can be used in the function in which they have been defined. 6. They are stored in memory. rhe role of static variables is clear from followiflg examples: Example 1:

30

Local & global variables The variables used in user defined functions and main function can be classified in two categories. Such categories are Local & Global Variables. Global Declaration: The variables of main programs and subprograms/functions are not known outside each other. Both the programs [main & sub] has their own local declaralion. The variables of local declaration are called Private Variables or Local Variable Or Auto variables. These variables get alive or activated when that function is called. They are created when function is called & they will be deleted automatically when function is exited. Such variables are also known as auto variables. These variables are declared within the function, in which they are needed. But there are some variables, which are defined outside the main () function. Such variables are called GLOBAL or PUBLIC VARIABLES. These variables are defined once & remain active in each sub function & main (). These variables are declared outside the main 0 function. They are activated, before main 0 - so they are get alive always. Let us consider an example.

31

In the above example, the variables a b j & k are defined outside the main() function, so they are global variables. The variable t is defined inside the function sumO so it is a local variable.

32

Q. 39. What do you mean by array? Discuss in detail. Ans. An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. That means that, for example, we can store 5 values of type mt in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, mt for example, with a unique identifier. For example, an array to colitain 5 integer values of type mt called billy could be represented like this: where each blank panel represents an element of the array, that in this case are integer values of type mt. These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length. Like a regular variable, an array must be declared before it is used. A typical declaration for an array inC++ is: type name [elements]; where type is a valid type (like mt1 float...), name is a valid identifier and the elements field (which is always enclosed in square brackets []), specifies how many of these elements the array has to contain. Therefore, in order to declare an array called billy as the one shown in the above diagram it is as simple as: mt billy [51; The elements field within brackets [1 which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order33

to create arrays with a variable length dynamic memory is needed, which is explained later in these tutorials. Initializing arrays. When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its elements will not be initialized to an value by default, so their content will be undetermined until we store some value in them. Global and static arrays, on the other hand, are automatically initialized filled with zeros. In both cases, local and global, when we declare an Array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces { }. For example: mt billy [51 { 16, 2, 77, 40, 12071 }; This declaration would have created an array like this: The amount of values between braces } must not be larger than the number of elements that we declare for the array between square brackets. For example, in the example of array billy we have declared that it has 5 elements and in the list of initial values within braces { } we have specified 5 values, one for each element. When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets empty [1. In this case, the compiler will assume a size for the Array that matches the number of values included between braces { ): mt billy [1 = { 16, 2, 77, 40, 12071 }; After this declaration, Array billy would be 5 ints long, since we have provided 5 initialization values. - Accessing the values of an Array In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable,, thus being able to both read and modify its value. The format is as simple as: name[indexj Following the previous examples in which billy had 5 elements and each of those elements was of type int, the name which we can use to refer to each element is the following: For example, to store the value 75 in the third element of billy, we could write the following statement: billy[21 = 75; and, for example, to pass the value of the third element of billy to a variable called a, we could write: a hilly[2}; Therefore, the expression hilly[2J s br all purposes like a variable of type mt. Notice that the third element of billy is specified billy[2], since the first one is billy[O], the second one is billy[lj, and therefore, the third one is billy[2]. By this same reason, its last element is billy[4]. Therefore, if we write billy[5J, we would be accessing the sixth element of billy and therefore exceeding the size of the array.

34

In C++ it is syntactically correct to exceed the valid range of indices for an Array. This can create problems, since accessing outof-range elements do not cause compilation errors but can cause runtirne errors. The reason why this is allowed will be seen farther ahead when we begin to use pointers. At this point it is important to be able to clearly distinguish between the two uses that brackets [] have related to arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and the second one is to specify indices for concrete array elements. Do not confuse these two possible uses of brackets [] with arrays. mt billy [5]; // declaration of a new Array billy[21 = 75; // access to an element of the Array. If you read carefully, you will ee that a type specifier always precedes a variable or array declaration, while it never precedes an access. Some other valid operations with arrays:

Multidimensional Arrays Multidimensional arrays can be described as arrays of arrays. For example, a bidimensional array can be imagined as a bidimensional table made of elements, all of them of a same uniform data type. jimmy represents a bidimensional array of 3 per 5 elements of type mt. The way to declare this array in C++ would be: mt jimmy [3][5]; and, for example, the way to reference the second element vertically and fourth horizontally in an expression would be: jimmy[1][3] (remember that array indices always begin by iero). 35

Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can contain as many indices as needed. But be careful! The amount of memory needed for an array rapidly increases with each dimension. For example: char century [100] [365] [24] [60] [60]; declares an array with a char element for each second in a century, that is more than 3 billion chars. So this declaration would consume more than 3 gigabytes of memory! Multidimensional arrays are just an absfraction for programmers, since we can obtain the same results with a simple array just by putting a factor between its indices: mt jimmy [3][5]; I/is equivalent to mt jimmy [15]; /1(3 * 5 = 15) With the only difference that with multidimensional arrays the compiler remembers the depth of each imaginary dimension for us. Take as example these two pieces ofode, with both exactly the same result. One uses a bid imensional array and the other one uses a simple array: Multidimensional array

36

None of the two source codes above produce any output on the screen, but both assign values to the memory block called jimmy in the following way: #define HEIGHT 3 to: #define HEIGHT 4 with no need to make any other modifications to the program. Arrays as parameters At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function,but we are allowed to pass its address. In practice this has almost the same effect and it is a much faster and more efficient operation. In order to accept arrays as parameters the only thing that we have to do when declaring the function is to specify in its parameters the element type of the array, an identifier and a pair of void brackets. For example, the following function: void procedure (mt arg(J) accepts a parameter of type Array of int called arg. In order to pass to this function an array declared as:

37

As you can see, the first parameter (mt arg[]) accepts any array whose elements are of type int, wathever its length. For that reason we have included a second parameter that tells the function the length of each array that we pass to it as its first parameter. This allows the for loop that prints out the array to know the range to iterate in the passed array without going out of range. In a function declaration it is also possible to include multidimensional arrays. The format for a tridimensional array parameter is: base_type[j [depth] [depth] for example, a function with a multidimensional array as argument could be: void procedure (mt myarray{] [31[4}) Notice that the first brackets [j are left blank while the following ones are not. This is so because the compiler must be able to determine within the function which is the depth of each additional dimension. Arrays, both simple or multidimensional, passed as function parameters are a quite common source of errors for novice programmers. Q. 40. What do you mean by I/O in C? Discuss in detail. Ans. Introduction to I/O Input means to enter the data and output means receive the data. Keyboard, mouse are the best example of input device and monitor ,printer are comes under the categories of output device. InC language there are some library function which are to be used for input/output. e.g. printf, scanfQ, mainQ, getchQ, putcQ, putch() etc. I/O functions are classified into two categories 1. Unformatted I/O functions 2. Formatted I/O functions 1. Unformatted I/O functions 38

Unformatted I/O functions are considers as the library function. These functions are to be used for single character r a string of characters. (i) Single Character input functions (a) getch() this funtion returns the character that has been typed most recently. e.g. char a; agetchO; (b) getche() this function echoes or display the character type on the screen. Adding e to getch() is for echo. char a; a=getcheO; The difference between getch() and getche() is that, if user use getch() function the it will not wait for the user to press the enter key. As soon as the user press any key the control will be passed further in the program on the other hand getche() function will assign the character pressed to a and will also display it on the screen. (c) getchar-) this is similar as getche() function but the only difference between these two is that in getchar() function these is the need to press the enter key pressing then it is assigned to the variable and gets displayed. (ii) Single Character Output functions (a) putchO, putchar() are two single character output functions char x putch(x); putchar(z); the output of both the function will be the same z (b) gets() this function is used on the place of scanf() function because scanf() function has some limitation when user use any string value. When user use the space in two string then scanf() consider it one word and then user gets only one word on the screen but not the whole word.

39

So the space used after Ravinder is consider the end of the word. So gets() function is to be used to remove this limitation.

2. Formatted I/O Functions It is used to format the input or output of data as per the user requirements. With the use of Formatted I/O functions user can control the input/output on the screen but in the case of unformatted I/O function this is not possible. There are some Formatted I/O functions which are 10 be used in C programs. To read the data scanf() function is to be used. To print the data printf() function is to be used. Format string function sign is used with some single character. e.g. %d ,%f,%c,%s,%lf etc.

40

Q. 41 (a). Discuss in detail the Pointers. Ans.. Pointer are conceptually quite simple ,they are variables that hold the memory addresses of other variables. To concretize concepts think of an array the elements of which, as you know, are places in consecutive locations of storage, at a regularly increasing addresses. It is apparent that the address of any element is immediately computable relative to that of the zeroth : for, if the address of the zeros elementof the array be x, say, and if each element of it be w bytes wide, then, relatively to its beginning, the address of the kth element must be x+y*z,y=1,2 You can see that pointers which are variables to store memory addresses, should be very closely allied to arrays. In an array, the address of any element is one unit greater than that of the proceeding element. A pointer represents the address or location of the variables, where a variable has been stored in computer memory It does not represent the actual value of a variable. User can store the address of all types of variable like ordinary /scalar/ unsubscripted variables, array variable, matrices or string.

Pointer Variable and Pointer Arithmetic One of the most powerful feature of C, and one that makes it quite close to assembly language, is its ability to refer to the addresses of program variables., in C one can in fact declare variables to be pointers, that is variables which will hold the memory address of other variables. Syntax: char *x; x is a pointer variable; x can now be assigned the address of a char like variable. Simithrly one can declare pointer variables to point to int, long, float or double in short, of variable of any type, includirg user defined types. The statement

The values of pointer variable are meipry address. How does one extract the memory address of a program variable? and , conversely, 41

given a memory address, how does one determine the contents at that address ? The C address of operator is the ampersand, &. Its a unary operator, that, applied to a variable yields its memory address;

Advantages of Pointers 0 It has close relation with arrays,matrics/ tables and string. User can access any type of data by using pointers. o String can be represented in a single dimensional array, with the use of pointer. 42

o Execution speed of a program will be increased. 0 Length and complexity of program will he reduced. o User can developed their own library functions, header file etc. o It can be used to return multiple data values to the calling function. Pointer to a Function Function can be return only one value to the calling program or main prog.But following particular situation function can not be used: o If two variable x and y sent to a function, interchange them and return to main program. This option is very useful in sorting program like bubble sort method. o If two or more than two variable are sent to function, do some calculations on them and return value to calling/main function. /* Write a program that will exchange the value of two integer variable */

Q. 41. (b). Write a simple C++ program showing the working at arays of pointers.

43

Ans. Pointer, Array and The Subscript Operator. We have already remarkedupon the close relationship between pointers and arrays. That relationship is crystallized in the following truth: The name of an array is the pointer to its zeroth element. Let primes[100] be an array of ints. Then Primes == & primes[0] The name primes is itself a pointer! its value is the address of primes[0] . primes +1 is the address of the next element of the array, primes i is the address of its(i+1)th element. One can use this property in the following way suppose you wish to scan values into the elements of an array it marks [40]. Then the following for(;;) loop will do: for(i0;i<40;i++) scanf(%d,(marks +i)); This statement works because the arguments of scanf() must be pointers, and marks + i is a pointer to the ith element after the zeroth of marks. /* Program to uses the pointer notation to store the first 1000 primes in an array /

44

Pointer to Pointer A pointer contains the address of the data item pointed to, by it,. This data item that is pointed to may be a pointer itself i.e it can contain the address of another data item. Thus, a pointer can point to another pointer, which in turn points to a data item.accessing data item from the given pointer requires two levels of indirection i.e.( * For example: Tnt *b; Tnt **C;

what happen is that be stores the address of a. thus, if we print *h it would give the value of a i.e. 10, whereas c contains the address of be which itself is a pointer to a, this is what is called pointer to pointer. Thus if you say Printf( u%dll,**c) Output: 10 Q. 42. What do you mean by structure and union ? Give diference between sructure and union. Ans. It is user defined data type, which represents different types of data within a single group. Array, as we have seen in the previous units, provide a means to bundle homogeneous data items into a single named unit. But more often than not real world applations require the grouping together of heterogeneous data items. Consider once more the information that one would want to store about admission record of the student. 0 Name of the student 0 Which class 0 Fathers name 45

0 Mothers name 0 Section o Session o Date of birth o Date of admission o Admission fee deposits Above list show that some items are character type while some are integer. If we considered using arrays to store the records of several similar transactions, then we should need nine in all; Structure are a C facility that permit several heterogeneous but interrelated items to be treated as a single unit. The keyword struct introduces such a unit.

This struct declaration names nine members; (array have elements; structs have members). But it reserves no storage. It creates a template that can be used to define objects of type struct student_record. Declaring a structure The structure is declared in the following way

Memory allocated is according to the structure elements, like, if you have one structure element as int, other as char and third as float. 7 byte would be fixed in memory for such structure i.e 2 for int, 1 for char and 4 for float, which equals 7 byets. For example if you make a structure of students which consists of roIl_no,name,class, address. 46

EmployeeId no. is 1 Employee Name is ravinder singh Employee address is grain market Employee salary is 12500 NESTINC OF STRUCTURE In condition statements as wesaw..that if couktberteai i.e. one if within another if: One structure can be nested within another structure. This neting ofstruttume helps in creating complex data types. 47

UNION Unionlike strUctures , store within them different data types The only difference between the two is that members within a union share the same storage area within the computers memory, whereas each member within the structure has its own unique storage area. Thus, unions conserve memory. The general format of defining union is : Union union-name

Union name is the name that identifies theunin and members are the variables that may be of different data types.

48

In the above program you observe that the variable and the members declaration is same as we do in structures. The elements are also accessed in the same way by using a dot operator(.). the difference between the structure and union is viewed in the memory allocation. If it was a structure, 4 bytes of memory would have been consumed i.e 2 byte for integer and I each for character. But in union, only 2 bytes of memory is occupied because both the integer and a character data types are stored in the same memory space. Thus, key.opt[O] and key.opt[I] can be accessed by using the same memory location of key.i.

ADVANTAGES OF STRUCTURES & UNIONS 1. Structures and union has an important role in C programming. The arrays and martices are used to handle the variables of same type. But there are many applications, in whit 1 we have to use the variables of different types. Like in a payroll program, we need to input : employee number, name, salary, department, income tax etc. Here employee number is an integer variable, name & deptt are character string variables, salary & income tax are float variables. These variables can be collectively defined by using a structure or a union. They are useful to handle related items. 2. If we want to pass an employee record to a function, then all the individual elements has to pass. It will increase the variable declaration, program execution time, complexity & size of program But using structures to supply individual members to the function. It will increase the program declaration and program size as well as complexity.

49

Q. 43. What do you mean by Macros in C? Ans. They are defined in definition section of a C program. All the mathematical functions and constants can be defined with the help of #define, The general format of #define is #define VARIABLE value or #define function function declaration Eg. #define Q 10.00 #define F(X) XX+10 The variable names used in #define are called SYMBOLIC CONSTANTS or SYMBOLIC NAMES. o They may be written in uppercase or lower case letters. Mostly these variable names are written in uppercase letters. This is not a rule but just an convention. They are written in upper case, just to differentiate from other variables & constants. o The instruction like #include & #define are called COMPILER DECLARATIVES or pre-processor directives. o They do not ends with semi colon (;). They instruct the compilers to do something. Programs to show the actual use of #define / Prog. to find the volume of sphere using define */ #define P1 3.142 /* Symbolic Constant */ #include <math.h> /* for pow function */ main() float r,v; clrscrQ; p1: printf(Enter the radius ); scanf( % f,&r); if(r<0) printf(\nSorry invaild value of r, please check \n); gotopl; v = 4/3.0 * P1 * pow(r,3); printf(\nVolume of sphere = %.4f,v ); printf(\nThanks); getcheQ; I

50

Output Runi Enter the value of alpha: Q Enter Value of function at x10.000000 is 56.000000 Sorry, 10.000000 is not a root of 1(x) Output Run2 Enter the value of alpha: Enter Value of function at x3.000000 is 0.000000 Yes 3.000000 is a root of f(x) Output Run3 Enfer the value of alpha: 2 Enter Value of function at x2.000000 is = 0.000000 Yes 2.000000 is a root of f(x)

51

Q. 44. What do you mean by User defined data types(UDP)? Ans. It is the beauty of C that we can define a new data type by using the keyword! reserve word typedef in the prog. It means we can reNAME the existing data type. The features of this concept is: 1. We can define a new data type. 2. We are not actually creating a new data type but defining a new name for an existing data.type. -3. This process can make machine-dependent programs. 4. Such programs can be more portable, readable and understandable. 5. Once we have define a new data type, it can be used anywhere by giving new nems to-the variables. 6. if we want to add or delete or change some data types then only typedef command has to be changed, and other program environment need not to be changed. 7.When we are compiling for new program afterchanges in the typedef statement, thtzpedef statement automatically changes the programming environment The syntax i

For example : Most of the uerscorifusedwith mt and float so they can be defined as: typedef Int without_decimal; typedef float with_decimal; Following prog will show the actual use of typedef. /* Program to show the use of typedef */ typedef mt without_decimal; typedef float with_decimal; void rnain() without_decimal a5,b6; with_decimal c1.4, d=1.2, x; clrscrO; 52

xa+b+c+.d; printf(\nSum is = %f,x); getche getcheo; Q. 45. What do you mean by Function? Discuss in detail. Ans. Although object-oriented programming has shifted attention from functions and toward objects, functions nonetheless remain a central component of any program. Today you will learn: O What a function is and what its parts are. o i-low to declare and define functk& () How to pass parameters into functions. o How to return a value from a function.

What is the function Afunctin is. in effect, a subprogram that can act on data anImtum a value Every C++ program has at least one function, main() When your program starts, mam() is called automatically main() might call other functions, some of which might caU still others Each function has its own name, and when that name is encountered, the execution of the ogram branches to the body of that function When the function ietonis, execution resumes or the next line of the calling function. When a program calls a function, execution switches to the function and then resumes at the line after the function call. Well-designed functions perform a specific and easily .undeitood task. Complicated tasks should be broken down into multiple functions, and theieathcan be ahled mturn Eunctionseome in two varieties. user-delmeci and built-in r Bu1144n functions are part of your compiler packagethey are upplied by the mmfacturer for your. use. : DcIaring and Defining Functions using functions in your program requires that you first declare the function and that you then define-the function. The declaration tells the compiler the name, return type; and parameters of the.function. The definition tells the: compiler how the function works.No function can be called from any other ftmctio,i that hasnt first been decIared. The declaration of a function is called its prqtotype.

Declaring the Fujction There are three ways to declare a function 0 Write your prototype into a file, and then use the #include directive to include it in your program. 53

0. Write the prototype into the file in which your function is used. 0 define the function before it is called by any other function. When you do this, the definition acts as its own declaration. Although you cn define the function before using it, and thus avoid the necessity of creating a function prototype, this is not good programming practice foi three reasons. First It is a bad idea to require that functions appear in a file in a paqicular order Doing so makes it hard to maintain the program as requirements change. Second, it is possible that function A() needs to be able to call function BO, but functioi\ B() also needs to be able tcall function A() under some circumstances. It is not possible to define function AO before you define function B() and also to define function 80 before you define function AO, so at least one of them must be declared in any case. Third, function prototypes are a good and powerful debugging technique. If your prototype declares that your function takes a particular set of parameters, or that it returns a particular type of value, and then your function does not match the prototype, the compiler can flag your error instead of waiting for it to show itself when you run the program.

Function Prototypes Many of the built-in functions you use will have their function prototypes already written in the files you include in your program by using #include. For functions you write yourself, you must include the prototype. The function prototype is a statement, which means it ends with a semiclon. It consists of the functions return type, name, and parameter list. The parameter list is a list of all the parameters and their types, separated by commas. The function prototype and the function definition must agree exactly about the return type, the name, and the parameter list. If they do not agree, you will get a compile-time error. Note, however, that the function prototype does not need to contain the names of the parameters, just their types. A prototype that looks like this is perfectly legal: long Area(int, int); This prototype declares a function named Area() that returns a long and that has two parameters, both integers. Although this is legal, it is not a good idea. Adding parameter names makes your prototype clearer. The same function with named parameters might be long Area(int length, mt width); It is now obvious what this function does and what the parameters are. Note that all functions have a return type. If none is explicitly stated, the return type defaults to mt. Your programs will be easier to understand, however, if you explicitly declare the return type of every function, including mainQ. A function declaration and the definition and use of that function.

54

enclosed in braces, even when it consists of only one statement, as in this case. Defining the Function The definition of a function consists of the function header and its body. The header is exactly like the function prototype, except that the parameters must be named, and there is no terminating semicolon.The body of the function is a set of statements enclosed in braces.

Functions

55

A function prototype tells the compiler the return type, name, and parameter list. Func-tions are not required to have arameters, and if they do, the prototype is not required to list their names, only their types. A prototype always ends with a semicolon (;). A function definition must agree in return type and parameter list with its prototype. It must provide names for ali the parameters, and the body of the function definition must be surrounded by braces. All statements within the body of the function must be terminated with semicolons, hut the function itself is not ended with a semicolon; it ends with a closing brace. If the function returns a value, it should end with a return statement, although return statements can legally appear anywhere in the body of the function. Every function has a ieturn type. If one is not explicitly designated, the return type will be in Be sure to give every function an explicit return type. If a function does not return a value, its return type will be void. Function Prototype Examples long FindArea(long ieng*k. long width); // returns long, has two parameters . void PrintMessage(int messageNumber); II returns void, has one parameter jut GetChoice . // returns int, has nopammeters BadFunctionO; 7/ returns int,, has no parameters Function Definition Examples long Area(tongl,longw) I *. .. .. return l*w; void PrintMessage(int whichMsg) :[.wNs= 0:. cout << Hello.\n; if (whichMsg == 1) .cout << Coodbye.\n; if(whichMsg>1) cout <<im confused.\n; Function Statements There is virtually no limit to the number or types of statements that. can be in a function body. Although. you cant define another function from Wi in a functiv, you can call a function, and of course main() does just that in nearly every C++ program. Functions can even call themselves, which is discussed soon, in the section on recursion. Although there is no limit to the size of a function in C++, well-designed functions tend to be small. Many programmers advise keeping your functions short enough to fit on a single screen so that you can see the entire function at one time. This is a rule -of thumb, often broken by very good programmers, but a smaller function is easier to understand and maintain.Each function should carry out a single, easily understood task. If your functions start getting large, took for places where you can divide them into coMponent tasks. 56

Function Arguments Function arguments do not have to all be of the same type. it is perfectly reasonable to write a function that takes an integer, two longs, and a character as its arguments. Any valid C++ expression can be a function argument, including constants, mathematical- and logical expressions, and other functions that return a value. Using Functions as Parameters to Functions Although it is legal for one functioh to take as a parameter a second function that returns a value, it can make for code that is hard to read and hard to debug. As an example, say you have the functions doubleO, tripleO, squareO, and cubeO, each of which returns a value. You could write Answer = (double(triple(square(cube(myVal ue))))); This statement takes a variable, my Value, and passes it as an argument to the function cubeO, whose return value is passed as an argument to the function squareO, whose return value is in turn passed to tripleO, and that return value is passed to doubleO. The return value of this doubled, tripled, squared, and cubed number is now passed to Answer. Q. 46. What do you mean by function overloading? Discuss with the help of program. Ans.C++ enables you to create more than one function with the same name. This is called function overloading. The functions must differ in their parameter list, with a different type of parameter, a different number of parameters, or both. Heres an example: mt myFunction (int, int); mt myFunction (long, long); mt myFunction (long); myFunction() is overloaded with three different parameter lists. The first and second versi.ons differ in the types of the parameters, and the third differs in the number of parameters. The return types can be the same or different on overloaded functions. You should note that two functions with the same name and parameter list, but different return types, generate a compiler error. Function overloading is also called function polijiiioi plasm. Poly means many, and morph means form: a polymorphic function is many-formed. Function polymorphism refers to the ability to overload a function with more than one meaning. By changing the number or type of the parameters you can give two or more functions the same function name, and the right one will be called by matching the parameters used. This allows you to create a function that can average integers, doubles, and other values without having to create individual names for each function, such as: AveragelntsQ, AverageDoublesO, and so on. Suppose you write a function that doubles whatever input you give it. You wou1d like to be able to pass in an mt. a long, a float, or a double. Without function overloading, you would have to create four function names: mt Doublelnt(int); 57

long DoubleLong(long); float DoubleFloat(float); double DoubleDouble(douhle); With function overloading, you make this declaration:

This is easier to read and easier to use. You dont have to worry about which one to call; you just pass in a variable, and the right function is called automatically. A demonstration of function polymorphism.

58

Q. 47. What are the inline functions? Explain with an example. Or Discuss the inline function using suitable programming example. Ans. Inline Functions: When you define a function, normally the compiler creates just one set of instructions in memory. When you call thefiinction, execution of the program jumps to those instructions, and when the function returns, execution jumps back to the next line in the calling function. If you call the function 10 times, your program jumps to the same set of instructions each time. This means there is only one copy of the function, not 10. There is some performance overhead in jumping in and out of functions. It turns out that some functions are very small, just a line or two of code, and some efficiency can be gained if the program can avoid making these jumps just to execute one or two instructions. When programmers speak of efficiency, they usually mean speed: the program runs faster if the function call can be avoided. 59

If a function is declared with the keyword inline, the compiler does not create a real function: it copies the code from the inline function directly into the calling function. No jump is made; it is just as if you had written the statements of the function right into the calling fuhcion. Note that inline functions can bring a heavy cost. If the function is called 10 times, the inline code is copied into the calling functions each of those 10 times. The tiny improvement in speed you might achieve is more than swamped by the increase in size of the executable program Even the speed increase might be illusory. First, todays optimizing compilers do a terrific job on their own, and there is almost never a big gain from declaring a function inline. More important, the increased size brings its own performance costWhats the rule of thumb? If you have a small function, one or two statements, it isa candidate for inline When in doubt, though, leave it out Demonstrates an inline function.

Output: Enter a number to work with: 20 Target: 40 Target: 80 Target: 160 60

Q. 48. What are the various advanced preprocessor statements ? Or Write a note on Advanced preprocessor operators.

Ans. Preprocessors: #include : The preprocessor is used to give a special instruction to the compiler. It is typically placed at the beginning of a line and it is followed by a word that would perform an action. The formula to use the preprocessor is: #action What-To-Do There are various actions you could ask the compiler to perform. The #include is used to include an external file in the currert file. The file to include is called a header file, a library, or another kind of file you want the compiler to consider before going any further. For example, to include one of the header files that shipped with 1kb, such as calendar.h, you can write - #include <calendar.h> To include one of your header files when you wiWhaie created one, you can write #include Circle.h Preprocessors: #define: The #define, called a directive, is used to direct the compiler to create or perform a (small) action. This action is called a macro. For example, you can ask the compiler to use Rio de Janeiro whenever it sees RDJ. To do that you can write #define RDJ Rio de Janeiro If you use the word RDJ in your program, the compiler would replace it with the defined name. You can also use the #define directive to create words that would be replaced with numeric values. Here is an example: #include <iostream> using namespace std; using namespace System; #define RDJ Rio de Janeiro #define Print(Sentence) Console::WriteLine(Sentence) mt main() cout << City: <<RDJ << Print( Welcome to the Wonderful World of C++/CLI.); return 0; This would produce: City: Rio de Janeiro Welcome to the Wonderful World of C++/CL1. 61

Press any key to continue. Preprocessors: #pragma : Every compiler in the industry has characteristics that distinguish it from other compilers. When building or compiling a program, you should be sensitive to the environment the program would he running. The #pragma preprocessor is used to give specific instructions to the compiler based on the particular compiler that is being used to create the program. This means the #pragma directive completely depends on the compiler you are using. The C Preprocessor The preprocessor more or less provides its own language which can be a very powerful tool to the programmer. Recall that all preprocessor directives or commands begin with a #. Use of the preprocessor is advantageous since it makes: 1. programs easier to develop, 2. easier to read, 3. easier to modify 4. C code more transportable between different machine architectures. The preprocessor also lets us customise the language. For example to replace { ... ) block statements delimiters by PASCAL like begin ... end we can do: #define begin #define end During compilation all occurrences of begin and end get replaced by corresponding or ) and so the subsequent C compilation stage does not know any difference!!!. Lets look at #define in more detail #define: Use this to define constants or any macro substitution. Use as follows: #define <macro> <replacement name> For Example #define FALSE 0 #define TRUE !FALSE We can also define small functions using #defie. For example max. of two variables: #define max(A,B) ((A) > (B) ? (A):(B)) ? is the ternary operator in C. Note: that this does not define a proper function -max. So if in our C code we typed something like: x max(q+r,s+t); after preprocessing, if we were able to look at.the code it would appear like this: x = ( (q+r) > (rs) ? (q+r) : (s+t)); Other examples of #define could be: 62

#define Deg.Jo_Rad(X) (X*MPI/ 180.0) /* converts degrees to radians, M_PI is the value of pi and is defined in math.h library */ #define LEFT_SHIFT_8 <<8 NOTE: The last macro LEFTSHIFr_8 is only valid so long as replacement context is valid i.e. x = y LEFT_SHIFT_8. #undef: This commands undefined a macro. A macro must be undefined before being redefined to a different value. #include: This directive includes a file into code. It has two possible forms: #include <file> or #include file file looks for a file in the current directory (where program was run from) Included files usually contain C prototypes and declarations from header files and iacii (algorithmic) C code (SEE next Chapter for reasons) #if Conditional inclusion: #if evaluates a constant integer expression. You always need a #endif to delimit end of statement. We can have else etc. as well by using #else and #elif else if. Another common use of #if is with: #ifdef if defined and #ifndef if not defined These are useful for checking if macros are set perhaps from different program modules and header files. For example, to set integer size for a portable C program between TurboC (on MSDOS) and Unix (or other) Operating systems. Recall that TurboC uses 16 bits/integer and UNIX 32 bits/integer. Assume that if TurboC is running a macro TURBOC will be defined. So we just need o check for this: 63

As another example if running program on MSDOS machine we want to include file msdos.h otherwise a default.h file. A macro SYSTEM is set (by OS) to type of system so check for this:

Preprocessor Compiler Control You can use the cc compiler to control what values are set or defined from the command line. This gives some flexibility in setting customised values and has some other useful functions. The -D compiler option is used. For example: cc -DLINELENGTH8O prog.c -o prog has the same effect as: #define LINELENGTH 80 Note that any #define or #undef within the program (prog.c above) override command line settings. You can also set a symbol without a value, for example: cc -DDEBUG prog.c -o prog Here the value is assumed to be 1. The setting of such flags is useful, especially for debugging. You can put commands like: #ifdef DEBUG print(Debugging: Program Version 1\); #else print(Program Version 1 (Production)\); #endif Also since preprocessor command can be written anywhere in a C program you can filter out variables etc for printing etc. when debugging: xy*3; #ifdef DEBUG print(Debugging: Variables (x,y) = 64

#endif The -E command line is worth mentioning just for academic reasons. It is not that practical a command. The -E command will force the compiler to stop after the preprocessing stage and output the current state of your program. Apart from being debugging aid for preprocessor commands and also as a useful initial learning tool (try this option out with some of the examples above) it is not that commonly used. Other Preprocessor Commands There are few other preprocessor directives available:

number string informs the preprocessor that the number is the next number of line of input. string is optional and names the next line of input. This is most often used with programs that translate other languages to C. For example, error messages produced by the C compiler can reference the file name and line numbers of the original source files instead of the intermediate C (translated) source files.

Q. 49. What do you mean by Recursions? Write a program for Fibonacci series using recursion.

Ans. A function can call itself. This is called recursion, and recursion can be direct or indirect. It is direct when a function calls itself; it is indirect recursion when a function calls another function that then calls the first function. Demonstrates recursion using the Fibonacci series.

65

Recursion is a very tricky part of advanced programming. It is presented here because it can be very useful to understand the fundamentals of how it works, but dont worry too much if you dont fully understand all the details. 66

Q. 50. Explain the Dynamic Memory Management functions provided by C++.Or Discuss the concept Dynamic Memory Management

Ans. In the case of C++, dynamic memory management is handled by the new and delete operators. In most cases, handling memory involves the common action of making sure to delete any pointer that was allocated with new when done with it. However, the generated C++ classes contain the concept of memory ownership which makes it possible for a user to assign ownership of memory to the container object being populated. This makes freeing the memory much easier. Instead of having to track each individual item, the class does it for you. Therefore, when the main container class is deleted at the end of use, all memory objects within that class that have had ownership assigned to the container are deleted as well. In cases where memory ownership can be assigned to the container class, the class may contain assignment methods that contain a boolean ownMemory argument. If this argument is set to true, the class will assume the object being transferred has been allocated dynamically using the new operator and will invoke delete on the object from within its destructor. An example of a method with an ownMemory argument is the append method generated for a repeating element class (this is taken from the cpp/sample/sim pleA rray sample program):

In this case, the item list is a list of strings. By using the second form of the append method to add an item to this list, memory ownership can be transferred to the list container. Then when the list is deleted, all of the objects with transferred ownership will be deleted as welL lhere is also a setOwnMemorij method defined in the OSBase Type base class. This method can also be used to transfer ownership of dynamic memory to the container class. When an XML instance is decoded, the decoder automatically transfers memory ownership to the container objects. It is therefore not necessary for the user to worry about freeing memory for any of the items within a returned class instance. Deleting the 67

main object is all that is necessary to free the memory of all of the items within.

Q. 51. Explain in brief about inheritance with a small working example. Or Wh do you understand by inheritance in C++ ? Explain with examples.

Ans. Its a common saying. It suggests that we carry over some oLthe traits of our parents. Not only that we carry over their traits, but also, their belongings. They give us whatever they have except for a few things, which they treat as personnel or private to them. Except for these few, everything else, by default, falls in our lap. They serve us as a base for our growth. Apart from what we get from our parents in legacy, we also have some personnel traits and acquire our own belongings, which prove to be an extension to the subtle base our parents provide. This is the phenomenon of INHERITANCE. In this whole process one unique feature that comes out is that we as inheritors are not required to work for what our parents have acquired - we simply extend it. However at the application point the effect is of our possessing both - into our account - what our parents had and what we have. In OOPS this concept is followed, as it is, by extending classes. Inheritance is a real-life concept of deriving something more specific from a generalised existing thing, children have their own mental, physical and spiritual traits but they also inherit thefeatures of their parents. Inheritance, as a mechanism of extending classes, involves deriving a ne4 class from an old one. (existing one). The existing/old class is referred to as base class and the new one is known as the derived class. Classes driven and pulled have been inherited from vehicles class. Class driven serves base class for twowheelers and four-wheelers. Similarly, cart and rikshaw have been inherited from pulled class. The direction of arrow in fig. above should not be a source of confusion for the reader. Some texts show the arrow pointing from base class to derived class, while other texts show it in reverse order (representing inherited from relationship). The derived class inherits some or all of the traits from the base class. Why Inheritance? Inheritance truly supports REUSABILITY feature of Object Oriented Programming (OOP). If a class has been tested, debugged and used many times, then the effort of developing and testing the class again can be saved by making use of same class. If changes are required, programmerscan derive another class from already existing one and make necessary changes in the derived of class. A class fun developed by Tom can be used by his friends X, Y, Z, A, B and so on (of course! only as long as Tom is willing to do share). Different Types of Inheritance Single Inheritance A derived class has only one base class. In the figure, class B is inherited from Class A Multiple Inheritances 68

A class with several base classes is known as multiple inheritance. Class C inherits from both A and B Hierarchical Inheritance. In such a form of inheritance, the traits of one class are inherited by more than one class. Multilevel Inheritance. The mechanism of deriving a class from .another derived class is known as multilevel inheritance. Hybrid Inheritance This form of inheritance combines two or more forms of inheritance Above the child (or rather grand child) inherits the properties of mother and father, who have in turn, inherited from grandparents. Defining Derived Classes; Visibility Modes In order to define a class having name derived-class-name from a class having name base-class-name, the following syntax is used class derived-class-name : visibility-mode base-class-name The colon indicates that the derived-class-name has been derived from base-classmd name. It is important to learn about visibility modes while inheriting from a class REMEMBER THAT PRIVATE DATA MEMBERS OF BASE CLASS WILL NOT BE INHERITED IN ANY CASE. When a class is privately inherited, its effect is that all public members of base class become private in the derived class, such that they are inaccessible to the objects of the derived class. On the other hand, when a class is publicly inherited into another class, the public members of base class remain public inthe derived class, such that they are accessible to the objects of derived class. The syntax illustration is given below:

69

70

D.addO; Ddisplay 0; Thus the derived class has data member h and functions return a( ), show a( ) and get_ab( ), which it has acquired through public inheritance from base. Let us now modify the earlier example a bit by inheriting the derived class privately. Notice the consequent changes design carefully 71

class base

72

Protected : To Make a Private Member Inheritable A major problem that remains unsolved is how to inherit a private data member, if it is needed in derived class. The private label does not allow to break the walls of encapsulation whereas making such a data member public would make it accessible to outside world besides imparting it inheritance capability. The answer is protected data member. The visibility label protected ensures that the members declared under it are accessible to the derived class through inheritance. Further, protected members cannot be accessed by the functions outside the class. In a way, they combine the functionality of private and public members into one label. It is important to learn that behavior of protected data members in derived class depends upon visibility mode of inheritance. The following example shows the use of protected visibility label: # include <iostream, h> class base

73

In the given example, the protected member a became private in derived class. But it canno be referred directly in main. Further, the function get_ab( ) can be completely removed by accepting the input for a and b in the add () function itself. When using protected visibility label, inheritance should be public if we expect more classes to be derived from the derived class. (so that the protected member lands as protected in the derived class). In case the inheritance is not needed further after derived class, it is advisable to inherit privately. That is why, the last example uses private inheritance. The table given in fig. 7.9 summarizes the inheritance rules: Public inheritance Private Inheritance Private Not inherited Not inherited Protected Protected Private Public Public Private 74

Q. 52. Write note on Macros in c++.

Ans. By defining a macro, one can define a symbol (a token) to be equal to some C++ code and use that symbol wherever the code is required in program. When the source file is preprocessed, every occurrence of a macros name is replaced with its definition. A common use of this feature is o define a symbolic name for a numerical constant and use the symbol instead of the numbers in your program. This improves the readability of the source code, because with a descriptive name, you are not left guessing why a p&rticular number is being used in the program. You can define such macros in a straightforward manner using the # define directives as follows. # define P1 3.14159 # define BUFS1ZE 512 Once these symbols ate defined,you can use PT and BUFSIZE instead of the numerical constants through out the source file. The capability of macros, however go well beyond replacing a symbol for a constant. Macros can accept parameters and replace each occurrence of a parameter with the value provided for it when the macro is used in the program. Thus, the code resulting from the expansion of a macro can change depending on the parameter you provide. When using the macro. For example, the following macro accepts a parameter and expands to an expression designed to calculate the square of the parameter: # define square(x) ((x)*(x)) If you use square(z) in your program, it becomes ((z)*(z)) after the source of file is processed. This macro is essentially equivalent to a function that computes the square of its arguments. You do not, however, have the overhead of calling a function, because the expression gencrated by the macro is placed directly in the source file. New feature provided by ANSI C preprocessor is the stringizthg operator, which makes a string out of any parameter with a prefix by putting that parameter in quotes. Suppose we want to print out the value of certain variables in a program. Instead of calling the cout directly, we can define a utility macro that will do the work. The required macro to do above job is given below: # define Trace (x) 75

Then, to print out the value of a variable named currentjndex. For instance we can smply wrtte this: Trace (current index); When the preprocessor expands this, it generates the following statement: cout <<current_index << <<current index <</n;

Q. 53. Why use unnecessary parentheses when precedence will determine which operators are acted on first?

Ans. Although it is true that the compiler will know the precedence and that a programmer can look up the precedence order, code that is easy to understand is easier to maintain.

Q. 54. If the relational operators always return 1 or 0, why are other values considered true?

Ans. The relational operators return 1 or 0, but every expression returns a value, and those values can also be evaluated in an if statement. Heres an example: if((x=a+b)==35) This is a perfectly legal C++ statement. It evaluates to a value even if the sum of a and h is not equal to 35. Also note that x is assigned the value that is the sum of a and b in any case. Q.55. What effect do tabs, spaces, and new lines have on the program?

Ans, Tabs, spaces, and new lines (known as whitespace) have no effect on the program, although judicious use of whitespace can make the program easier to read. Q. 56. Why not make all variables global?

Ans. There was a time when this was exactly how programming was done. As

76

programs became more complex, however, it became very difficult to find bugs in programs because data could be corrupted by any of the functionsglobal data can be changed anywhere in the program. Years of experience have convinced programmers that data should be kept as local as possible, and access to changing that data should be narrowly defined. Q. 57. When should the keyword inline be used in a function prototype?

Ans. If the function is very small, no more than a line or two, and wont be called from many places in your program, it is a candidate for inlining.

Q. 58. Why arent changes to the value of function arguments reflected in the calling function ?

Ans. Arguments passed to a function are passed by value. That means that the argument in the function is actually a copy of the original value. This concept is explained in depth in the Extra Credit sectionthat follows the Workshop.

Q. 59. Are negative numbers true or false?

Ans. All nonzero numbers, positive and negative, are true. Q. 60. How big is a class object?

Ans. A class objects size in memory i determined by the sum of the sizes of its member variables. Class methods dont take up room as part of the memory set aside for the object. Some compilers align variables in memory in such a way that two-byte variables actually consume somewhat more than two bytes. Check your compiler manual to he sure, but at this point there is no reason to be concerned with these details. 77

Q. 61. Why shouldnt I make all the member data public?

Ans. Making member data private enables the client of the class to use the data without worrying about how it is stored or computed. For example, if the Cat class has a method GetAge, clients of the Cat class can ask for the cats age without knowing or caring if the cat stores its age in a member variable, or computes its age on the fly. Q. 62. Is there ever a reason to use a structure in a C++ program?

Ans.. Many C++ programmers reserve the struct keyword for classes that have no functions. This is a throwback to the old C structures, which could not have functions. Frankly, I find it confusing and poor programming practice. Todays method less structure might need methods tomorrow. Then youll be forced either to change the type to class or to break your rule and end up with a structure with methods.

Q. 63. What are the characteristics of NTFS?

Ans. Windows 2000 NTFS file systems are newer than Windows NT NTFS file systems. In order for Windows NT and Windows 2000 to use the Windows 2000 file system together, the Windows NT system must have service pack 4 or later installed. o Filenames up to 255 characters long o Filenames preserve case but are not case sensitive. o Filenames exclude / \ <>: I o Supports built in file compression as a file attribute. Compression is applied to files in a folder if that folder has its compression attribute set. Also optionally sub folders and their contents may be compressed. Compression is not supported if the cluster size is above 4K in size. Moved files retain their compression attribute, but if they are copied they will assume the compression attribute of the target folder. o Provides automatic transaction tracking of disk activity for correcting corrupt or failed operations. o Supports auditing. o Provides sector sparing. O There is a recycle bin for each user. o Windows 16 bit and DOS environments cant use this filesystem. 78

o Maximum file or partition size of 16 exabytes. O Supports file sharing with Macjntosh clients.

Q. 64. Discuss the various functions used for dynamic memory management. OR Explain the concept of dynamic memory allocation.

Ans. Dynamic Memory Allocation and Dynamic Structures Dynamic allocation is a pretty unique feature to C (amongst high level languages). It enables us to create data types and structures of any size and length to suit our programs need within the program. We will look at two common applications of this: 0 dynamic arrays 0 dynamic data structure e.g. linked lists Malloc, Sizeof, and Free The Function malloc is most commonly used to attempt to grab a continuous portion of memory. It is defined by: void *malloc(size_t number_of_bytes) That is to say it returns a pointer of type void * that is the start in memory of the reserved portion of size number_of_bytes. If memory cannot be allocated a NULL pointer is returned. Since a void * is returned the C standard states that this pointer can be converted to any type. The size_t argument type is defined in stdlib.h and is an unsigned type. So: char *cp; cp = malloc(100); attempts to get 100 bytes and assigns the start address to cp. Also it is usual to use the sizeof() function to specify the number of bytes: mt *jp; ip = (mt *) malloc(100*sizeof(int)); Some, C compilers may require to cast the type of conversion. The (mt *) means 79

coercion to an integer pointer. Coercion to the correct pointer type is very important to ensure pointer arithmetic is performed correctly. I personally use it as a means of ensuring that I am totally correct in my coding and use cast all the time. It is good practice to use sizeof() even if you know the actual size you want it makes for device independent (portable) code. sizeof canbe used to find the size of any data type, variable or structure. Simply supply one of these as an argument to the function. SO: mt i;

When you have finished using a portion of memory you should always free() it. This allows the memory freed to be aavailable again, possibly for further malloc() calls The function free() takes a pointer as an argument and frees the memory to which the pointer refers. Calloc and Realloc There are two additional memory allocation functions, Calloc() and ReaflocO. Their prototypes are given below: void *calloc(size t num elements, size_t element_size); void *realloc( void *ptr, size_t new size); Malloc does not initialise memory (to zero) in any way. If you wisl to initialise memory then use calloc. Cailoc there is slightly more computationally expensive but, occasionally, more convenient than malloc. Also note the different syntax between calloc and malloc in that calloc takes the number of desired elements, num elements, and element_size, element_size, as two individual arguments. Thus to assign 100 integer elements that are all initially zero you would do: int*ip; ip = (mt *) calloc(100, sizeof(int)); Realloc is a function which attempts to change the size of a previous allocated block of memory. The new size can be larger or smaller, If the block is made larger then the old contents remain unchanged and memory is added to the end of the block. If the size is made smaller then the remaining contents are unchanged. 80

If the original block size cannot be resized then realloc will attempt to assign a new block of memory and will copy the old block contents. Note a new pointer (of different value) will consequently be returned. You must use this new value. If new memory cannot be reallocated then realloc returns NULL. Thus to change the size of memory allocated to the *p pointer above to an array block of 50 integers instead of 100, simply do: ip = (mt *) calloc( ip, 50); Linked Lists Let us now return to our linked list example: typedef struct { mt value; ELEMENT *next. ELEMENT; We can now try to grow the list dynamically: link = (ELEMENT *) malloc(sizeof(ELEMENT)); This will allocate memory for a new link. If we want to deassign memory from a pointer use the freeO function: free(link) -

Full Program: queue.c A queue is basically a special case of a linked list where one data element joins the list at the left end and leaves in a ordered fashion at the other end. The full listing for queue.c is as follows:

81

82

83

84

else( listpointer = (struct listelement *) malloc (sizeof (listelement)); listpointer -> link NULL;. listpointer -> dataitem = data; return listpointer; listelement * Removeltem (listelement * listpointer) listelement * tempp; printf (Element removed is %d\n, listpointer -> dataitem); tempp = listpointer -> link; free (listpointer); return tempp;

85

Q. 65. Write a simple C++ program showing the working of Arrays of points

Ans. Arrays and Pointers To fully understand the workings of C you must know that pointers and arrays are related. An array is actually a pointer to the 0th element of the array. Dereferencing the array name will give the 0th element. This gives us a range of equivalent notations for array access. In the following examples, arr is an array. There are some differences between arrays and pointers. The array is treated as a constant in the function where it is declared. This means that we can modify the values in the array, but not the array itself, so statements like arr ++ are illegal, but arr[n] ++ is legal. Since an array is like a pointer, we can pass an array to a function, and modify elements of that array without having to worry about referencing and de-referencing. Since the array is implemented as a hidden pointer, all the difficult stuff gets done automatically. A function which expects to he passed an array can declare that parameter in one of two ways. Either of these definitions is independent of the size of the array being passed. This is met most frequently in the case of character strings, which are implemented as an array of type char. Give any program of array of pointer. Q. 66. What is program?

Ans. A computer program is one or more instructions that are intended for execution by a computer. Computer programs are the results from the compilation or interpretation of programming languages, are embedded into hardware, or may be manually inputted to the central processor of a computer. A computer program does nothing unless its instructions are executed by a central processor. A computer program in the form of a human-readable, computer programming language is called source code. Source 86 code may be converted into an executable image by a compiler or executed immediately with the aid of an interpreter.

Compiled computer programs are commonly referred to as exectah1es, binary images, or simply as binaries a reference to the binary file format commonly used to store the executable code.

Q. 67. How Class differs from a structure ? Or How a class differs from a structure ? What is an ADT?

Ans. In a Class, the member data and function are by default private. Where as in structures they are by default public. Structures are used to hold data only and classes are used to hold both data and functions. However, in C++ , structures can in fact hold both data and functions. In C they can hold only data. The syntactical distinction between structures and classes, in C++ , is minimal, so in theory they can be used almost interchangeably. But most C++ programmers use structures exclusively for data. Classes are used to hold both data and functions. Here is an example that shows how structure members can be initialized when the structure variable is defined. #include<iostream .h> struct mt modelnumber; mt partnumber;

87

88

In the above program the class distance contains two data items feet and inthes. And three fucntin setdistO, getdist() and showdistO . In mam() we define two objects_of the class dist I and dist2.Distl is given a value using setdist() and dist2 is given the value supplied by the user.

Q. 68. What is the need of recursion? Write a Program to find the factorial of a number using recursion.

Ans. In C++ , it is possible for the functions to call themselves. A function is called uRecursionI If a statement within the body of a function calls the same function. Sometime called circular definition, recursion is thus the process of defining89

something in terms of itself. This is an example of recursion. Try to understand it on your own. Let us repeat thatC++ functions may be used recursively; that is, a function may call itself either directly or indirectly. Recursion is very similar to looping but there is a major difference between looping and recursion is: o In looping when control variable have a value it will immediately used and at the end of loop last value is created but in recursion every time calculated value is preserved in a stack and at the end, recursion process value in reverse order. o Recursion is fast as compared to loops o Recursion reduce the usage of loops o Some of the problems can only be solved using recursion like ACKERMANN FUNCTION, TOWER OF HANOI. Program Example

90

Q. 69. What do you understand by operator overloading? Using Classes, write a program to add two complex numbers?

Ans. Overloading is primarily useful for creating smart pointer, that is, objects that act like pointers and also perform some action where ever an object is accessed through them For example , one can define a class Recptr for accessing objects of class Rec stored on disk. Rec_prts constructor takes a name that can be used to find the object on disk. Rec_.ptr::operator () brings the object into main memory when accessed thorough its Rec_ptr, and Rec_ptrs destructor eventually writes the updates object back out to disk C++ supports a set of operator for its built in types. But, most concepts for which operators are used are not built in types . But , most concepts for which operators are used are not built in types in C++, so they have to be represented as user defined types. For example, if we which to use complex arithmetic, matrix algebra, logic signals or character strings in C++ , wee use classes to represent these notions. Defining operators for such classes allows a programmer to have more conventional and convenient notation for manipulating objects than could he achieved using only the basic functional n\notation. In the example below: Class complex 91

define a simple implementation of the concept of complex numbers. A complex is represented b a pair of double precision floating point numbers manipulated by the operators + and * complex:: operator + ()and complex :: operator * () provide meaning for + and * respectively. For example, if b and c are of type complex b+c mean b. operator+( c). We can now write the conventional interpretation of complex expressions. / Prog. to find the sum of two complex numbers */

Q. 70. Can we have more than one constructor in a class 7 if yes, explain the need for each situation, Ans. To cope with assignments and initialization of complex variables with scalars, we have to use conversion of a scalar (integer or floating a point number) to a complex. For example: Complex b3; // mean b.re3,b.imO A constructor taking a single argument specifies a conversion from its argument type to the constructors type. For example:

The constructor specifies the traditional embedding of the real line in the complex plane. A constructor is used for creating a value of a given type. The constructor is used when a value of a type is expected and when such a value can be created by a constructor from the value supplied as an initialize or assigned value. Thus a constructor requiring a single argument need not be called explicitly. For example: 92

Complex b3; Means Complex b=complex(3); A user define conversion is implicitly applied only if it is unique. When a constructor is explicitly declared for a type, it is not possible to use an initialize list as the initialize. For example: Complex zl= (6); / / error: complex has a constructor Complex z2={6,8); / / error: complex has a constructor Copy Constructor: A part from the explicitly declared constructors a class by default d\gets a copy constructor defined. A default copy constructor simply copies all members. A reference argument is used for the copy constructor because I must. The copy constructor defines what copying meansincluding what copying an argument means so writing. Complex:: comple.x (complex C): re(c.re),im(c.im){} / /error Is and error because any call would have invioded an infinite recursion. For other functions taking complex arguments we can use value arguments there is little difference between a function that takes a complex argument and one that takes a const complex & argument.

Q.71. Write a C++ Program showing the working of array to pointer.

Ans. Array are internally stored as pointers. The elements of an array can be accessed efficiently by using a pointer.

93

Thus, the address ofthefirst array flement can be expressed as either & arrfOJ simply arr. Prog Example

94

Q. 72. Write a function to add and delete a node in a link list?

95

96

Q. 73. What is CString class ? Write programs to overload + function for pncatenating two strings?

Ans. A CStringT object consists of a variable-length sequence of characters. CStringT rovides functions nd operators using syntax similar to that of Basic. Concatenation and mparison operators, together with simplified memory management, make CstringT objects easier to use than ordinary character arrays. By using different combinations of the BaseType and StringTraits parameters, CStringT objects can come in the following types, which are have been predefined by the AU libraries. If using in an ATL application: 97

CString, CStringA, and CStringW are exported from the MPC DLL (MFC8O.DLL), never from user DLLs. This is done to prevent CStringT from being multiply defined. The CString class is extremely easy, versatile, and memory-efficient. It have a number of functions that require the LPCSTR type, and reai the CString class is interchangeable with LPCSTR/const char*. This also Seems the best and easiest to work with while coding. However, it seems cString is only included for MFC projects. In order to use cString, one must include the AFX header, and apparently if I include the windows.h header. CStringT inherits from CSimpleStringT Class. Advanced features, such as character manipulation, ordering, and searching, are implemented by CStringT. i/C++ overloading sample class MyString

Q. 74. What are the logical operations?

Ans. The operations that we performing using logical operators are called logical operations. (Also give detail of the various logical operator).

Q. 75. Write a for top that will never the the central.

Ans. # include iostream.h>

98

Q. 76. How we can passing function into single dimension array?

Ans. Single Dimensional Arrays Sometimes its inconvenient to call a function that requires a long list of arguments. One way around this, is to store your variables into an array, then pass a POINTER to the array to the function. This method will be discussed in greater detail in the pointers section, but for now you need to know that the array isnt actually passed to the function - just the arrays location in the memory. This is known as PASS BY REFERENCE. The name of an array references the arrays location in the memory, its ADDRESS.

Notice that Ive left the size of the array blank in both the function declaration and definition - the compiler works it out for you; Also, when I called the function, I passed on the name of the array. This is the equivalent to passing &array[0] the address of the first element. Q. 77. Write short note on CPP application file.

Ans, Application.cpp File: Include dependency graph for Application.cpp: 99

100

You might also like