Wednesday, December 10, 2008
C++ INTERVIEW QUESTIONS PART 2
These are access specifiers for class data members and member methods.
1. Public: The data members and methods having public as access specifier can be accessed by the class objects created outside the class.
2. Protected: The data members and methods declared as protected will be accessible to the class methods and the derived class methods only.
3. Private: These data members and methods will be accessible from the class methods only, not from derived classes and not from objects created outside the class.
4. Internal: Some languages define internal as an access specifier which means the data member or method is available to all the classes inside that particular assembly.
5. Friend: A friend class or method can access all data of a class including private and protected data.
2. When is an object created and what is its lifetime?
An object is created when a class is instantiated. This is the time when memory is allocated to the object and the class constructor is called to initialize the data members.
3. What do you mean by multiple inheritance and multilevel inheritance?
Ans 1:
Multiple inheritance refers to a class being derived from two or more classes.
Multilevel inheritance refers to a class inheriting from a parent class which is itself derived from another class.
Multilevel inheritance is supported by all OOPs languages. Multiple inheritance is supported by C++, but not by Java and C#. Java and C# recommend that instead of multiple inheritance the design should be inheriting from one class and implementing other interfaces.
This solves the problems of having to declare 'virtual base classes' as in C++ which arises out of multiple copies of uppermost base class object in a class at inheritance level 3 onwards.
Ans 2:
Multiple: ClassA--extends-->ClassB, ClassA--extends--
>ClassC, ClassA--extends-->ClassD class A can Inherit all
the classes and can have access on all calss' public
properties and functions.
MultiLevel: ClassA-->ClassB-->ClassC-->ClassD and ClassD
will have the accesss on all the properties of its upper
level class like C,B and A
4. What are the main differences between procedure oriented languages and object oriented languages?
Ans 1:
1. Procedural languages enforce sequential processing of instructions. Object oriented languages may implement event driven processing.
2. Procedural languages store all data as global while OOPs languages support data encapsulation -- all related data is stored inside one object and only relevant data is shown to the user.
3. Facilities like function overloading and operator overloading (polymorphism) allow you to use same names and provide different functionality which avoids personalism in naming conventions. These overloaded versions are easy to use and remember.
Ans 2:
In procedural programming the main emphasis is on procedure while in object oriented the data is important part. on the same hand data is more secured in object oriented program.
-----------------------------------------------------------
Procedure Oriented Language:
---------------------------
PO Language is fully concentrates on Procedures/functions/methods. It normally works as a sequence of actions as seen in flowchart or in any algorithm. It follows top-down approach. It totally focuses on methods and not the data which is utilized by methods. In PO languages if data is used by many methods then its declared as global data but there is a problem if we do that, what is that, if we forgot or by mistake if we consume that data in some other method than it comes with problem. Mostly these scenarios happen in large systems.
Example: COBOL, PASCAL, C, FORTRAN etc.
Object Oriented Language:
------------------------
OO concepts says it think about data and bind that data and methods those are manipulating that data into one entity known as object and then utilize that object into system.
Example: C++, Java, C#, VB.Net etc.
There are some fundamental concepts of OO Language which a language has to follow to be a truly OO language.
• OBJECT
• CLASS
• ABSTRACTION
• ENCAPSULATION
• DATA HIDING / INFORMATION HIDING
• INHERITANCE
• POLYMORPHISM
5. What are generic functions and generic classes?
Ans 1:
Generic functions are functions which are not used for any particular datatype..they are useful for anydatatype Ex: if you write code for the Sorting program using templates then the function is useful for any data type to sort...Generic classes are same as generic functions
Ans 2:
Generic functions are the function which return void ptr... (void*)... Generic Classes are template classes...
Basicaly we implement both of them for reusability.. and abstraction..
6. What is the difference between pass by reference and pass by value?
Ans 1:
in pass by referance the parameters are passed as the address of the variables whereas in pass by value the variables are directly passed as parameters
Ans 2:
When using by reference there is no new variable just a alias to the memory address, if this parameters is not constant it is possible to change the content of that address.
When using by value a new variable will be created in memory and it is impossible to change the original content.
7. Why do we use virtual functions?
A function that is defined in a base class but overridden by the derived class is called a virtual function. To create virtual functions precede the function declaration in the base class with the keyword virtual. When a class containing a virtual function is inherited the derived class overrides the virtual function with its own definition. Virtual functions are like member functions however what makes them different is the capability to support run time polymorphism when accessed via a pointer. A base class pointer can point to an object of a derived class. When a base class pointer points to an object of a derived class that contains a virtual function, C++ determines which function version to call based on the type of object pointed by the base class pointer. This is runtime polymorphism as it can be determined at run time. In this way when different objects are pointed to then different versions of virtual functions are executed. Whenever a virtual function is defined all aspects of its prototype should match. Also virtual functions should be non static members of the class and they cannot be friend functions too. E.g. class base { public: virtual void display (); }; class derived: public{ public: virtual void display ();};base *p, b;derived d1, d2;p = &b;p->display (); //calls base class functionp = &d1;p->display (); //calls derived class function
8. What are virtual classes?
Detailed:
Classes can be abstract (and therefore are also base classes, see below). Member functions of classes can be marked virtual.
A class can have member functions that are virtual which means they can be overridden and redefined by sub-classes and allows run time polymorphism. Dr. Bjarne Stroustrup implies in the "The Design and Evolution of C++" that the keyword "virtual" was borrowed from a language called Simula and that virtual is the 'Simula and C++ term for "may be redefined later in a class derived from this one"'.
Now this can be taken to the extreme in that no definition may be provided in the class that initially declares a virtual function - it is a pure virtual function:
class A
{
virtual do_something() = 0; // = 0 => pure virtual function
virtual ~A() {}
};
A consequence of doing this is that you cannot create objects of class A as doing so and calling do_something on the object would result in a call to a non-existent function. You have to derive from A and override do_something providing a function definition (i.e a function implementation) for it. Because you cannot create objects of class A, class A is known as an abstract class. In fact because it has to be used as a base class (that is other classes have to be derived from it to be useful) the proper term is abstract base class (or ABC).
The above is not quite correct. In fact you can provide a definition for a pure virtual function. However this function can only be called directly using compile time (i.e. static) function call despatch, not through the run time polymorphic dynamic despatch mechanism. Anytime you have a pointer or reference to an object of an ABC (abstract base class) like class A and you call a pure virtual function on it that has not been overridden the compiler will probably have to issue a dynamic call using the dynamic call despatch mechanism, which still has a pure (i.e. non-existent) definition for the function and Bang! Your program would crash, or possibly terminate with some message about a pure virtual function being called. For this reason even if you do provide a function definition for a pure virtual member function the class is still abstract and you still cannot create objects of the class or any class derived from it that has not provided definitions for all pure virtual functions.
OK, so you are probably a little confused after that, so I have provided some more information on the calling mechanisms used by C++ below. It is not really directly relevant to your question so only read it if you are interested, and if you do then please ask followup questions if you require clarification as it is not an easy thing to describe (so sorry if it is not 100% clear!).
Before doing so I shall mention briefly that a class used as a base class to some derived class can be specified as a virtual base class. When this occurs a further class deriving from two base classes that both derive from a common virtual base class only get one copy of the common virtual base class:
class Base {};
class Middle1 : public Base {};
class Middle2 : public Base {};
class Derived : public Middle2 : public Middle1 {};
The above class hierarchy does not use virtual base classes and Derived contains two Base sub-objects – one from Middle1 and the other from Middle2. Often this is not at all what is required. What is required is that Derived contain one base sub-object, one Middle1 sub-object and one Middle2 sub-object. This is where virtual base classes come in:
class Base {};
class Middle1 : virtual public Base {};
class Middle2 : virtual public Base {};
class Derived : public Middle2 : public Middle1 {};
Note that the virtual-ality is only applied for a specific use of the Base type – when it is being used as a base class. It does not affect Base itself in other circumstances. For more information see for example Chapter 15 of "The C++ Programming Language 3rd edition" by Bjarne Stroustrup.
You should also check out the C++ FAQ lite at http://www.parashift.com/c++-faq-lite/, for virtual function, ABCs and virtual base classes and loads of other common C++ topics.
Now onto some explanation of function calling in C++. Note that I have made simplifications so as to try to get the main points across.
In general in C++ function calls, whether they are to member functions or free functions (i.e. non member functions) a made using a static despatch mechanism. That is, they are wired up at compile time. It works something like this:
A function implementation, or definition if you like, has an address. The compiler compiles the contents of the function and allocates storage for the code it contains.
If you call the function the compiler makes a direct reference to the address of the function in the code at the call site:
; func();
call 0x00ab0cf0
If you ask for an assembler listing from a compiler (optional output controlled with command line options) and are lucky the listing will use a symbol, here is a real example from a listing produced by MSVC++ 8.0 (the 2005 edition):
call ?FillArray@@YAIPAHI@Z ; FillArray
You can then look for further references to ?FillArray@@YAIPAHI@Z and find its assembler code definition, plus a load of other low level stuff, much of which is probably for the benefit of the linker.
Which brings up the problem of functions called that are defined in other modules. In these cases a similar call instruction is generated, but the symbol used is marked as an external function and it is up to the linker to fill in the details during linking.
In either case the result is the same - the addresses of the functions called in call instructions are fixed by the time the executable has been created. They are static in that when the program is executed these values will not change.
So what happens when you use the dynamic, runtime virtual despatch mechanism by using virtual member functions? Well basically the calls are made indirectly. This is normally (that is practically always) achieved by storing pointers to virtual member functions in a table, called the vtable (v for virtual), for which there is one per class (note: _not_ per object) that requires one. A class requires a vtable if it has at least one virtual member function. However each object of such classes do require access to the class's vtable and so a pointer to it is placed as a hidden data member to each object.
The compiler maintains the entries in this table. As virtual functions are overridden the function pointers to them are updated in the class's vtable. Setting these pointers occurs during construction. Base class parts of an object are initialised before derived class parts so the vtable first gets filled with pointers to base class virtual member function definitions. Later on if a derived class overrides a virtual function the constructor for the derived class part will replace the pointer to the base class function definition with a pointer to the derived class function definition. Note that this is why you cannot call virtual functions during construction and have them call the derived implementation - those parts have not been initialised yet so the vtable contains the base class virtual function definition pointers!
Now you may be able to guess why pure virtual functions are initialised using =0. Yep, the pointer to such functions is notionally a null pointer (or zero), and so a null pointer is placed into the vtable for pure virtual functions and trying to make a call to a function through a null pointer is not a good idea! In fact some compilers place a pointer to a piece of code that causes a pure virtual function call error to be raised instead of a real null pointer.
Here is an example:
First the C++ of a simple virtual function pair of classes:
struct ABC
{
virtual void vfunction() = 0;
virtual ~ABC() {}
};
struct Derived : ABC
{
virtual void vfunction();
};
void Derived::vfunction()
{
std::cout << "Derived::vfunction() called\n";
}
Next a function that calls vfunction dynamically on a reference to ABC:
void Call_VFunction( ABC & object_ref )
{
object.vfunction();
}
And finally some code that calls this function:
int main()
{
Derived d; // Must use a Derived as ABC is abstract
Call_VFunction(d);
}
Now let us look at the dynamic call to Derived::vfunction though the object_ref ABC refernce argument to Call_VFunction.
Here is the simpified assembler:
mov eax, _object_ref$[ebp]
mov edx, [eax]
mov esi, esp
mov ecx, _object_ref$[ebp]
mov eax, [edx]
call eax
Quite complex isn't it?
Some of the lines concern setting up the stack and this pointer for the call:
mov esi, esp
mov ecx, _object_ref$[ebp]
So we can remove them as they are not central to the discussion. This leaves:
mov eax, _object_ref$[ebp]
mov edx, [eax]
mov eax, [edx]
call eax
The sequence goes as follows:
mov eax, _object_ref$[ebp]
Move the value of the object_ref parameter into register eax. This is the address of the Derived object d passed from main. Effectively eax holds a pointer to d.
mov edx, [eax]
Move into register edx the contents at the addess in register eax, which is the first data item in d. This is the pointer to the vtable. Register edx now holds a pointer to the Derived class's vtable.
mov eax, [edx]
Move into eax (again!) the value at the address in edx. This is the address of the first entry in the Derived class's vtable. Register eax now holds a pointer to the Derived::vfunction function.
call eax
Finally! Call the function at the address in eax.
Now the same piece of code will work with another class derived from ABC, say Derived2:
struct Derived2 : ABC
{
virtual void vfunction();
};
void Derived2::vfunction()
{
std::cout << "Derived2::vfunction() called\n";
}
All that happens is that the following are done:
mov eax, _object_ref$[ebp]; load pointer to Derived2 object
mov edx, [eax] ; load pointer to Derived2 vtable
mov eax, [edx] ; load pointer to Derived2::vfunction
call eax ; Call Derived2::vfunction
The same code can call different functions depending on the exact type of the object it is passed. The code does not know at compile time which function it will call, that is only determined dynamically at run time.
It does of course rely on the vtables for all the related types being laid out in a compatible and consistent manner and, for that matter, that the position of the vtable pointer for objects is maintained consistently.
9. Does c++ support multilevel and multiple inheritance?
Yes,
In C++ we can derive a class C from B which is derived from A -- multilevel inheritance.
In C++ we can derive a class D from two base classes A and B -- multiple inheritance. This may cause a problem in case A and B are derived from a single base class say P. When a D's method refers to a public/protected data member of P (the uppermost parent) there are two paths available -- A::var or B::var -- here the compiler gives an error. To avoid this problem A and B need to be 'virtually' derived from P. If they are virtually derived then only one copy of P's data members exist for both A and B objects.
10. What are the advantages of inheritance?
Ans 1:
Inheritance offers the following advantages --
1. Developement model closer to real life object model with hierarchical relationships
2. Reusability -- facility to use public methods of base class without rewriting the same
3. Extensibility -- extending the base class logic as per business logic of the derived class
4. Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class
Ans 2:
In OOPs, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have combined features of both the
classes.
11. When is a memory allocated to a class?
Ans 1:
A class is a template.As Teginder said,it will get allocated memory when u create object of that class.
Ans 2:
When an object is instantiated.
12. What is the difference between declaration and definition?
Answer 1:
You have to declare functions, structures and variable because the compiler needs to know how much memory (or stack space) to reserve for these things.
Function prototype...
int myfunction(int x, char c);
You need a function prototype so the compiler knows how much memory this functions needs to reserve on the stack for the parameters passed to and from the function. (In this case 5 bytes)
A definition is used as a direct replacement...
1. DEFINE MYVALUE 0xef
Wherever the compiler encounters "MYVALUE" it replaces it with the defined value (0xef).
This is useful because if you have to change a value, you just change it in the definition (usually placed at the start of the C file).
Otherwise you have to find every place this value is used and change it manually.
For example: If your software displays it's version number on the screen and in any files it may create, you can use a defintion...
1. DEFINE VERSION V1.01
printf("My Program %s\n", VERSION);
fprintf( fp, "My Program %s\n", VERSION);
When the version number changes, you can just change the definition and the new version number is compiled for every placed it is used.
Answer 2:
The term declaration means (in C) that you are telling the compiler about type, size and in case of function declaration, type and size of its parameters of any variable, or user defined type or function in your program. _No_ space is reserved in memory for any variable in case of declaration. However compiler knows how much space to reserve in case a variable of this type is created.
for example, following are all declarations: extern int a; struct _tagExample { int a; int b; }; int myFunc (int a, int b);
Definition on the other hand means that in additions to all the things that declaration does, space is also reserved in memory. You can say "DEFINITION = DECLARATION + SPACE RESERVATION" following are examples of definition: int a; int b = 0; int myFunc (int a, int b) { return a + b; } struct _tagExample example;
13. What is virtual constructors/destructors?
Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.
There is a simple solution to this problem – declare a virtual base-class destructor. This makes all derived-class destructors virtual even hough they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying he delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.
irtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.
14. What is late bound function call and early bound function call? Differentiate.
Ans 1:
Functions are boud to there address so that they could be executed. if the address of the functions are known durning compile time the compiler binds it, this kind of binding is known as compile time binding or early binding. Where as when we dont know which function needs to be exucuted during compile time (as in case of dynamic polymorphism), compiler uses mechaninsm of virtual table and binds the function address during runtime. this is known as runtime binding or late binding.
Ans 2:
if function or any variable known during the compile time such Binding is known as Early Binding.
if during compile time does not specify which function is bind. such binding known as Late Binding.
Example
--------
Object is best Example of late binding
we are bind object variable at Dynamically when we use the object.
15. How is exception handling carried out in c++?
Exception handling is carried out using try, catch blocks and the throw statement.
Try block includes all code which can result into any exception.
It is followed by one or more catch blocks starting from most specific to least specific. A catch block handling exception of a class type can also handle exceptions of any class in its inheritance hierarchy.
A function can declare a throw (....) declaration saying that it is not going to handle exceptions of the specified types. These exceptions will be thrown to the calling function.
If an exception is unhandled the program will have abnormal termination.
try catch blocks can be nested to any level.
16. When will a constructor executed?
A constructor is executed when an object of a class is getting initialized (constructed)
17. What is Dynamic Polymorphism?
Ans 1:
Dynamic polymorphism is also known as runtime polymorphism.
It is achieved by means of virtual functions.
Depending on the type of object referred by a variable the decision about the method to be called (whether to call base class implementation or the derived class implementation) is taken at runtime. This is dynamic polymorphism.
Ans 2:
in hirarchie, when sub class overrides the super class method then we call that method using the super class reference then which version of method is called is resolved at run time based on the object that the reference refers to is called dynamic polymorphisum or dynamic binding.and also called run time polymorphisum
18. Write a macro for swapping integers.
Ans 1:
main(){ int a,b;scanf("%d,%d"a,b); a^=b;b^=a;a^=b;printf("The values after swap is %d %d",a,b);}
Ans 2:
#define SWAP(a,b) b=a+b-(a=b)
Ans 3:
# define swap(a,b) a = a + b; b = a - b; a = a - b;
APTITUDE SAMPLE PATTERNS
MATHEMATICS (25 QUESTIONS 30 MINUTES)
1). From 7:00 AM to 11:00 AM it rained 2.25 inches. At 11:00 AM the rain increased to fall at a rate of 1.25 in. every two hours. How many inches of rain landed on the ground by 5:00 PM?
a) 7
b) 9.75
c) 6
d) 3.25
e) 7.125
Solution:
7 am to 11 am - 2.25 in
11- am to 1 pm - 1.25 in (From 11 am, the fall rate is 1.25 in for every 2 hours)
1 pm to 3 pm - 1.25 in
3 pm to 5 pm - 1.25 in
---------
6.00 in
---------
2). The owner of a hobby store needed to calculate the percentage of customers who purchase wood glue. Upon completing his survey, he noticed that 60% of the people that entered his store purchased an item. Of those customers, 15 percent purchased wood glue. What percent of the people that entered the store purchased wood glue?
a) 8%
b) 7%
c) 9%
d) 12%
e) 15%
Solution:
Take the number of people as 100.
% of people purchased an item - 60%. (60)
15% out of this 60% people purchased wood glue. (15% in 60 = 9)
So, the % of people purchased wood glue is 9% (9)
3) If 1/x = 3.5. then 1/(x+2) =
a) 7/9
b) 16/7
c) 7/16
d) 9/7
e) 7/4
Solution:
1/x = 3.5
x = 1/3.5
x + 2 = 1/3.5 + 2
= 8/3.5 [How?: ((2*3.5) + 1)/3.5]
So, 1/(x+2) = 1/(8/3.5)
= 3.5/8
==> 7/16
4) A store owner is packing small radios into larger boxes that measure 25 in. by 42 in. by 60 in. If the measurement of each radio is 7 in. by 6 in. by 5 in., then how many radios can be placed in the box?
a) 300
b) 325
c) 400
d) 420
e) 480
Solution:
Volume of big box = 25 X 42 X 60 = 63000 cubic in.
Volume of radio= 7 X 6 X 5 = 210 cubic in.
so no. of radios which can be packed = 63000/210 = 300
5) Frank is 15 years younger then John. In 5 years John will be twice as old as Frank. How old will Frank be in four years?
a) 8
b) 10
c) 12
d) 14
e) 16
Solution:
Now:
Frank is 15 years younger than John.
John --> 25 yrs
Frank --> 10 yrs
In 5 Years:
John will be twice as old as Frank.
John --> 30 yrs
Frank --> 15 yrs
So, in 4 years:
How old will Frank be?
Frank --> 15 -1 ==> 14
6) A store owner decided to raise the price of a particular item by exactly 10%. Of the following which is NOT the new price?
a) $1.10
b) $8.80
c) $11.00
d) $57.30
e) $78.10
Solution:
We need to check which of the above option does not fit as exactly 10%.
Previous Price % Increase New Price
----------------- -------------- -------------
a --> $1 10% ($ 0.1) $ 1.10
b --> $8 10% ($ 0.8) $ 8.80
c --> $10 10% ($ 1.0) $11.00
e --> $71 10% ($ 7.1) $78.10
So, all the above options fit into 10%.
But for option d --> $52 10% ($5.20) %57.20
So, 57.30 is not exact 10%.
7) The price of a candy bar is $1.00. The price of a ten pack of the same candy bar is $7.40. The ten pack of candy bars is what percentage cheaper then purchasing ten candy bars individually?
a) 18%
b) 26%
c) 32%
d) 48%
e) The prices are same
Solution:
Price of 1 candy bar = 1.00 (A)
Price of ten pack = 7.40
So, Price of 1 candy bar in a pack = 7.40/10 ==>0.74 (B)
Difference between these two = A - B ==> 1.00 - 0.74 = 0.26.
So, ten pack candy bar is 26% cheaper than purchasing ten candy bars individually.
8) In a certain department store, which has four sizes of a specific shirt, there are 1/3 as many small shirts as medium shirts, and 1/2 as many large shirts as small shirts. If there are as many x-large shirts as large shirts, what percent of the shirts in the store are medium?
a) 10%
b) 25%
c) 33%
d) 50%
e) 60%
Solution:
no of small(S) shirts= D
no of med(M) shirts= C
no of lar(L) shirts= B
no of x-lar(XL) shirts= A;
1/3 C = D; ==> C = 3D;
1/2 D = B; ==> D = 2B;
B=A;
So,
A=B;
C=6B; (Because D=2B, C=3D ==> C=3*2B ==> C=6B)
D=2B;
% of med (C) shirts = C/(A+B+C+D) *100
= C/(B + B + 6B+ 2B) *100
= C/10B *100
= 6B/10B * 100
= 60%.
9) A new apartment complex purchased 60 toilets and 20 shower heads. If the price of a toilet is three times the price of a shower head, what percent of the total cost was the cost of all the shower heads?
a) 9%
b) 10%
c) 11%
d) 13%
e) 15%
Solution:
Price of the toilet = Three times the price of a shower head
For example,
Let is take the price of a shower head = Rs.20.
Then, the price of the toilet = Rs.60 (3 X 20).
Items purchased = 60 toilets and 20 shower heads
Total cost = (60 toilets * Rs.60) + (20 shower heads * Rs.20) = Rs.3600 + Rs.400 ==> Rs.4000
Question is: what percent of the total cost was the cost of all the shower heads?
Total Cost = Rs.4000
Cost of Shower heads = Rs. 400
% = 10%
10) A car averages 55 mph for the first 4 hours of a trip and averages 70 mph for each additional hour. The average speed for the entire trip was 60 mph. How many hours long is the trip?
a) 6
b) 8
c) 11
d) 12
e) 14
Solution:
Total speed = 60 mph * 60 mins = 360 mph
First 4 Hours = 4 hrs * 55 mph = 220 mph
Remaining = 140 mph
Fifth Hour = 70 mph
Sixth Hour = 70 mph
Then, Total in 2 Hours = 140 mph
So, the total hours travelled is 4 Hrs + 2 Hrs = 6 Hrs
11) In 1991, was the number of people in City A three times greater then the number of people in City B?
1) In 1991, there were approximately 1.1 million more people in City A than in City B.
2) In 1991, the 300,000 Catholics in City A made up 20% of its population, and the 141,000 Buddhists in City B made up 30% of its population.
a) if statement (1) ALONE is sufficient, but statement (2) alone is not sufficient to answer the question.
b) if statement (2) ALONE is sufficient, but statement (1) alone is not sufficient to answer the question.
c) if BOTH statements (1) and (2) TOGETHER are sufficient to answer the question asked, but NEITHER statement ALONE is sufficient.
d) if EACH statement ALONE is sufficient to answer the question asked.
e) if statements (1) and (2) TOGETHER are NOT sufficient to answer the question asked, and additional data specific to the problem are needed.
Solution:
e
12) (165)2 - (164)2 =
a) 1
b) 100
c) 229
d) 329
e) 349
Solution:
(165)2-(164)2
it is in the form a2-b2
(a+b)(a-b)
therefore (165+164)(165-164)
165+164=329;165-164=1
(165)2-(164)2=329
13) If the ticket sales s for a company increases 25% from standard sales to 60 tickets sold, then 60 - s =:
a) 7
b) 12
c) 18
d) 30
e) 48
Solution:
Increased Sales = 1.25 s = 60
s = 60/1.25 = 48
Therefore,
Then, the Standard Sales s would be 48. (Because 25% in 48 is 12 and so, 48 + 12 = 60)
So, 60 - s = 60 - 48 = 12.
14) All of the tickets for 2 music concerts, X and Y, were either purchased or given away, and the ratio of X tickets to Y was 2 to 1. Of the total number of X tickets and Y tickets, what percentage was purchased?
1) The total number of X tickets and Y tickets, is 240.
2) Of the X tickets, exactly 60% were purchased, and of the Y tickets, exactly 80% were purchased.
a) if statement (1) ALONE is sufficient, but statement (2) alone is not sufficient to answer the question.
b) if statement (2) ALONE is sufficient, but statement (1) alone is not sufficient to answer the question.
c) if BOTH statements (1) and (2) TOGETHER are sufficient to answer the question asked, but NEITHER statement ALONE is sufficient.
d) if EACH statement ALONE is sufficient to answer the question asked.
e) if statements (1) and (2) TOGETHER are NOT sufficient to answer the question asked, and additional data specific to the problem are needed.
Solution:
b
15) If a and b are positive integers, is a + 4b odd?
1) b is even.
2) a is odd.
a) if statement (1) ALONE is sufficient, but statement (2) alone is not sufficient to answer the question.
b) if statement (2) ALONE is sufficient, but statement (1) alone is not sufficient to answer the question.
c) if BOTH statements (1) and (2) TOGETHER are sufficient to answer the question asked, but NEITHER statement ALONE is sufficient.
d) if EACH statement ALONE is sufficient to answer the question asked.
e) if statements (1) and (2) TOGETHER are NOT sufficient to answer the question asked, and additional data specific to the problem are needed.
Solution:
(b) statement (2) is sufficient to answer it has nothing to do with 4b because ...product of even and odd is always even...and sum of even and odd is always odd.
16) If q is a multiple of prime numbers, is q a multiple of r?
1) r < 4.
2) q = 18.
a) if statement (1) ALONE is sufficient, but statement (2) alone is not sufficient to answer the question.
b) if statement (2) ALONE is sufficient, but statement (1) alone is not sufficient to answer the question.
c) if BOTH statements (1) and (2) TOGETHER are sufficient to answer the question asked, but NEITHER statement ALONE is sufficient.
d) if EACH statement ALONE is sufficient to answer the question asked.
e) if statements (1) and (2) TOGETHER are NOT sufficient to answer the question asked, and additional data specific to the problem are needed.
Solution:
e
From Statement (1) -- q can be positive and r can be negative.
r can also be a real number but not necessarily an integer.
Hence insufficient.
From Statement (2) -- q = 18.
But r can be negative or can be positive.
r can also be a real number not an integer
Hence insufficient
Taking both statements (1) and (2) together -- Again r can be positive or negative. And again r can also be a real number.
Hence insufficient
17) How many integers between 100 and 150, inclusive, cannot be evenly divided by 3 nor 5?
a) 35
b) 27
c) 25
d) 26
e) 28
Solution:
number of integers between then is =51
number of integers divided by 3 of the numbers =17
number of integers divided by 5 of there number =11
number of integers divided by both =4
Then, the answer is 51 - (17+11-4) =27
18) Susan wants to put up fencing around three sides of her rectangular yard and leave a side of 20 feet unfenced. If the yard has an area of 680 square feet, how many feet of fencing does she need?
a) 38
b) 44
c) 72
d) 88
e) 97
Solution:
answer is 88 ft bcoz she wants leave a side of 20 feet unfenced
19) Which of the following equations has a root in common with x2 - 6x + 5 = 0?
a) x2 + 1 = 0
b) x2 - x - 2 = 0
c) 2x2 - 2 = 0
d) x2 - 2x - 3 = 0
e) x2 - 10x - 5 = 0
Solution:
x2-6x+5=0
so,
x2-6x+5=(x-1)(x-5)=0
x-1=0;x-5=0
x=1, x=5
With this values for x and y, the equation c only is seems to be correct. ==> 2x2 - 2 = 0 ==> 2(1) - 2 = 0. So the anwer may be c.
20) A computer store regularly sells all stock at a discount of 20 percent to 40 percent. If an additional 25 percent were deducted from the discount price during a special sale, what would be the lowest possible price of a part costing $16 before any discount?
a) $6.80
b) $7.20
c) $9.60
d) $11.30
e) $14.80
Solution:
The regular discount is 20-40%.So the maximum regular discount is 40%.So the Price after 40% discount is $9.6.From this amount 25% is deducted.So the new price is now $7.2,which is the lowest price.
21) If "basis points" are defined so that 1 percent is equal to 100 basis points, then 75.5 percent is how many basis points greater than 65.5 percent?
a) .01
b) .10
c) 10
d) 100
e) 1000
Solution:
Given: 1%= 100 Basis Points
Therefore 75.5%= 7550 Basis Points
and also 65.5%= 6550 Basis Points
Therefore 75.5%>65.5%(7550-6550) by 1000 basis points
Answer is 1000 basis points..........
22) If x + 8y = 20 and x = -3y, then y =
a) 3
b) 4
c) 5
d) 6
e) 8
Solution:
x + 8y = 20 ==> 8y = 20 - x
-3y = x
5y = 20
y = 4
23) If 2x + y = 10 and x = 3, what is x – y
a) -3
b) -1
c) 0
d) 1
e) 3
Solution:
2x + y = 10
x = 3
Then, 2(3) + y = 10
6 +y = 10
y = 4
So, x - y = 3 - 4 = -1
24) If a triangle has a base B and the altitude of the triangle is twice the base, then the area of the triangle is
a) .5AB
b) AB
c) .5AB2
d) B2
e) 2B2
Solution:
Base = B
Altitude = A = 2B
Area = 1/2 * AB ==> 1/2 * 2B * B ==> B2
25) If y/x = 1/3 and x + 2y = 10, then x is
a) 2
b) 3
c) 4
d) 5
e) 6
Solution:
y/x = 1/3
x/y = 3
x = 3y
x + 2y = 10
3y + 2y = 10
5y = 10
y = 2
x = 3y
x = 3(2) = 6
SECTION B
VERBAL REASONING ( 20 QUESTIONS 30 MINUTES )
DIRECTIONS :- ENITRE SECTION B IS DIVIDED INTO THREE PASSAGES. READ EACH PASSAGE CAREFULLY AND ANSWER QUESTIONS MENTIONED BELOW.
PASSAGE – I
QUESTION NO 1-6
If one always ought to act so as to produce the best possible circumstances, then morality is extremely demanding. No one could plausibly claim to have met the requirements of this "simple principle." . . . It would seem strange to punish those intending to do good by sentencing them to an impossible task. Also, if the standards of right conduct are as extreme as they seem, then they will preclude the personal projects that humans find most fulfilling.
From an analytic perspective, the potential extreme demands of morality are not a "problem." A theory of morality is no less valid simply because it asks great sacrifices. In fact, it is difficult to imagine what kind of constraints could be put on our ethical projects. Shouldn't we reflect on our base prejudices, and not allow them to provide boundaries for our moral reasoning? Thus, it is tempting to simply dismiss the objections to the simple principle. However, in Demands of Morality, Liam Murphy takes these objections seriously for at least two distinct reasons.
First, discussion of the simple principle provides an excellent vehicle for a discussion of morality in general. Perhaps, in a way, this is Murphy's attempt at doing philosophy "from the inside out.". . . Second, Murphy's starting point tells us about the nature of his project. Murphy must take seriously the collisions between moral philosophy and our intuitive sense of right and wrong. He [must do so] because his work is best interpreted as intended to forge moral principles from our firm beliefs, and not to proscribe beliefs given a set of moral principles.
[Murphy] argues from our considered judgments rather than to them. . . For example, Murphy cites our "simple but firmly held" beliefs as supporting the potency of the over-demandingness objection, and nowhere in the work can one find a source of moral values divorced from human preferences.
Murphy does not tell us what set of "firm beliefs" we ought to have. Rather, he speaks to an audience of well-intentioned but unorganized moral realists, and tries to give them principles that represent their considered moral judgments. Murphy starts with this base sense of right and wrong, but recognizes that it needs to be supplemented by reason where our intuitions are confused or conflicting. Perhaps Murphy is looking for the best interpretation of our convictions, the same way certain legal scholars try to find the best interpretation of our Constitution.
This approach has disadvantages. Primarily, Murphy's arguments, even if successful, do not provide the kind of motivating force for which moral philosophy has traditionally searched. His work assumes and argues in terms of an inner sense of morality, and his project seeks to deepen that sense. Of course, it is quite possible that the moral viewpoints of humans will not converge, and some humans have no moral sense at all. Thus, it is very easy for the moral skeptic to point out a lack of justification and ignore the entire work.
On the other hand, Murphy's choice of a starting point avoids many of the problems of moral philosophy. Justifying the content of moral principles and granting a motivating force to those principles is an extraordinary task. It would be unrealistic to expect all discussions of moral philosophy to derive such justifications. Projects that attempt such a derivation have value, but they are hard pressed to produce logical consequences for everyday life. In the end, Murphy's strategy may have more practical effect than its first-principle counterparts, which do not seem any more likely to convince those that would reject Murphy's premises.
1) The author suggests that the application of Murphy's philosophy to the situations of two different groups:
a) would help to solve the problems of one group but not of the other.
b) could result in the derivation of two radically different moral principles.
c) would be contingent on the two groups sharing the same fundamental beliefs.
d) could reconcile any differences between the two groups.
2) Suppose an individual who firmly believes in keeping promises has promised to return a weapon to a person she knows to be extremely dangerous. According to Murphy, which of the following, if true, would WEAKEN the notion that she should return the weapon?
a) She also firmly believes that it is morally wrong to assist in any way in a potentially violent act.
b) She believes herself to be well-intentioned in matters of right and wrong.
c) The belief that one should keep promises is shared by most members of her community.
d) She derived her moral beliefs from first-principle ethical philosophy.
3) The passage implies that a moral principle derived from applying Murphy's philosophy to a particular group would be applicable to another group if:
a) the first group recommended the principle to the second group.
b) the moral viewpoints of the two groups do not converge.
c) the members of the second group have no firmly held beliefs.
d) the second group shares the same fundamental beliefs as the first group.
4) According to the passage, the existence of individuals who entirely lack a moral sense:
a) confirms the notion that moral principles should be derived from the considered judgments of individuals.
b) suggests a potential disadvantage of Murphy's philosophical approach.
c) supports Murphy's belief that reason is necessary in cases in which intuitions are conflicting or confused.
d) proves that first-principle strategies of ethical theorizing will have no more influence over the behavior of individuals than will Murphy's philosophical approach.
5) Which of the following can be inferred about "doing philosophy from the inside out?"
a) Murphy was the first philosopher to employ such an approach.
b) It allows no place for rational argument in the formation of ethical principles.
c) It is fundamentally different from the practice of first-principle philosophy.
d) It is designed to dismiss objections to the "simple principle."
6) A school board is debating whether or not to institute a dress code for the school's students. According to Murphy, the best way to come to an ethical decision would be to:
a) consult the fundamental beliefs of the board members.
b) analyze the results of dress codes instituted at other schools.
c) survey the students as to whether or not they would prefer a dress code.
d) determine whether or note a dress code has ever been instituted in the school's history.
PASSAGE – II
QUESTION NO 7-13
Agonistic behavior, or aggression, is exhibited by most of the more than three million species of animals on this planet. Animal behaviorists still disagree on a comprehensive definition of the term, hut aggressive behavior can be loosely described as any action that harms an adversary or compels it to retreat. Aggression may serve many purposes, such as Food gathering, establishing territory, and enforcing social hierarchy. In a general Darwinian sense, however, the purpose of aggressive behavior is to increase the individual animal’s—and thus, the species’—chance of survival.
Aggressive behavior may he directed at animals of other species, or it may be conspecific—that is, directed at members of an animal’s own species. One of the most common examples of conspecific aggression occurs in the establishment and maintenance of social hierarchies. In a hierarchy, social dominance is usually established according to physical superiority; the classic example is that of a pecking order among domestic fowl. The dominance hierarchy may be viewed as a means of social control that reduces the incidence of attack within a group. Once established, the hierarchy is rarely threatened by disputes because the inferior animal immediately submits when confronted by a superior.
Two basic types of aggressive behavior are common to most species: attack and defensive threat. Each type involves a particular pattern of physiological and behavioral responses, which tends not to vary regardless of the stimulus that provokes it. For example, the pattern of attack behavior in cats involves a series of movements, such as stalking, biting, seizing with the forepaws and scratching with tile hind legs, that changes very little regardless of the stimulus—that is, regardless of who or what the cat is attacking.
The cat’s defensive threat response offers another set of closely linked physiological and behavioral patterns. The cardiovascular system begins to pump blood at a faster rate, in preparation for sudden physical activity. The eves narrow and the ears flatten against the side of the cat’s head for protection, and other vulnerable areas of the body such as the stomach and throat are similarly contracted. Growling or hissing noises and erect fur also signal defensive threat. As with the attack response, this pattern of responses is generated with little variation regardless of the nature of the stimulus.
Are these aggressive patterns of attack and defensive threat innate, genetically programmed, or are they learned? The answer seems to be a combination of both. A mouse is helpless at birth, but by its l2th day of life can assume a defensive threat position by backing up on its hind legs. By the time it is one month old, the mouse begins to exhibit the attack response. Nonetheless, copious evidence suggests that animals learn and practice aggressive behavior; one need look no further than the sight of a kitten playing with a ball of string. All the elements of attack—stalking, pouncing, biting, and shaking—are part of the game that prepares the kitten for more serious situations later in life.
7) The passage asserts that animal social hierarchies are generally stable because:
a) the behavior responses of the group are known by all its members.
b) the defensive threat posture quickly stops most conflicts.
c) inferior animals usually defer to their physical superior.
d) the need for mutual protection from other species inhibits conspecific aggression.
Solution : c
8) According to the author, what is the most significant physiological change undergone by a cat assuming the defensive threat position?
a) An increase in cardiovascular activity
b) A sudden narrowing of the eyes
c) A contraction of the abdominal muscles
d) The author does not say which change is most significant
Solution : a
9) Based on the information in the passage about agonistic behavior, it is reasonable to conclude that:
I. the purpose of agonistic behavior is to help ensure the survival of the species.
II. agonistic behavior is both innate and learned.
III. conspecific aggression is more frequent than i aggression.
a) I only
b) II only
c) I and II only
d) I,II and III only
Solution : c
10) Which of the following would be most in accord with the information presented in the passage?
a) The aggressive behavior of sharks is closely inked to their need to remain in constant motion.
b) fine inability of newborn mice to exhibit the attack response proves that aggressive behavior must be learned.
c) Most animal species that do riot exhibit aggressive behavior are prevented from doing so by environmental factors.
d) Members of a certain species of hawk use the same method to prey on both squirrels and gophers.
Solution : b
11) The author suggests that the question of whether agonistic behavior is genetically programmed or learned:
a) still generates considerable controversy among animal behaviorists.
b) was first investigated through experiments on mice.
c) is outdated since most scientists now believe the genetic element to be most important.
d) has been the subject of extensive clinical study.
Solution : b
12) Which of the following topics related to agonistic behavior is NOT explicitly addressed in the passage?
a) The physiological changes that accompany attack behavior in cats
b) The evolutionary purpose of aggression
c) Conspecific aggression that occurs in dominance hierarchies
d) The relationship between play and aggression
Solution : d
13) The author of this passage is primarily concerned with:
a) analyzing the differences between attack behavior and defensive threat behavior.
b) introducing a subject currently debated among animal behaviorists.
c) providing a general overview of aggressive behavior in animals.
d) illustrating various manifestations of agonistic behavior among mammals.
Solution : a
PASSAGE – III
QUESTION NO 14 - 20
The rich analysts of Fernand Braudel arid his fellow Annales historians have made significant contributions to historical theory and research. In a departure from traditional historical approaches, the Annales historians assume (as do Marxists) that history cannot be limited to a simple recounting of conscious human actions, but must be understood in the context of forces and material conditions that underlie human behavior. Braudel was the first Annales historian to gain widespread support for the idea that history should synthesize data from various social sciences, especially economics, in order to provide a broader view of human societies over time (although Febvre and Bloch, founders of the Annales school, had originated this approach).
Braudel conceived of history as the dynamic interaction of three temporalities. The first of these, the evenmentielle, involved short-lived dramatic events such as battles, revolutions, and the actions of great men, which had preoccupied traditional historians like Carlyle. Conjonctures was Braudel’s term for larger cyclical processes that might last up to half a century. The longue duree, a historical wave of great length, was for Braudel the most fascinating of the three temporalities. Here he focused on those aspects of everyday life that might remain relatively unchanged for centuries. What people ate, what they wore, their means and routes of travel—for Braudel these things create “structures’ that define the limits of potential social change for hundreds of years at a time.
Braudel’s concept of the longue duree extended the perspective of historical space as well as time. Until the Annales school, historians had taken the juridical political unit—the nation-state, duchy, or whatever—as their starting point. Yet, when such enormous timespans are considered, geographical features may well have more significance for human populations than national borders, In his doctoral thesis, a seminal work on the Mediterranean during the reign of Philip II, Braudel treated the geohistory of the entire region as a “structure” that had exerted myriad influences on human lifeways since the first settlements on the shores of the Mediterranean Sea. And so the reader is given such arcane information as the list of products that came to Spanish shores from North Africa, the seasonal routes followed by Mediterranean sheep and their shepherds, and the cities where the best ship timber could be bought.
Braudel has been faulted for the imprecision of his approach. With his Rabelaisian delight in concrete detail, Braudel vastly extended the realm of relevant phenomena but this very achievement made it difficult to delimit the boundaries of observation, a task necessary to beginning any social investigation. Further, Braudel and other Annales historians minimize the differences among the social sciences. Nevertheless, the many similarly designed studies aimed at both professional and popular audiences indicate that Braudel asked significant questions that traditional historians had overlooked.
14) The primary purpose of the passage is to:
a) show how Braudel’s work changed the conception of Mediterranean life held by previous historians.
b) evaluate Braudel’s criticisms of traditional and Marxist historiography.
c) contrast the perspective of the longue duree with the actions of major historical figures
d) outline some of Braudel’s influential conceptions and distinguish them from conventional approaches.
Solution : d
15) The author refers to the work of Febvre and Bloch in order to:
a) illustrate the limitations of the Annale tradition of historical interpretation.
b) suggest the relevance of economics to historical investigation.
c) debate the need for combining various sociological approaches.
d) show that previous Annales historians anticipated Braudel’s focus on economics.
Solution : b or d
16) According to the passage, all of the following are aspects of Braudel’s approach to history EXCEPT that he:
a) attempted to draw on various social sciences.
b) studied social and economic activities that occurred across national boundaries.
c) pointed out the link between increased economic activity and the rise of nationalism.
d) examined seemingly unexciting aspects of everyday life.
Solution : c
17) In the third paragraph, the author is primarily concerned with discussing:
a) Braudel’s fascination with obscure facts.
b) Braudel’s depiction of the role of geography in human history.
c) the geography of the Mediterranean region.
d) the irrelevance of national borders.
Solution : d (doubt)
18) The passage suggests that, compared with traditional historians, Annales/i> historians are:
a) more interested in other social sciences than in history.
b) critical of the achievements of famous historical figures.
c) skeptical of the validity of most economic research.
d) more interested in the underlying context of human behavior.
Solution : b or d
19) Which of the Following statements would be most likely to follow the last sentence of the passage?
a) Few such studies however, have been written by trained economists.
b) It is time, perhaps, for a revival of the Carlylean emphasis on personalities.
c) Many historians believe that Braudel’s conception of three distinct “temporalities” is an oversimplification.
d) Such diverse works as Gascon’s study of Lyon and Barbara Tuchman’s A Distant Mirror testify to his relevance.
Solution : b (doubt)
20) The author is critical of Braudel’s perspective for which of the Following reasons
a) It seeks structures that underlie all forms of social activity.
b) It assumes a greater similarity among the social sciences than actually exists.
c) It fails to consider the relationship between short-term events and long-term social activity.
d) It rigidly defines boundaries for social analysis.
Solution : b or c
SECTION C
ANALYTICAL REASONING ( 20 QUESTIONS 30 MINUTES )
1) Five racing drivers, Alan, Bob, Chris, Don, and Eugene, enter into a contest that consists of 6 races. The results of all six races are listed below:
Bob always finishes ahead of Chris.
Alan finishes either first or last.
Eugene finishes either first or last.
There are no ties in any race.
Every driver finishes each race.
In each race, two points are awarded for a fifth place finish, four points for fourth, six points for third, eight points for second, and ten points for first.
If Eugene finishes two places ahead of Chris in the first race, all of the following will be true EXCEPT:
a) Bob finishes ahead of Don.
b) Chris finishes two places ahead of Alan.
c) Don finishes fourth.
d) Bob finishes immediately behind Eugene.
e) Chris finishes ahead of Bob.
Solution : e
2) Five racing drivers, Alan, Bob, Chris, Don, and Eugene, enter into a contest that consists of 6 races. The results of all six races are listed below:
Bob always finishes ahead of Chris.
Alan finishes either first or last.
Eugene finishes either first or last.
There are no ties in any race.
Every driver finishes each race.
In each race, two points are awarded for a fifth place finish, four points for fourth, six points for third, eight points for second, and ten points for first.
If Don finishes third in the third race, which of the following must be true of that race?
a) Alan finishes first.
b) Eugene finishes first.
c) Bob finishes second.
d) Chris finishes second.
e) Alan finishes fifth.
Solution : c
3) Five racing drivers, Alan, Bob, Chris, Don, and Eugene, enter into a contest that consists of 6 races. The results of all six races are listed below:
Bob always finishes ahead of Chris.
Alan finishes either first or last.
Eugene finishes either first or last.
There are no ties in any race.
Every driver finishes each race.
In each race, two points are awarded for a fifth place finish, four points for fourth, six points for third, eight points for second, and ten points for first.
If Eugene's total for the six races is 36 points, which of the following must be true?
a) Bob's total is more than 36 points.
b) Chris's total is more than 36 points.
c) Alan's total is 36 points.
d) Don's total is less than 36 points.
e) Don's total is 36 points.
Solution : c
4) Five racing drivers, Alan, Bob, Chris, Don, and Eugene, enter into a contest that consists of 6 races. The results of all six races are listed below:
Bob always finishes ahead of Chris.
Alan finishes either first or last.
Eugene finishes either first or last.
There are no ties in any race.
Every driver finishes each race.
In each race, two points are awarded for a fifth place finish, four points for fourth, six points for third, eight points for second, and ten points for first.
If Alan finishes first only once, and Don finishes second exactly twice, the lowest total number of points that Bob can earn in the race is:
a) 32 points.
b) 38 points.
c) 40 points.
d) 44 points.
e) 48 points.
Solution : c
5) Five racing drivers, Alan, Bob, Chris, Don, and Eugene, enter into a contest that consists of 6 races. The results of all six races are listed below:
Bob always finishes ahead of Chris.
Alan finishes either first or last.
Eugene finishes either first or last.
There are no ties in any race.
Every driver finishes each race.
In each race, two points are awarded for a fifth place finish, four points for fourth, six points for third, eight points for second, and ten points for first.
If Alan finishes first in four races, which of the following could earn a total of fewer than 26 points in the six races?
a) Bob only.
b) Chris only.
c) Don only.
d) Eugene of Chris.
e) Don or Chris.
Solution : e
6) Five racing drivers, Alan, Bob, Chris, Don, and Eugene, enter into a contest that consists of 6 races. The results of all six races are listed below:
Bob always finishes ahead of Chris.
Alan finishes either first or last.
Eugene finishes either first or last.
There are no ties in any race.
Every driver finishes each race.
In each race, two points are awarded for a fifth place finish, four points for fourth, six points for third, eight points for second, and ten points for first.
If Frank enters the third race and finishes behind Chris and Don, which of the following must be true of that race?
a) Eugene finishes first.
b) Alan finishes sixth.
c) Don finishes second.
d) Frank finishes fifth.
e) Chris finishes third.
Solution : d
7) Jane works at a fashion design company, and is having problems getting dressed for work. She refuses to wear any color combination that does not go well together as many of her clients may look down upon this.
She has two pairs of skirts, brown and blue; three blouses, white, sky blue, and gray; four pairs of stockings, red, black, brown, and blue; and two pairs of shoes, black and brown.
The blue skirt cannot be worn with red or brown stockings.
Gray does not go well with brown.
Black does not go well with brown.
If Jane wears black shoes she will not wear:
a) red stockings.
b) a blue skirt.
c) a white blouse.
d) blue stockings.
e) a sky blue blouse.
Solution : a
8) Jane works at a fashion design company, and is having problems getting dressed for work. She refuses to wear any color combination that does not go well together as many of her clients may look down upon this.
She has two pairs of skirts, brown and blue; three blouses, white, sky blue, and gray; four pairs of stockings, red, black, brown, and blue; and two pairs of shoes, black and brown.
The blue skirt cannot be worn with red or brown stockings.
Gray does not go well with brown.
Black does not go well with brown.
If Jane is color blind and is unable to determine what outfits went well together, how many possible clothing combinations could she have?
a) 24
b) 32
c) 36
d) 44
e) 48
Solution :
9) Jane works at a fashion design company, and is having problems getting dressed for work. She refuses to wear any color combination that does not go well together as many of her clients may look down upon this.
She has two pairs of skirts, brown and blue; three blouses, white, sky blue, and gray; four pairs of stockings, red, black, brown, and blue; and two pairs of shoes, black and brown.
The blue skirt cannot be worn with red or brown stockings.
Gray does not go well with brown.
Black does not go well with brown.
If Jane wears a brown skirt and a white blouse, she could:
a) not wear blue stockings.
b) not wear brown shoes.
c) not wear black shoes.
d) wear blue stockings.
e) wear red stockings.
Solution : c
10) Jane works at a fashion design company, and is having problems getting dressed for work. She refuses to wear any color combination that does not go well together as many of her clients may look down upon this.
She has two pairs of skirts, brown and blue; three blouses, white, sky blue, and gray; four pairs of stockings, red, black, brown, and blue; and two pairs of shoes, black and brown.
The blue skirt cannot be worn with red or brown stockings.
Gray does not go well with brown.
Black does not go well with brown.
Jane buys a gray scarf. If she wears the new scarf, then she could:
a) not wear blue stockings.
b) not wear brown stockings.
c) not wear black shoes.
d) wear a white blouse.
e) wear black stockings.
Solution : b
11) Jane works at a fashion design company, and is having problems getting dressed for work. She refuses to wear any color combination that does not go well together as many of her clients may look down upon this.
She has two pairs of skirts, brown and blue; three blouses, white, sky blue, and gray; four pairs of stockings, red, black, brown, and blue; and two pairs of shoes, black and brown.
The blue skirt cannot be worn with red or brown stockings.
Gray does not go well with brown.
Black does not go well with brown.
Jane will never wear:
a) blue and red together.
b) white and red together.
c) gray and blue together.
d) white and black together.
e) white and red together.
Solution : a
12) Two men, Barry and David, and two women Ann and Cathy are doctors. One is a surgeon, one a dentist, one an optometrist, and one is a general practitioner. They are seated around a square table, with one person on each side.
1) Barry is across from the dentist.
2) David is not across from the surgeon.
3) The optometrist is on Ann's immediate left.
4) Cathy is the general practitioner.
5) The surgeon and general practitioner are married to each other.
6) The general practitioner is not on Cathy's immediate left.
7) The general practitioner is across from the optometrist.
Which of the following must be true?
a) Barry is the dentist.
b) The surgeon and general practitioner are women.
c) The dentist is across from the surgeon.
d) David is the surgeon.
e) Cathy is across from Ann.
Solution : c
13) Two men, Barry and David, and two women Ann and Cathy are doctors. One is a surgeon, one a dentist, one an optometrist, and one is a general practitioner. They are seated around a square table, with one person on each side.
1) Barry is across from the dentist.
2) David is not across from the surgeon.
3) The optometrist is on Ann's immediate left.
4) Cathy is the general practitioner.
5) The surgeon and general practitioner are married to each other.
6) The general practitioner is not on Cathy's immediate left.
7) The general practitioner is across from the optometrist.
If both women leave the table, the
a) optometrist and dentist remain.
b) surgeon and optometrist remain.
c) surgeon and general practitioner remain.
d) general practitioner and dentist remain.
e) general practitioner and optometrist remain.
Solution : b
14) A new bank has decided to stay open only on weekends - all day Saturday and Sunday - and no other days. The bank has hired two managers (U and V), Four tellers (W,X,Y, and Z), and two operation officers (S and T), for a total of exactly eight full-time employees. No part-time employees are hired. Each employee works a complete day when working.
A manager must be on duty each day.
The managers cannot work on the same day.
At least two tellers must be working on the same day.
W and X will not work on the same day.
S and Z will only work on Saturday.
No employee can work on consecutive days, but each employee must work on Saturday or Sunday.
Which of the following could be false?
a) If U works on Saturday, then V works on Sunday.
b) If X works on Saturday, then W works on Sunday.
c) T can work either day.
d) If W works on Saturday and Y works on Sunday, then X works on Sunday.
e) If U works on Sunday, then X works on Saturday.
Solution : c
15) A new bank has decided to stay open only on weekends - all day Saturday and Sunday - and no other days. The bank has hired two managers (U and V), Four tellers (W,X,Y, and Z), and two operation officers (S and T), for a total of exactly eight full-time employees. No part-time employees are hired. Each employee works a complete day when working.
A manager must be on duty each day.
The managers cannot work on the same day.
At least two tellers must be working on the same day.
W and X will not work on the same day.
S and Z will only work on Saturday.
No employee can work on consecutive days, but each employee must work on Saturday or Sunday.
Which one of the following is an acceptable group of employees that could work on Saturday?
a) ZWYST
b) UVWYZS
c) VWXST
d) UZST
e) VWZS
Solution : e
16) A new bank has decided to stay open only on weekends - all day Saturday and Sunday - and no other days. The bank has hired two managers (U and V), Four tellers (W,X,Y, and Z), and two operation officers (S and T), for a total of exactly eight full-time employees. No part-time employees are hired. Each employee works a complete day when working.
A manager must be on duty each day.
The managers cannot work on the same day.
At least two tellers must be working on the same day.
W and X will not work on the same day.
S and Z will only work on Saturday.
No employee can work on consecutive days, but each employee must work on Saturday or Sunday.
What is the greatest number of employees that can work on Saturday?
a) 2
b) 3
c) 4
d) 5
e) 6
Solution : d
17) A new bank has decided to stay open only on weekends - all day Saturday and Sunday - and no other days. The bank has hired two managers (U and V), Four tellers (W,X,Y, and Z), and two operation officers (S and T), for a total of exactly eight full-time employees. No part-time employees are hired. Each employee works a complete day when working.
A manager must be on duty each day.
The managers cannot work on the same day.
At least two tellers must be working on the same day.
W and X will not work on the same day.
S and Z will only work on Saturday.
No employee can work on consecutive days, but each employee must work on Saturday or Sunday.
If W works on Sunday, then which one of the following must be true?
a) X works on Saturday
b) Y works on Saturday
c) T works on Saturday
d) Z works on Saturday
e) U works on Saturday
Solution : a
18) A new bank has decided to stay open only on weekends - all day Saturday and Sunday - and no other days. The bank has hired two managers (U and V), Four tellers (W,X,Y, and Z), and two operation officers (S and T), for a total of exactly eight full-time employees. No part-time employees are hired. Each employee works a complete day when working.
A manager must be on duty each day.
The managers cannot work on the same day.
At least two tellers must be working on the same day.
W and X will not work on the same day.
S and Z will only work on Saturday.
No employee can work on consecutive days, but each employee must work on Saturday or Sunday.
Which one of the following must be true?
a) T always works on the same day as Y.
b) S never works on the same day as U.
c) Z never works on the same day as X.
d) If W works on Sunday, then Y always works on Saturday.
e) Only two tellers work on Saturday.
Solution : e
19) A new bank has decided to stay open only on weekends - all day Saturday and Sunday - and no other days. The bank has hired two managers (U and V), Four tellers (W,X,Y, and Z), and two operation officers (S and T), for a total of exactly eight full-time employees. No part-time employees are hired. Each employee works a complete day when working.
A manager must be on duty each day.
The managers cannot work on the same day.
At least two tellers must be working on the same day.
W and X will not work on the same day.
S and Z will only work on Saturday.
No employee can work on consecutive days, but each employee must work on Saturday or Sunday.
Which one of the following is a complete and accurate list of the employees who have the possibility of working on Sunday?
a) UWYZ
b) UWYS
c) UVWXT
d) UVWXYT
e) UVWXYTS
Solution : Wrong Answers
20) In the earliest stages of common law, a party could have their case heard by a judge only upon the payment of a fee to the court, and then only if the case fit into one of the forms for which there existed a writ. At first the number of such formalized cases of action was very small, but judges invented new forms which brought more cases and greater revenues.
Which of the following conclusions is most strongly suggested by the paragraph above?
a) In most early cases, the plaintiff rather than the defendant prevailed.
b) One of the motivating forces for the early expansion in judicial power was economic considerations.
c) The first common law decisions were inconsistent with one another and did not form a coherent body of law.
d) Early judges often decided cases in an arbitrary and haphazard manner.
e) The judiciary at first had greater power than either the legislature or the executive.
Solution :
C++ INTERVIEW QUESTIONS PART1
Question: What is a memory leak? How can we avoid it?
Answer :A memory leak can be avoided by making sure that whatever memory has been dynamically allocated will be cleared after the use of the same. for example
int main()
{ char *myCharData[20];
for (int nLoop =0;nLoop < 20; ++nLoop) { myCharData[nLoop ] = new char[256];
strcpy(myCharData[nLoop],"SABITH");
......
}
........................
/*Some manipulations here using myCharData*/
/*Now here we have to clear the data. The place can vary according to ur program. This being a simple program,u can clear at the end*/
for(int nLoop =0;nLoop < 20; ++nLoop)
{
delete[] myCharData[nLoop ];
}
return 0;
Question: How do you write a program which produces its own source code as its output?
Answer :write this program and save it as pro.c....run....it will show the program to the consol and write the source code into data.txt file...................
#include
void main()
{
FILE *fp,*ft;
char buff[100];
fp=fopen("pro.c","r");
if(fp==NULL)
{
printf("ERROR");
}
ft=fopen("data.txt","w+");
if(ft==NULL)
{
printf("ERROR");
}
while(getc(fp)!=EOF)
{
fscanf(fp,"%s",buff);
printf("%s\n",buff);
fprintf(ft,"%s\n",buff);
}
}
Question: What are the things contains in .obj file ? ( compiled result of .cpp file ) Answer :C++ .obj file holds code and data suitable for linking with other object files to create an executable or a shared object file.
Question :What is difference between followin intialization.
int iVar1;
int iVar2 = int();
and which one of two should we prefer always and why?
Answer :In first case a variable will be create in memeory with the default base type value (depending upon compiler 2 compiler) bcoz it is not initialized. in second case the variable will be created in the memory with the value retuned by the function int() (if int is a user define function) the second statement should have been int *i = new int();
Question :What is the difference between Object and Instance?
Answer :An instance of a user-defined type (i.e., a class) is called an object. We can instantiate many objects from one class.
An object is an instance or occurrence of a class.
Question: How is static variable stored in the memory?
(if there are 2 functions in a file, and the static variable name is same (ex var) in both the function. how is it keep separately in the memory).
Answer: C++ uses name mangling when storing both local and global static varibales at the same place. The local static variables have function name and the global variables will have file name. Essentially the compiler uses namespace to distinguish between local and global static variables.
Question :what is the difference betwen wait() and delay()?
Answer :Wait() and delay() works same but works on different platforms. Wait(2) will wait processing fro 2 second on Linux/Unix while delay(2000) with wait for 2 second but on DOS or Windows.
so wait(2) on linux == delay(2000) on DOS
Delay() is under
Question :Why always array starts with index 0
Answer :Array name is a constant pointer pointing to the base address(address of the first byte where the array begin) of the memory allocated. When you use arr[i], the compiler manipulates it as *(arr + i). Since arr is the address of the first element, the value of i must be 0 for accessing it. Hence all arrays begin with an index of 0.
Question: Can main() be overridden
Answer : In any application, there can be only one main function. In c++, main is not a member of any class. There is no chance of overriding
Question :What is the difference between macro and inline()?
Answer :1. Inline follows strict parameter type checking, macros do not.
2. Macros are always expanded by preprocessor, whereas compiler may or may not replace the inline definitions.
Question: How can double dimensional arrays be dynamically initialized in C++?
Answer :example of how to dynamically initialize double dimensional arrays:
int num[2][3] = {34,32,30,24,22,20};
num[1][1] = 34
num[1][2] = 32
num[1][3] = 30
num[2][1] = 24
num[2][2] = 22
num[2][3] = 20
Question: Can destructor be private?
Answer: Yes destructors can be private. But according to Standard Programming practice it is not advisable to have destructors to be private.
Question: what is memory leaking in c++ ?
Answer: When a class uses dynamically allocated memory internally, all sorts of problems arise. If not properly used or handled, they can lead to memory leaks & corrupts Data Structures.
A memory leak is the situation that occurs when dynamically allocated memory is lost to the program.
Char * p;
p= new char[10000];
.....
p= new char[5000];
Initially, 10000 bytes are dynamically allocated & the the address of those bytes is stored in p. later 5000 bytes are dynamically allocated & the address is stored in p. However, the original 10000 bytes’ve not been returned to the system using delete [] operator.
Memory leak actually depends on the nature of the program.
Question:
class A()
{
};
int main()
{
A a;
}
Whether there will be a default contructor provided by the compiler in above case ?
Answer :yes, if the designer of the class donot define any constructor in the class. then the compiler provides the default constructor in the class.
Question: what is the use of virtual destructor?
Answer :virtual destructor is very useful....everyone should use that......if there is no any strong reason for not using virtual destructor....like...One class having two char variable...........so it's size is two byte........if u use virtual destructor it's size will be 6 bytes....4 byte for virtual ptr....Now if this class have 1 millions objects...so 4 magabyte memory will be lost...where all ptr do the same thing.....
Question: Why cant one make an object of abstract class?Give compiler view of statement
Answer :we cant make object of abstract class becoz, in the vtable the vtable entry for the abstract class functions will be NULL, which ever are defined as pure virtual functions...
even if there is a single pure virtual function in the class the class becomes as abstract class..
if there is a virtual function in your class the compiler automatically creates a table called virtual function table .. to store the virtual function addresses.... if the function is a pure virtual function the vtable entry for that function will be NULL.
even if there is a single NULL entry in the function table the compiler does not allow to create the object.
Question: In c++ have a default constructor?
Answer: Yes C++ does have a default constructor provided by the compiler. In this case all the members of the class are initialized to null values. These values act as the default values. For eg: My Class me; In the above case since the object is not initialized to any value so the default constructor will be called which will initialize the class with the default values.
Question: Have you heard of "mutable" keyword?
Answer :The mutable keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.
SEE FOLLOWING CODE :-
********************************************
class Mutable
{
private :
int m_iNonMutVar;
mutable int m_iMutVar;
public:
Mutable();
void TryChange() const;
};
Mutable::Mutable():m_iNonMutVar(10),m_iMutVar(20) {};
void Mutable::TryChange() const
{
m_iNonMutVar = 100; // THis will give ERROR
m_iMutVar = 200; // This will WORK coz it is mutable
}
Question: What is "strstream”?
Answer: Class that reads and writes to an array in memory
Question: Can we generate a C++ source code from the binary file?
Answer: Technically this is possible, but in my knowledge their no such software available yet. Why this is possible? In program flow we do like this to generate binary file. High level language programming code -low level programming code- hex code- binary code. How we can do reverse can be illustrated with this example. When I type 0 on screen the ASCII equivalent is 65 and so the binary code will be by converting 65 (01010 0101) so I can recognize this and decode this. Same technique can be used. Some secret mission defense org. I heard have this code splitter from binary to assembly language (low level language)/ Converter type devices available, they use them for secret national purpose.
Question: Explain "passing by value", "passing by pointer" and "passing by reference"
Answer: There is major difference between these three are when we want to avoid making the copy of variable and we want to change value of actual argument on calling function. There are we use passing by pointer, passing the reference. We can not perform arithmetic operation on reference.
Question: Difference between "vector" and "array"?
Answer: Vector and Array List are very similar. Both of them represent a 'grow able array', where you access to the elements in it through an index.
Array List it's part of the Java Collection Framework, and has been added with version 1.2, while Vector it's an object that is present since the first version of the JDK. Vector, anyway, has been retrofitted to implement the List interface.
The main difference is that Vector it's a synchronized object, while Array List it's not.
While the iterator that are returned by both classes are fail-fast (they cleanly thrown a ConcurrentModificationException when the original object has been modified), the Enumeration returned by Vector are not.
Unless you have strong reason to use a Vector, the suggestion is to use the Array List
Question: What are the types of STL containers?
Answer: deque
hash_map
hash_multimap
hash_multiset
hash_set
list
map
multimap
multiset
set
vector
Question:Difference between a "assignment operator" and a "copy constructor"
Answer :Copy constructor is called every time a copy of an object is made. When you pass an object by value, either into a function or as a function's return value, a temporary copy of that object is made.
Assignment operator is called whenever you assign to an object. Assignment operator must check to see if the right-hand side of the assignment operator is the object itself. It executes only the two sides are not equal
Question: Can we have "Virtual Constructors"?
Answer: No, we cannot have virtual constructors. But if the need arises, we can simulate the implementation of virtual constructor by calling a Init method from the constructor which, should be a virtual function.
Question: Explain the need for "Virtual Destructor".
Answer: In case of inheritance, objects should be destructed exactly the opposite way of their construction. If virtual keyword is not added before base class destructor declaration, then derived class destructor will not at all be called. Hence there will be memory leakage if allocated for derived class members while constructing the object.
Question: What will happen if I say delete this
Answer: if you say "delete this", you are effectively calling the destructor twice, which could well be a disaster if your class uses heap. The destructor will be called when you say “delete this” and again when that object goes out of scope. Since this is the language behavior, there is no way to prevent the destructor from being called twice. Please refrain from forcibly calling a destructor or using clause like this.
Question: What is the output of printf ("%d")
Answer :Usually the output value cannot be predicted. It will not give any error. It will print a garbage value. But if the situation is
main()
{
int a=1,b=2,c=3;
printf("%d");
}
The output will be the value of the last variable, ie. 3
Question: # what is an algorithm (in terms of the STL/C++ standard library)?
Answer: Algorithm in STL consist different searching and sorting algos implementation, which takes start and end iterators of STL container
on which algo is going to work.
Question: How can you force instantiation of a template?
Answer: you can instantiate a template in two ways. 1. Implicit instantiation and 2. Explicit Instantion. implicit instatanitioan can be done by the following ways:
template
class A
{
public:
A(){}
~A(){}
void x();
void z();
};
void main()
{
A
A
}
External Instantion can be done the following way:
int main()
{
template class A
template class A
}
Question: What is the difference between operator new and the new operator?
Answer: This is what happens when you create a new object: 1. the memory for the object is allocated using "operator new". 2. the constructor of the class is invoked to properly initialize this memory. As you can see, the new operator does both 1 and 2. The operator new merely allocates memory, it does not initialize it. Where as the new operator also initializes it properly by calling the constructor.
Question: What is the Basic nature of "cin" and "cout" and what concept or principle we are using on those two?
Answer: Basically "cin and cout" are INSTANCES of istream and ostream classes respectively. And the concept which is used on cin and cout is operator overloading. Extraction and Insertion operators are overloaded for input and ouput operations.
Question: What are virtual functions?
Answer: C++ virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes.
C++ virtual function is,
* A member function of a class
* Declared with virtual keyword
* usually has a different functionality in the derived class
* A function call is resolved at run-time
Question: We can overload assignment operator as a normal function.But we can not overload assignment operator as friend function why?
Answer :If the operation modifies the state of the class object, it operates on, it must be a member function, not a friend fucntionThus all operator such as =, *=, +=, etc are naturally defined as member functions not friend functions Conversely, if the operator does not modify any of its operands, but needs only a representation of the object, it does not have to be a member function and often less confusing. This is the reason why binary operators are often implemented as friend functions such as + , *, -, etc..
Question: What is the difference between class and structure?
Answer: 1:By default, the members of structures are public while that for class is private
2: structures doesn't provide something like data hiding which is provided by the classes
3: structures contains only data while class bind both data and member functions
Question: What is virtual class and friend class?
Answer: Friend classes are used when two or more classes are designed to work together and virtual base class aids in multiple inheritance.
Question: Is there any way to write a class such that no class can be inherited from it. Please include code
Answer: Simple, make all constructors of the class private.
Question: Why can’t we overload the sizeof, :?, :: ., .* operators in c++
Answer: The restriction is for safety. For example if we overload. Operator then we can’t access member in normal way for that we have to use ->.
Question :What is importance of const. pointer in copy constructor?
Answer :Because otherwise you will pass the object to copy as an argument of copy constructor as pass by value which by definition creates a copy and so on... an infinite call chain
C INTERVIEW QUESTIONS - PART1
Question: Difference between arrays and pointers?
Answer: Pointers are used to manipulate data using the address. Pointers use * operator to access the data pointed to by them
Arrays use subscripted variables to access and manipulate data. Array variables can be equivalently written using pointer expression.
Question: What is the purpose of realloc ( )?
Answer: The function realloc (ptr,n) uses two arguments. The first argument ptr is a pointer to a block of memory for which the size is to be altered. The second argument n specifies the
new size. The size may be increased or decreased. If n is greater than the old size and if sufficient space is not available subsequent to the old region, the function realloc ( )
may create a new region and all the old data are moved to the new region.
Question: What is static memory allocation and dynamic memory allocation?
Answer: Static memory allocation: The compiler allocates the required memory space for a declared variable. By using the address of operator, the reserved address is obtained and this address may be assigned to a pointer variable. Since most of the declared variable has static memory, this way of assigning pointer value to a pointer variable is known as static memory allocation. Memory is assigned during compilation time.
Dynamic memory allocation: It uses functions such as malloc ( ) or calloc ( ) to get memory dynamically. If these functions are used to get memory dynamically and the values returned by these functions are assigned to pointer variables, such assignments are known as dynamic memory allocation. Memory is assigned during run time.
Question: How are pointer variables initialized?
Answer: Pointer variable are initialized by one of the following two ways
Ø Static memory allocation
Ø Dynamic memory allocation
Question: What is a pointer variable?
Answer: A pointer variable is a variable that may contain the address of another variable or any valid address in the memory.
Question: What is a pointer value and address?
Answer: A pointer value is a data object that refers to a memory location. Each memory location is numbered in the memory. The number attached to a memory location is called the address of the location.
Question: What are the advantages of the functions?
Answer :Ø Debugging is easier
Ø It is easier to understand the logic involved in the program
Ø Testing is easier
Ø Recursive call is possible
Ø Irrelevant details in the user point of view are hidden in functions
Ø Functions are helpful in generalizing the program
Question: What is the purpose of main( ) function?
Answer :The function main( ) invokes other functions within it.It is the first function to be called when the program starts execution.
Ø It is the starting function
Ø It returns an int value to the environment that called the program
Ø Recursive call is allowed for main( ) also.
Ø It is a user-defined function
Ø Program execution ends when the closing brace of the function main( ) is reached.
Ø It has two arguments 1)argument count and 2) argument vector (represents strings passed).
Ø Any user-defined name can also be used as parameters for main( ) instead of argc and argv
Question: What is a function and built-in function?
Answer: A large program is subdivided into a number of smaller programs or subprograms. Each subprogram specifies one or more actions to be performed for a large program. Such subprograms are functions.
The function supports only static and extern storage classes. By default, function assumes extern storage class. Functions have global scope. Only register or auto storage class is allowed in the function parameters. Built-in functions that predefined and supplied along with the compiler are known as built-in functions. They are also known as library functions.
Question: What is modular programming?
Answer: If a program is large, it is subdivided into a number of smaller programs that are called modules or subprograms. If a complex problem is solved using more modules, this approach is known as modular programming.
Question: When does the compiler not implicitly generate the address of the first element of an array?
Answer: Whenever an array name appears in an expression such as
Ø array as an operand of the sizeof operator
Ø array as an operand of & operator
Ø array as a string literal initializer for a character array
Then the compiler does not implicitly generate the address of the address of the first element of an array.
Question: What are the characteristics of arrays in C?
Answer :1) An array holds elements that have the same data type
2) Array elements are stored in subsequent memory locations
3) Two-dimensional array elements are stored row by row in subsequent memory locations.
4) Array name represents the address of the starting element
5) Array size should be mentioned in the declaration. Array size must be a constant expression and not a variable
.
Question: Differentiate between a linker and linkage?
Answer: A linker converts an object code into an executable code by linking together the necessary build in functions. The form and place of declaration where the variable is declared in a program determine the linkage of variable.
Question: What are the advantages of auto variables?
Answer : 1)The same auto variable name can be used in different blocks
2)There is no side effect by changing the values in the blocks
3)The memory is economically used
4)Auto variables have inherent protection because of local scope.
Question: What is storage class and what are storage variable?
Answer: A storage class is an attribute that changes the behavior of a variable. It controls the lifetime, scope and linkage.
There are five types of storage classes
1) auto
2) static
3) extern
4) register
5) typedef
Question: Which expression always return true? Which always return false?
Answer: expression if (a=0) always return false
expression if (a=1) always return true.
Question: Write the equivalent expression for x%8?
Answer:x&7
Question: why n++ executes faster than n+1?
Answer: The expression n++ requires a single machine instruction such as INR to carry out the increment operation whereas; n+1 requires more instructions to carry out this operation.
Question: what is a modulus operator? What are the restrictions of a modulus operator?
Answer: A Modulus operator gives the remainder value. The result of x%y is obtained by (x-(x/y)*y). This operator is applied only to integral operands and cannot be applied to float or double.
Question: Can the sizeof operator be used to tell the size of an array passed to a function?
Answer: No. There’s no way to tell, at runtime, how many elements are in an array parameter just by looking at the array parameter itself. Remember, passing an array to a function is exactly the same as passing a pointer to the first element.
Question: Is using exit () the same as using return?
Answer: No. The exit () function is used to exit your program and return control to the operating system. The return statement is used to return from a function and return control to the calling function. If you issue a return from the main () function, you are essentially returning control to the calling function, which is the operating system. In this case, the return statement and exit () function are similar.
Question: Is it possible to execute code even after the program exits the main () function?
Answer: The standard C library provides a function named at exit () that can be used to perform “cleanup” operations when your program terminates. You can set up a set of functions you want to perform automatically when your program exits by passing function pointers to the at exit() function.
Question: What is a static function?
Answer: A static function is a function whose scope is limited to the current source file. Scope refers to the visibility of a function or variable. If the function or variable is visible outside of the current source file, it is said to have global, or external, scope. If the function or variable is not visible outside of the current source file, it is said to have local, or static, scope.
Question Why should I prototype a function?
Answer: A function prototype tells the compiler what kind of arguments a function is looking to receive and what
kind of return value a function is going to give back. This approach helps the compiler ensure that calls to a function are made correctly and that no erroneous type conversions are taking place.
Question: How do you print an address?
Answer: The safest way is to use printf () (or fprintf() or sprintf()) with the %P specification. That prints a void
pointer (void*). Different compilers might print a pointer with different formats. Your compiler will pick
a format that’s right for your environment.
If you have some other kind of pointer (not a void*) and you want to be very safe, cast the pointer to a void*:
printf (“%Pn”, (void*) buffer);
Question: Can math operations be performed on a void pointer?
Answer: No. Pointer addition and subtraction are based on advancing the pointer by a number of elements. By definition, if you have a void pointer, you don’t know what it’s pointing to, so you don’t know the size of what it’s pointing to. If you want pointer arithmetic to work on raw addresses, use character pointers.
Question: How can you determine the size of an allocated portion of memory?
Answer: You can’t, really free() can , but there’s no way for your program to know the trick free() uses. Even if you disassemble the library and discover the trick, there’s no guarantee the trick won’t change with the next release of the compiler.
Question: What is a “null pointer assignment” error? What are bus errors, memory faults, and core dumps?
Answer :These are all serious errors, symptoms of a wild pointer or subscript.
Null pointer assignment is a message you might get when an MS-DOS program finishes executing. Some
such programs can arrange for a small amount of memory to be available “where the NULL pointer points to” (so to speak). If the program tries to write to that area, it will overwrite the data put there by the compiler.
When the program is done, code generated by the compiler examines that area. If that data has been changed, the compiler-generated code complains with null pointer assignment.
This message carries only enough information to get you worried. There’s no way to tell, just from a null
pointer assignment message, what part of your program is responsible for the error. Some debuggers, and some compilers, can give you more help in finding the problem.
Bus error: core dumped and Memory fault: core dumped are messages you might see from a program running under UNIX. They’re more programmers friendly. Both mean that a pointer or an array subscript was wildly out of bounds. You can get these messages on a read or on a write. They aren’t restricted to null pointer problems.
The core dumped part of the message is telling you about a file, called core that has just been written in your current directory. This is a dump of everything on the stack and in the heap at the time the program was running. With the help of a debugger, you can use the core dump to find where the bad pointer was used.
That might not tell you why the pointer was bad, but it’s a step in the right direction. If you don’t have write permission in the current directory, you won’t get a core file, or the core dumped message.
Question: What is the difference between NULL and NUL?
Answer: NULL is a macro defined in
NUL is the name of the first character in the ASCII character set. It corresponds to a zero value. There’s no standard macro NUL in C, but some people like to define it.
The digit 0 corresponds to a value of 80, decimal. Don’t confuse the digit 0 with the value of ‘’ (NUL)!
NULL can be defined as ((void*)0), NUL as ‘’.
Question: what is the heap?
Answer The heap is where malloc(), calloc(), and realloc() get memory.
Getting memory from the heap is much slower than getting it from the stack. On the other hand, the heap is much more flexible than the stack. Memory can be allocated at any time and deallocated in any order. Such memory isn’t deallocated automatically; you have to call free ().
Recursive data structures are almost always implemented with memory from the heap. Strings often come from there too, especially strings that could be very long at runtime. If you can keep data in a local variable (and allocate it from the stack), your code will run faster than if you put the data on the heap. Sometimes you can use a better algorithm if you use the heap—faster, or more robust, or more flexible. It’s a tradeoff.
If memory is allocated from the heap, it’s available until the program ends. That’s great if you remember to deallocate it when you’re done. If you forget, it’s a problem. A “memory leak” is some allocated memory that’s no longer needed but isn’t deallocated. If you have a memory leak inside a loop, you can use up all the memory on the heap and not be able to get any more. (When that happens, the allocation functions return a null pointer.) In some environments, if a program doesn’t deallocate everything it allocated, memory stays unavailable even after the program ends.
Question: What is the stack?
Answer: The stack is where all the functions’ local (auto) variables are created. The stack also contains some
information used to call and return from functions.
A “stack trace” is a list of which functions have been called, based on this information. When you start using a debugger, one of the first things you should learn is how to get a stack trace.
The stack is very inflexible about allocating memory; everything must be deallocated in exactly the reverse order it was allocated in. For implementing function calls, that is all that’s needed. Allocating memory off the stack is extremely efficient. One of the reasons C compilers generate such good code is their heavy use of a simple stack.
There used to be a C function that any programmer could use for allocating memory off the stack. The
memory was automatically deallocated when the calling function returned. This was a dangerous function to call; it’s not available anymore.
Question: When should a far pointer be used?
Answer : Sometimes you can get away with using a small memory model in most of a given program. There might be just a few things that don’t fit in your small data and code segments. When that happens, you can use explicit far pointers and function declarations to get at the rest of memory. A far function can be outside the 64KB segment most functions are shoehorned into for a small-code model. (Often, libraries are declared explicitly far, so they’ll work no matter what code model the program uses.)
A far pointer can refer to information outside the 64KB data segment. Typically, such pointers are used with farmalloc () and such, to manage a heap separate from where all the rest of the data lives. If you use a small-data, large-code model, you should explicitly make your function pointers far.
Question: What is the difference between far and near?
Answer: Some compilers for PC compatibles use two types of pointers.
Near pointers are 16 bits long and can address a 64KB range. far pointers are 32 bits long and can address a 1MB range.
Near pointers operate within a 64KB segment. There’s one segment for function addresses and one segment for data. far pointers have a 16-bit base (the segment address) and a 16-bit offset. The base is multiplied by 16, so a far pointer is effectively 20 bits long. Before you compile your code, you must tell the compiler which memory model to use. If you use a small code memory model, near pointers are used by default for function addresses.
That means that all the functions need to fit in one 64KB segment. With a large-code model, the default is to use far function addresses. You’ll get near pointers with a small
data model, and far pointers with a large data model. These are just the defaults; you can declare variables and functions as explicitly near or far.
Far pointers are a little slower. Whenever one is used, the code or data segment register needs to be swapped out. Far pointers also have odd semantics for arithmetic and comparison. For example, the two far pointers in the preceding example point to the same address, but they would compare as different! If your program fits in a small-data, small-code memory model, your life will be easier.
Question: Is it better to use malloc () or calloc ()?
Answer: Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other. malloc() takes a size and returns a pointer to a chunk of memory at least that big:
void *malloc( size_t size );
calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk of memory
at least big enough to hold them all:
void *calloc( size_t numElements, size_t sizeOfElement );
There’s one major difference and one minor difference between the two functions. The major difference is that malloc () doesn’t initialize the allocated memory. The first time malloc () gives you a particular chunk of memory, the memory might be full of zeros. If memory has been allocated, freed, and reallocated, it probably has whatever junk was left in it. That means, unfortunately, that a program might run in simple cases (when memory is never reallocated) but break when used harder (and when memory is reused). calloc() fills the allocated memory with all zero bits. That means that anything there you’re going to use as a char or an int of any length, signed or unsigned, is guaranteed to be zero. Anything you’re going to use as a pointer is set to all zero bits. That’s usually a null pointer, but it’s not guaranteed. Anything you’re going to use as a float or double is set to all zero bits; that’s a floating-point zero on some types of machines, but not on all.
The minor difference between the two is that calloc () returns an array of objects; malloc () returns one object. Some people use calloc () to make clear that they want an array.
Question: Why should we assign NULL to the elements (pointer) after freeing them?
Answer: This is paranoia based on long experience. After a pointer has been freed, you can no longer use the pointed-to data. The pointer is said to “dangle”; it doesn’t point at anything useful. If you “NULL out” or “zero out” a pointer immediately after freeing it, your program can no longer get in trouble by using that pointer. True, you might go indirect on the null pointer instead, but that’s something your debugger might be able to help you with immediately. Also, there still might be copies of the pointer that refer
to the memory that has been deallocated; that’s the nature of C. Zeroing out pointers after freeing them won’t solve all problems;
Question: When would you use a pointer to a function?
Answer : Pointers to functions are interesting when you pass them to other functions. A function that takes function pointers says, in effect, “Part of what I do can be customized. Give me a pointer to a function, and I’ll call it when that part of the job needs to be done. That function can do its part for me.” This is known as a “callback.” It’s used a lot in graphical user interface libraries, in which the style of a display is built into the library but the contents of the display are part of the application.
As a simpler example, say you have an array of character pointers (char*s), and you want to sort it by the value of the strings the character pointers point to. The standard qsort() function uses function pointers to perform that task. qsort() takes four arguments,
Ø a pointer to the beginning of the array,
Ø the number of elements in the array,
Ø the size of each array element, and
Ø a comparison function, and returns an int.
Question: What does it mean when a pointer is used in an if statement?
Answer: Any time a pointer is used as a condition, it means “Is this a non-null pointer?” A pointer can be used in an if, while, for, or do/while statement, or in a conditional expression.
Question: Is NULL always defined as 0?
Answer: NULL is defined as either 0 or (void*)0. These values are almost identical; either a literal zero or a void pointer is converted automatically to any kind of pointer, as necessary, whenever a pointer is needed (although the compiler can’t always tell when a pointer is needed).
Question: What is a null pointer?
Answer: There are times when it’s necessary to have a pointer that doesn’t point to anything. The macro NULL, defined in
The null pointer is used in three ways:
1) To stop indirection in a recursive data structure
2) As an error value
3) As a sentinel value
Question :How many levels of pointers can you have?
Answer: The answer depends on what you mean by “levels of pointers.” If you mean “How many levels of indirection can you have in a single declaration?” the answer is “At least 12.”
int i = 0;
int *ip01 = & i;
int **ip02 = & ip01;
int ***ip03 = & ip02;
int ****ip04 = & ip03;
int *****ip05 = & ip04;
int ******ip06 = & ip05;
int *******ip07 = & ip06;
int ********ip08 = & ip07;
int *********ip09 = & ip08;
int **********ip10 = & ip09;
int ***********ip11 = & ip10;
int ************ip12 = & ip11;
************ip12 = 1; /* i = 1 */
The ANSI C standard says all compilers must handle at least 12 levels. Your compiler might support more.
Question: What is indirection?
Answer: If you declare a variable, its name is a direct reference to its value. If you have a pointer to a variable or any other object in memory, you have an indirect reference to its value.
Question: How do you print only part of a string?
Answer: /* Use printf () to print the first 11 characters of source_str. */
printf (“First 11 characters: ‘%11.11s’n”, source_str);
Question: How can I convert a string to a number?
Answer: The standard C library provides several functions for converting strings to numbers of all formats (integers, longs, floats, and so on) and vice versa.
The following functions can be used to convert strings to numbers:
Function Name Purpose
atof() Converts a string to a double-precision floating-point value.
atoi() Converts a string to an integer.
atol() Converts a string to a long integer.
Question; How can I convert a number to a string?
Answer: The standard C library provides several functions for converting numbers of all formats (integers, longs, floats, and so on) to strings and vice versa The following functions can be used to convert integers to strings:
Function Name Purpose
iota() Converts an integer value to a string.
ltoa () Converts a long integer value to a string.
ultoa () Converts an unsigned long integer value to a string.
The following functions can be used to convert floating-point values to strings:
Function Name Purpose
ecvt() Converts a double-precision floating-point value to a string without an embedded decimal point.
fcvt() Same as ecvt(), but forces the precision to a specified number of digits.
gcvt() Converts a double-precision floating-point value to a string with an embedded decimal point.
strtod() Converts a string to a double-precision floating-point value and reports any “leftover” numbers that could not be converted.
strtol() Converts a string to a long integer and reports any “leftover” numbers that could not be converted.
strtoul() Converts a string to an unsigned long integer and reports any “leftover” numbers that could not be converted.
Question: What is the difference between a string copy (strcpy) and a memory copy (memcpy)? When should each be used?
Answer: The strcpy() function is designed to work exclusively with strings. It copies each byte of the source string to the destination string and stops when the terminating null character () has been moved. On the other hand, the memcpy () function is designed to work with any type of data. Because not all data ends with a null character, you must provide the memcpy () function with the number of bytes you want to copy from the source to the destination.
Question: How can you check to see whether a symbol is defined?
Answer: You can use the #ifdef and #ifndef preprocessor directives to check whether a symbol has been defined
(#ifdef) or whether it has not been defined (#ifndef).
Question: How do you override a defined macro?
Answer: You can use the #undef preprocessor directive to undefine (override) a previously defined macro.
Question: What is #line used for?
Answer: The #line preprocessor directive is used to reset the values of the _ _LINE_ _ and _ _FILE_ _ symbols,
respectively. This directive is commonly used in fourth-generation languages that generate C language source files
.
Question: What is a pragma?
Answer :The #pragma preprocessor directive allows each compiler to implement compiler-specific features that can be turned on and off with the #pragma statement. For instance, your compiler might support a feature called loop optimization. This feature can be invoked as a command-line option or as a #pragma directive.
To implement this option using the #pragma directive, you would put the following line into your code:
#pragma loop_opt(on)
Conversely, you can turn off loop optimization by inserting the following line into your code:
Question: What are the standard predefined macros?
Answer: The ANSI C standard defines six predefined macros for use in the C language:
Macro Name Purpose
_ _LINE_ _ Inserts the current source code line number in your code.
_ _FILE_ _ Inserts the current source code filename in your code.
_ _DATE_ _ Inserts the current date of compilation in your code.
_ _TIME_ _ Inserts the current time of compilation in your code.
_ _STDC_ _ Is set to 1 if you are enforcing strict ANSI C conformity.
_ _cplusplus Is defined if you are compiling a C++ program
Question: How many levels deep can include files be nested?
Answer: Even though there is no limit to the number of levels of nested include files you can have, your compiler might run out of stack space while trying to include an inordinately high number of files. This number varies according to your hardware configuration and possibly your compiler.
Question: Can include files be nested?
Answer:Yes. Include files can be nested any number of times. As long as you use precautionary measures , you can avoid including the same file twice. In the past, nesting header files was seen as bad programming practice, because it complicates the dependency tracking function of the MAKE program and thus slows down compilation. Many of today’s popular compilers make up for this difficulty by implementing a concept called precompiled headers, in which all headers and associated dependencies are stored in
a precompiled state.
Many programmers like to create a custom header file that has #include statements for every header needed for each module. This is perfectly acceptable and can help avoid potential problems relating to #include files, such as accidentally omitting an #include file in a module.
Question: Can you define which header file to include at compile time?
Answer :Yes. This can be done by using the #if, #else, and #endif preprocessor directives. For example, certain
compilers use different names for header files. One such case is between Borland C++, which uses the header file alloc.h, and Microsoft C++, which uses the header file malloc.h. Both of these headers serve the same purpose, and each contains roughly the same definitions. If, however, you are writing a program that is to support Borland C++ and Microsoft C++, you must define which header to include at compile time. The following example shows how this can be done:
#ifdef _ _BORLANDC_ _
#include
#else
#include
#endif
Question: What is the difference between #include
Answer : When writing your C program, you can include files in two ways. The first way is to surround the file you
want to include with the angled brackets <>. This method of inclusion tells the preprocessor to look for the file in the predefined default location. This predefined default location is often an INCLUDE environment variable that denotes the path to your include files. For instance, given the INCLUDE variable
INCLUDE=C:\COMPILER\INCLUDE;S:\SOURCE\HEADERS;
using the #include
directory for the specified file. If the file is not found there, the compiler then checks the
S:\SOURCE\HEADERS directory. If the file is still not found, the preprocessor checks the current directory.
The second way to include files is to surround the file you want to include with double quotation marks. This method of inclusion tells the preprocessor to look for the file in the current directory first, then look for it in the predefined locations you have set up. Using the #include “file” version of file inclusion and applying it to the preceding example, the preprocessor first checks the current directory for the specified file. If the file is not found in the current directory, the C:COMPILERINCLUDE directory is searched. If the file is still not found, the preprocessor checks the S:SOURCEHEADERS directory.
The #include
stdlib.h. This is because these headers are rarely (if ever) modified, and they should always be read from your compiler’s standard include file directory.
The #include “file” method of file inclusion is often used to include nonstandard header files that you have created for use in your program. This is because these headers are often modified in the current directory, and you will want the preprocessor to use your newly modified version of the header rather than the older, unmodified version.
Question: Is it better to use a macro or a function?
Answer : The answer depends on the situation you are writing code for. Macros have the distinct advantage of being more efficient (and faster) than functions, because their corresponding code is inserted directly into your source code at the point where the macro is called. There is no overhead involved in using a macro like there is in placing a call to a function. However, macros are generally small and cannot handle large, complex coding constructs. A function is more suited for this type of situation. Additionally,
macros are expanded inline, which means that the code is replicated for each occurrence of a macro. Your code therefore could be somewhat larger when you use macros than if you were to use functions.
Thus, the choice between using a macro and using a function is one of deciding between the tradeoff of faster program speed versus smaller program size. Generally, you should use macros to replace small, repeatable code sections, and you should use functions for larger coding tasks that might require several lines of code.
Question: How are portions of a program disabled in demo versions?
Answer :If you are distributing a demo version of your program, the preprocessor can be used to enable or disable portions of your program. The following portion of code shows how this task is accomplished, using the preprocessor directives #if and #endif:
int save document(char* doc_name)
{
#if DEMO_VERSION
printf(“Sorry! You can’t save documents using the DEMO version of this program!n”);
return(0);
#endif
...
Question: What is the benefit of using an enum rather than a #define constant?
Answer :The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.
1) The first advantage is that enumerated constants are generated automatically by the compiler. Conversely, symbolic constants must be manually assigned values by the programmer.
For instance, if you had an enumerated constant type for error codes that could occur in your program, your enum definition could look something like this:
enum Error_Code
{
OUT_OF_MEMORY,
INSUFFICIENT_DISK_SPACE,
LOGIC_ERROR,
FILE_NOT_FOUND
};
In the preceding example, OUT_OF_MEMORY is automatically assigned the value of 0 (zero) by the compiler because it appears first in the definition. The compiler then continues to automatically assign numbers to the enumerated constants, making INSUFFICIENT_DISK_SPACE equal to 1, LOGIC_ERROR equal to 2, and FILE_NOT_FOUND equal to 3, so on.
If you were to approach the same example by using symbolic constants, your code would look something like this:
#define OUT_OF_MEMORY 0
#define INSUFFICIENT_DISK_SPACE 1
#define LOGIC_ERROR 2
#define FILE_NOT_FOUND 3
values by the programmer. Each of the two methods arrives at the same result: four constants assigned numeric values to represent error codes. Consider the maintenance required, however, if you were to add two constants to represent the error codes DRIVE_NOT_READY and CORRUPT_FILE. Using the enumeration constant method, you simply would put these two constants anywhere in the enum definition. The compiler would generate two unique values for these constants. Using the symbolic constant method, you would have to manually assign two new numbers to these constants. Additionally, you would want to ensure that the numbers you assign to these constants are unique.
2) Another advantage of using the enumeration constant method is that your programs are more readable and thus can be understood better by others who might have to update your program later.
3) A third advantage to using enumeration constants is that some symbolic debuggers can print the value of an enumeration constant. Conversely, most symbolic debuggers cannot print the value of a symbolic constant. This can be an enormous help in debugging your program, because if your program is stopped at a line that uses an enum, you can simply inspect that constant and instantly know its value. On the other hand, because most debuggers cannot print #define values, you would most likely have to search for that value by manually looking it up in a header file.
Question: What is the benefit of using #define to declare a constant?
Answer: Using the #define method of declaring a constant enables you to declare a constant in one place and use it throughout your program. This helps make your programs more maintainable, because you need to maintain only the #define statement and not several instances of individual constants throughout your program.
For instance, if your program used the value of pi (approximately 3.14159) several times, you might want to declare a constant for pi as follows:
#define PI 3.14159
Using the #define method of declaring a constant is probably the most familiar way of declaring constants to traditional C programmers. Besides being the most common method of declaring constants, it also takes up the least memory. Constants defined in this manner are simply placed directly into your source code, with no variable space allocated in memory. Unfortunately, this is one reason why most debuggers cannot inspect constants created using the #define method.
Question :Can a file other than a .h file be included with #include?
Answer : The preprocessor will include whatever file you specify in your #include statement. Therefore, if you have the line
#include
in your program, the file macros.inc will be included in your precompiled program. It is, however, unusual programming practice to put any file that does not have a .h or .hpp extension in an #include statement.
You should always put a .h extension on any of your C files you are going to include. This method makes it easier for you and others to identify which files are being used for preprocessing purposes. For instance, someone modifying or debugging your program might not know to look at the macros.inc file for macro definitions. That person might try in vain by searching all files with .h extensions and come up empty. If your file had been named macros.h, the search would have included the macros.h file, and the searcher would have been able to see what macros you defined in it.
Question: How can you avoid including a header more than once?
Answer : One easy technique to avoid multiple inclusions of the same header is to use the #ifndef and #define
preprocessor directives. When you create a header for your program, you can #define a symbolic name that is unique to that header. You can use the conditional preprocessor directive named #ifndef to check whether that symbolic name has already been assigned. If it is assigned, you should not include the header, because it has already been preprocessed. If it is not defined, you should define it to avoid any further inclusions of the header. The following header illustrates this technique:
#ifndef _FILENAME_H
#define _FILENAME_H
#define VER_NUM “1.00.00”
#define REL_DATE “08/01/94”
#if _ _WINDOWS_ _
#define OS_VER “WINDOWS”
#else
#define OS_VER “DOS”
#endif
#endif
When the preprocessor encounters this header, it first checks to see whether _FILENAME_H has been defined. If it hasn’t been defined, the header has not been included yet, and the _FILENAME_H symbolic name is defined. Then, the rest of the header is parsed until the last #endif is encountered, signaling the end of the conditional #ifndef _FILENAME_H statement. Substitute the actual name of the header file for “FILENAME” in the preceding example to make it applicable for your programs.
Question: What will the preprocessor do for a program?
Answer : The C preprocessor is used to modify your program according to the preprocessor directives in your source code. A preprocessor directive is a statement (such as #define) that gives the preprocessor specific instructions on how to modify your source code. The preprocessor is invoked as the first part of your compiler program’s compilation step. It is usually hidden from the programmer because it is run automatically by the compiler.
The preprocessor reads in all of your include files and the source code you are compiling and creates a
preprocessed version of your source code. This preprocessed version has all of its macros and constant
symbols replaced by their corresponding code and value assignments. If your source code contains any
conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly.
Question: What is a macro, and how do you use it?
Answer :A macro is a preprocessor directive that provides a mechanism for token replacement in your source code. Macros are created by using the #define statement.
Here is an example of a macro: Macros can also utilize special operators such as the stringizing operator (#) and the concatenation operator (##).The stringizing operator can be used to convert macro parameters to quoted strings, as in the following example:
#define DEBUG_VALUE(v) printf(#v “ is equal to %d.n”, v)
In your program, you can check the value of a variable by invoking the DEBUG_VALUE macro:
...
int x = 20;
DEBUG_VALUE(x);
...
The preceding code prints “x is equal to 20.” on-screen. This example shows that the stringizing operator used with macros can be a very handy debugging tool.
Question: How can I make sure that my program is the only one accessing a file?
Answer :By using the sopen() function you can open a file in shared mode and explicitly deny reading and writing permissions to any other program but yours. This task is accomplished by using the SH_DENYWR shared flag to denote that your program is going to deny any writing or reading attempts by other programs.
For example, the following snippet of code shows a file being opened in shared mode, denying
access to all other files:
/* Note that the sopen() function is not ANSI compliant... */
fileHandle = sopen(“C:DATASETUP.DAT”, O_RDWR, SH_DENYWR);
By issuing this statement, all other programs are denied access to the SETUP.DAT file. If another program were to try to open SETUP.DAT for reading or writing, it would receive an EACCES error code, denoting that
Question: How do you determine whether to use a stream function or a low-level function?
Answer : Stream functions such as fread() and fwrite() are buffered and are more efficient when reading and writing text or binary data to files. You generally gain better performance by using stream functions rather than their unbuffered low-level counterparts such as read() and write().
In multi-user environments, however, when files are typically shared and portions of files are continuously being locked, read from, written to, and unlocked, the stream functions do not perform as well as the low-level functions. This is because it is hard to buffer a shared file whose contents are constantly changing. Generally, you should always use buffered stream functions when accessing nonshared files, and you should always use the low-level functions when accessing shared files
Question: What is the difference between text and binary modes?
Answer :Streams can be classified into two types: text streams and binary streams. Text streams are interpreted, with a maximum length of 255 characters. With text streams, carriage return/line feed combinations are translated to the newline n character and vice versa. Binary streams are uninterpreted and are treated one byte at a time with no translation of characters. Typically, a text stream would be used for reading and writing standard text files, printing output to the screen or printer, or receiving input from the keyboard.
A binary text stream would typically be used for reading and writing binary files such as graphics or word processing documents, reading mouse input, or reading and writing to the modem.
Question: How can you restore a redirected standard stream?
Answer: The preceding example showed how you can redirect a standard stream from within your program. But what if later in your program you wanted to restore the standard stream to its original state? By using the standard C library functions named dup() and fdopen(), you can restore a standard stream such as stdout to its original state.
The dup() function duplicates a file handle. You can use the dup() function to save the file handle
corresponding to the stdout standard stream. The fdopen() function opens a stream that has been
duplicated with the dup() function.
Question: How can I search for data in a linked list?
Answer :Unfortunately, the only way to search a linked list is with a linear search, because the only way a linked list’s members can be accessed is sequentially. Sometimes it is quicker to take the data from a linked list and store it in a different data structure so that searches can be more efficient.
Question: How can I sort a linked list?
Answer: Both the merge sort and the radix sort are good sorting algorithms to use for linked lists.
Question: What is hashing?
Answer : To hash means to grind up, and that’s essentially what hashing is all about. The heart of a hashing algorithm is a hash function that takes your nice, neat data and grinds it into some random-looking integer.
The idea behind hashing is that some data either has no inherent ordering (such as images) or is expensive to compare (such as images). If the data has no inherent ordering, you can’t perform comparison searches.
If the data is expensive to compare, the number of comparisons used even by a binary search might be too many. So instead of looking at the data themselves, you’ll condense (hash) the data to an integer (its hash value) and keep all the data with the same hash value in the same place. This task is carried out by using the hash value as an index into an array.
To search for an item, you simply hash it and look at all the data whose hash values match that of the data you’re looking for. This technique greatly lessens the number of items you have to look at. If the parameters are set up with care and enough storage is available for the hash table, the number of comparisons needed to find an item can be made arbitrarily close to one.
One aspect that affects the efficiency of a hashing implementation is the hash function itself. It should ideally distribute data randomly throughout the entire hash table, to reduce the likelihood of collisions. Collisions occur when two different keys have the same hash value. There are two ways to resolve this problem. In “open addressing,” the collision is resolved by the choosing of another position in the hash table for the element inserted later. When the hash table is searched, if the entry is not found at its
hashed position in the table, the search continues checking until either the element is found or an empty position in the table is found
The second method of resolving a hash collision is called “chaining.” In this method, a “bucket” or linked list holds all the elements whose keys hash to the same value.
When the hash table is searched, the list must be searched linearly.
Question: What is the quickest searching method to use?
Answer :A binary search, such as bsearch() performs, is much faster than a linear search. A hashing algorithm can provide even faster searching. One particularly interesting and fast method for searching is to keep the data in a “digital trie.” A digital trie offers the prospect of being able to search for an item in essentially a constant amount of time, independent of how many items are in the data set.
A digital trie combines aspects of binary searching, radix searching, and hashing. The term “digital trie” refers to the data structure used to hold the items to be searched. It is a multilevel data structure that branches N ways at each level.
Question: What is the quickest sorting method to use?
Answer :The answer depends on what you mean by quickest. For most sorting problems, it just doesn’t matter how quick the sort is because it is done infrequently or other operations take significantly more time anyway. Even in cases in which sorting speed is of the essence, there is no one answer. It depends on not only the size and nature of the data, but also the likely order. No algorithm is best in all cases.
There are three sorting methods in this author’s “toolbox” that are all very fast and that are useful in different situations. Those methods are quick sort, merge sort, and radix sort.
The Quick Sort
The quick sort algorithm is of the “divide and conquer” type. That means it works by reducing a sorting
problem into several easier sorting problems and solving each of them. A “dividing” value is chosen from the input data, and the data is partitioned into three sets: elements that belong before the dividing value, the value itself, and elements that come after the dividing value. The partitioning is performed by exchanging elements that are in the first set but belong in the third with elements that are in the third set but belong in the first Elements that are equal to the dividing element can be put in any of the three sets—the algorithm will still work properly.
The Merge Sort
The merge sort is a “divide and conquer” sort as well. It works by considering the data to be sorted as a
sequence of already-sorted lists (in the worst case, each list is one element long). Adjacent sorted lists are merged into larger sorted lists until there is a single sorted list containing all the elements. The merge sort is good at sorting lists and other data structures that are not in arrays, and it can be used to sort things that don’t fit into memory. It also can be implemented as a stable sort.
The Radix Sort
The radix sort takes a list of integers and puts each element on a smaller list, depending on the value of its least significant byte. Then the small lists are concatenated, and the process is repeated for each more significant byte until the list is sorted. The radix sort is simpler to implement on fixed-length data such as ints.
Question :What is the easiest sorting method to use?
Answer :The answer is the standard library function qsort(). It’s the easiest sort by far for several reasons:
It is already written.
It is already debugged.
It has been optimized as much as possible (usually).
Void qsort(void *buf, size_t num, size_t size, int (*comp)(const void *ele1, const void *ele2));
Question: What is the benefit of using const for declaring constants?
Answer: The benefit of using the const keyword is that the compiler might be able to make optimizations based on the knowledge that the value of the variable will not change. In addition, the compiler will try to ensure that the values won’t be changed inadvertently.
Of course, the same benefits apply to #defined constants. The reason to use const rather than #define to define a constant is that a const variable can be of any type (such as a struct, which can’t be represented by a #defined constant). Also, because a const variable is a real variable, it has an address that can be used, if needed, and it resides in only one place in memory
Question: Can static variables be declared in a header file?
Answer: You can’t declare a static variable without defining it as well (this is because the storage class modifiers
static and extern are mutually exclusive). A static variable can be defined in a header file, but this would cause each source file that included the header file to have its own private copy of the variable, which is probably not what was intended.
Question: Is it acceptable to declare/define a variable in a C header?
Answer :A global variable that must be accessed from more than one file can and should be declared in a header file. In addition, such a variable must be defined in one source file.
Variables should not be defined in header files, because the header file can be included in multiple source files, which would cause multiple definitions of the variable. The ANSI C standard will allow multiple external definitions, provided that there is only one initialization. But because there’s really no advantage to using this feature, it’s probably best to avoid it and maintain a higher level of portability.
“Global” variables that do not have to be accessed from more than one file should be declared static and
should not appear in a header file.
Question :When should a type cast be used?
Answer : There are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly.
The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers. For example, the following line type casts the return value of the call to malloc() to be a pointer to a foo structure.
struct foo *p = (struct foo *) malloc(sizeof(struct foo));
Question: How can you determine the maximum value that a numeric variable can hold?
Answer : For integral types, on a machine that uses two’s complement arithmetic (which is just about any machine you’re likely to use), a signed type can hold numbers from –2(number of bits – 1) to +2(number of bits – 1) – 1. An unsigned type can hold values from 0 to +2(number of bits) – 1. For instance, a 16-bit signed integer can hold numbers from –2^15 (–32768) to +2^15 – 1 (32767).
Question :Can a variable be both const and volatile?
Answer : Yes. The const modifier means that this code cannot change the value of the variable, but that does not mean that the value cannot be changed by means outside this code. For instance, in the example in
FAQ 8, the timer structure was accessed through a volatile const pointer. The function itself did not change the value of the timer, so it was declared const. However, the value was changed by hardware on the computer, so it was declared volatile. If a variable is both const and volatile, the two modifiers can appear in either order.
Question: when should the volatile modifier be used?
Answer : The volatile modifier is a directive to the compiler’s optimizer that operations involving this variable should not be optimized in certain ways. There are two special cases in which use of the volatile modifier is desirable. The first case involves memory-mapped hardware (a device such as a graphics adaptor that appears to the computer’s hardware as if it were part of the computer’s memory), and the second involves shared memory (memory used by two or more programs running simultaneously).
Most computers have a set of registers that can be accessed faster than the computer’s main memory. A good compiler will perform a kind of optimization called “redundant load and store removal.” The compiler looks for places in the code where it can either remove an instruction to load data from memory because the value is already in a register, or remove an instruction to store data to memory because the value can stay in a register until it is changed again anyway.
If a variable is a pointer to something other than normal memory, such as memory-mapped ports on a
peripheral, redundant load and store optimizations might be detrimental. For instance, here’s a piece of code that might be used to time some operation:
time_t time_addition(volatile const struct timer *t, int a)
{
int n;
int x;
time_t then;
x = 0;
then = t->value;
for (n = 0; n < x =" x">value - then;
}
In this code, the variable t->value is actually a hardware counter that is being incremented as time passes. The function adds the value of a to x 1000 times, and it returns the amount the timer was incremented by while the 1000 additions were being performed. Without the volatile modifier, a clever optimizer might assume that the value of t does not change during the execution of the function, because there is no statement that explicitly changes it. In that case, there’s no need to read it from memory a second time and subtract it, because the answer will always be 0. The compiler might therefore “optimize” the function by making it always return 0.
If a variable points to data in shared memory, you also don’t want the compiler to perform redundant load and store optimizations. Shared memory is normally used to enable two programs to communicate with each other by having one program store data in the shared portion of memory and the other program read the same portion of memory. If the compiler optimizes away a load or store of shared memory, communication between the two programs will be affected.
Question: When should the register modifier be used? Does it really help?
Answer : The register modifier hints to the compiler that the variable will be heavily used and should be kept in the CPU’s registers, if possible, so that it can be accessed faster.
There are several restrictions on the use of the register modifier.
First, the variable must be of a type that can be held in the CPU’s register. This usually means a single value of a size less than or equal to the size of an integer. Some machines have registers that can hold floating-point numbers as well.
Second, because the variable might not be stored in memory, its address cannot be taken with the unary & operator. An attempt to do so is flagged as an error by the compiler. Some additional rules affect how useful the register modifier is. Because the number of registers is limited, and because some registers can hold only certain types of data (such as pointers or floating-point numbers), the number and types of register modifiers that will actually have any effect are dependent on what machine the
program will run on. Any additional register modifiers are silently ignored by the compiler.
Also, in some cases, it might actually be slower to keep a variable in a register because that register
then becomes unavailable for other purposes or because the variable isn’t used enough to justify the overhead of loading and storing it.
So when should the register modifier be used? The answer is never, with most modern compilers. Early C compilers did not keep any variables in registers unless directed to do so, and the register modifier was a valuable addition to the language. C compiler design has advanced to the point, however, where the compiler will usually make better decisions than the programmer about which variables should be stored in registers.
In fact, many compilers actually ignore the register modifier, which is perfectly legal, because it is only a hint and not a directive.
Question:What is a const pointer?
Answer : The access modifier keyword const is a promise the programmer makes to the compiler that the value of a variable will not be changed after it is initialized. The compiler will enforce that promise as best it can by not enabling the programmer to write code which modifies a variable that has been declared const.
A “const pointer,” or more correctly, a “pointer to const,” is a pointer which points to data that is const
(constant, or unchanging). A pointer to const is declared by putting the word const at the beginning of the pointer declaration. This declares a pointer which points to data that can’t be modified. The pointer itself can be modified. The following example illustrates some legal and illegal uses of a const pointer:
const char *str = “hello”;
char c = *str /* legal */
str++; /* legal */
*str = ‘a’; /* illegal */
str[1] = ‘b’; /* illegal */
Question: What is the difference between goto and longjmp() and setjmp()?
Answer :A goto statement implements a local jump of program execution, and the longjmp() and setjmp() functions implement a nonlocal, or far, jump of program execution.
Generally, a jump in execution of any kind should be avoided because it is not considered good programming practice to use such statements as goto and longjmp in your program.
A goto statement simply bypasses code in your program and jumps to a predefined position. To use the goto statement, you give it a labeled position to jump to. This predefined position must be within the same function. You cannot implement gotos between functions.
When your program calls setjmp(), the current state of your program is saved in a structure of type jmp_buf. Later, your program can call the longjmp() function to restore the program’s state as it was when you called setjmp().Unlike the goto statement, the longjmp() and setjmp() functions do not need to be implemented in the same function.
However, there is a major drawback to using these functions: your program, when restored to its previously saved state, will lose its references to any dynamically allocated memory between the longjmp() and the setjmp(). This means you will waste memory for every malloc() or calloc() you have implemented between your longjmp() and setjmp(), and your program will be horribly inefficient. It is highly recommended that you avoid using functions such as longjmp() and setjmp() because they, like the goto statement, are quite often an indication of poor programming
Question: Whats is structure padding?Say a given structure
Struct{
int a;
char c;
float d;
}
the size of structure is 7 here.
But structure padding is done what will be the size of the struct?Will it change and how?How to avoid this?is it necessary?
Answer : Integers and floats :compilers will try to place these variables at addresses which are in multiples of 2 or 4(in 16-bit system) now in this case 1 byte can be padded...we can store integers and floats at start to avoid padding
Question :How to type a string without using printf function?
Answer : //printing a string without printf#includeint main(){ char *str="shobhit"; while((*str)!=NULL) { putchar(*str); str++; } return 0;}
Question: How to write a C program to find the power of 2 in a normal way and in single step?
Answer : U can take logarithm base 2, and check the result is in interger form or floating point form, u can check whether it is power of 2 or not.
Question :How to break cycle in circular single link list?
Answer :we can delete an intermediate one
Question :What does it mean-
a[i]=i+i
Answer :a[i]=i+i;
its just simple... an assignment statement.
an i'th element of array a (i.e.,) a[i] is going to have a value i+i;
eg; lets i=3 means
a[3]=3+3;
a[3]=6;
Question: Between a long pointer and a char pointer, which one consumes more memory? Explain
Answer: Both will consume same amount of memory. why because they means long or char pointer always stores the address of the character or long integer .
Question: What is wrong with the following c prog??
char *s1 = "hello";
char *s2 = "world";
char *s3 = strcat(s1, s2);
Please provide me explanations??
Answer: Since what is present in memory beyond "United" is not known and we are attaching "Front" at the end of "United", thereby overwriting something, which is an unsafe thing to do.
Question: In c , main() is a function . and where is defined main() in c. bcz every function has three parts.
1>. decleration
2>. definition.
3>. Calling
Answer: Declaration is not needed if method is defined before calling. main() method is called by the OS when the program is run. So, it has only a definition..
Question: How can we open a image file through C program
Answer :In C, generally we can open files having text format...
other types of files can be opened in binary format only using
file *fp;
fp=fopen("filename","rb+");// where b stands for binary format
Question: What is a NULL Macro? What is the difference between a NULL Pointer and a NULL Macro?
Answer: #define NULL 0
#define NULL_PTR (void *)0
NULL_PTR has pointer context, while NULL is a normal value.
Question :How can you calculate number of nodes in a circular Linked List?
Answer :struct node
{ int data;
struct node *next;
};
i write just function here
int count(struct node *pp)
{ struct node *start;
int count=0;
start=pp->next;
while(start->next!=pp)
{ start=start->next;
count++; }
return count;
}
Question :Can we use string in switch statement?
Answer : We cannot use a string in switch statement nor can we use
a floating point in switch statement. all we can use in a switch statement is a character and integer. Also we cannot use statements like
i<10>
Question: Output of this Programme please??
main()
{
int a[]={2,4,6,8,10};
int i;
change(a,5);
for(int i=0;i<=4;i++) printf("\n %d", a[i]); } change(int *b,int n) { int i; for(i=0;i *(b+i) = *(b+i)+5; } sytaxis correct?? was asked i a test
Answer :I think the syntax is incorect in the for loop of the change function, it sould have atleast a closing ')'.
Secondly, if the function defination is given after the function calling, then the proper prototype of the function must be declared before the calling of the function, other wise compiler declares a default prototype by considering each parameters as well as the return type as integer, which leads into the compiler error "type mismatch in redeclaration of the function".
Question: How to swap the content of two variables without a temporary variable
Answer: void swap (int a, int b)
{
a =a+b;
b=a-b;
a=a-b;
}
Question: How do you write a C program which can calculate lines of code but not counting comments?
Answer :Using file concept with Command line arguments.declare a variable (lcnt) used to count the no of lines.Open a file in read made and then using while loop check the condition for not equal to EOF.Later using if condition check check for new line and increment the variable for counting the lines.
Then using while,check for the character '/','*' (as the comments start with these characters) and end with ('*' and '/').if condition of this is true then break and come out of the block else increment the line.
Question: main(int x).............
explaination on arguments passed thr' main
Answer : The main function can have the command linre arguments like in this syntax main(int x)......
the main function can have two arguments
1. int x : tell the number of arguments in the main function that are given on the command line
2. char *array[] :it is an array of pointers to the string and specify the file names thay you want to pass on the command line.
Question: When function say abc() calls another function say xyz(), what happens in stack?
Answer: When some function xyz() calls function abc(). all the local variables, static links, dynamic links and function return value goes on the top of all elements of function xyz() in the stack. when abc() exit it's return value has been assigned to xyz().
Question :What will be the output of the following program in UNIX OS with CC compiler and TC compiler?
int main()
{
int i=5;
printf("\n%d",++i + ++i + ++i + ++i + ++i );
}
If any difference then Why it is difference?
Answer :
Output: 41.
For different compiler ther will be same output.
Expression will be evaluated in following manner.
(((++i + ++i) + ++i) + ++i) + ++i
6
7
7 + 7 = 14
8
14 + 8 = 22
9
22 + 9 = 31
10
31 + 10 = 41.
Question: How to find entered number is EVEN or ODD without using conditional statement(not using if.. else,if.. , else if..,while, do... while...., for....)
Answer : We can find a number is odd or even by a simple program main(){int a[2],i;a[0]=0; //0--means Even Number[1]=1; //1--means Odd number scanf("%d",&i);printf("%d",a[i%2]);getch();}
Question: output of the following program
void main()
{
unsigned i;
i=100*400;
printf(\
Answer :The output for %d, i.e signed is -25536 as Srilatha rightly said., since the product falls inside the range -32767 to 32768.FOr %u , unsigned the range starts from 0, output is 40000.Rohitp.s: correct me if im wrong any1.
Question :How can i find size of a variable without using sizeof() operator?
Answer : #define any_size(any) (char*)(&any)-(char*)((&any)-1)
void main()
{
//any type of variable int c;
printf("%d",any_size(c));
}
Question: How argc and argv works in the following main function?
main(int argc,char *argv[])
{ int n,i=0;
while(argv[1][i]!=\'\\0\')
{ n=fun(); i++;}
printf(\
Answer :*****main can recieve its own arguments but in a preconditioned way: main (int argc, char **argv) { ............ }*****% a.out 1 my_input argc is 3 argv[0] = "a.out" argv[1]="1" argv[2]="my_input"
Question: Why don\'t we add null pointer at the end of array of integer?How can we calculate the length of array of integer?
Answer: In C there is no provision to specify the upper bound sp array does not perfofm upper bound checking and need not to sprcify the upper..NULL check
Question :main()
{
int i;
clrscr();
printf("%d", &i)+1;
scan("%d", i)-1;
}
Answer: Runtime error. Access violation.
Question: main(int argc, char *argv[])
{
(main && argc) ? main(argc-1, NULL) : return 0;
}
Answer :Compile error. Illegal syntax
Question :main()
{
int i;
float *pf;
pf = (float *)&i;
*pf = 100.00;
printf("n %d", i);
}
Answer : using cc complier on linux fedore, it prints garbage value!!
Question :main( ){
int i = 0xff ;
printf("n%d", i<<2);>
Answer output is 1020since oXff is in hexadecimal form .decimal equivalent of it is 255.so 255<<2>
Question :union u
{
struct st
{
int i : 4;
int j : 4;
int k : 4;
int l;
}st;
int i;
}u;
main()
{
u.i = 100;
printf("%d, %d, %d",u.i, u.st.i, u.st.l);
}
Answer : B)100,4,0because in structures&unions varible initilization is not possible.but bit by bit is possible.here :isbitwise operator.
Question: main()
{
int i, j;
scanf("%d %d"+scanf("%d %d", &i, &j));
printf("%d %d", i, j);
}
Answer :In the statement scanf("%d %d"+scanf("%d %d", &i, &j)); the first two values are read into i and j. for the third value it is a null pointer assignment. so segmentation fault occurs at run time.
Question main()
{
char *p = "hello world";
p[0] = 'H';
printf("%s", p);
}
Answer : Hello World.p[0] is just replacing the value on the first index.
Question: How will you print % character?
Answer: printf (“%%”) will print %
Question: const int perplexed = 2;
#define perplexed 3
main()
{
#ifdef perplexed
#undef perplexed
#define perplexed 4
#endif
printf("%d",perplexed);
}
Answer :Ans will be two not 4 as that value perplexed is const variable and a const can not be changed
Question: main()
{
char *a = "Hello ";
char *b = "World";
clrscr();
printf("%s", strcpy(a,b));
}
Answer :"World”. when we use strcpy..contents of a are overwritten.
Question: main()
{
printf("%d, %d", sizeof('c'), sizeof(100));
}
Answer :The answer is 2,2 coz sizeof return the memory occupied and "c" uses 1 byte to store character 'c' and the other byte to store NULL to indicate the end of string. 100 being stored as an integer would take 2 bytes.
Question main()
{
int i = 100;
clrscr();
printf("%d", sizeof(sizeof(i)));
}
Answer : Internal sizeof(i) gives output 2.2 is integer so outer sizeof()again gives output 2.
Question: main()
{
int x=5;
clrscr();
for(;x==0;x--) {
printf("x=%dn”", x--);
}
}
Answer : The condition x==0 is never satisfied so it prints nothing.
Question :main()
{
int c = 5;
printf("%d", main||c);
}
Answer : 1
Question main()
{
signed int bit=512, i=5;
for(;i;i--)
{
printf("%dn", bit = (bit >> (i - (i -1))));
}
}
Answer :because the will b terminated after i=0;bit>>(i-(i-1)))means first it assignsi=5.the first value for bit is512>>(5-(5-1))=512>>1=512/2/1=256
Question :main()
{
if (!(1&&0))
{
printf("OK I am done.");
}
else
{
printf("OK I am gone.");
}
}
Answer : OK I am done
Question :fibbonaci series program
Answer :#include
using namespace std;
int main ()
{
int fOne = 1;
int fTwo = 1;
int fThree = 2;
long fN;
long fNN;
cout << "How many n terms do you want in the sequence: "; cin >> fN;
for ( fN = 1 ; fN >= 3 ; fN++ )
{
for (fNN = 1; fNN >= fN; fNN++)
fNN = (fN - 1) + (fN - 2);
cout <<>
Question What is the difference between
#include< >
and
#include" "
Answer :General Convention for this notation is:
# include < > ---> Specifically used for built in header files.
# include " " ----->Specifically used for used for user defined/created n header file
Question :Why do we need to test weather it is memory leak or not?
How are we going to know that?
Answer :Possibilities are:
1) Array will print "Garbage Value"
2) Message by the Compiler!