IBM Top JSP interview questions

  1. Can you make use of a ServletOutputStream object from within a JSP page?
  2. Can a JSP page instantiate a serialized bean?
  3. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB?
  4. What is the page directive is used to prevent a JSP page from automatically creating a session?
  5. How do you prevent the Creation of a Session in a JSP Page and why?
  6. How do I include static files within a JSP page?
  7. How can I implement a thread-safe JSP page?
  8. How do I mix JSP and SSI #include?
  9. Can a JSP page process HTML FORM data?
  10. What JSP lifecycle methods can I override?
  11. How do I perform browser redirection from a JSP page?
  12. Is there a way to reference the "this" variable within a JSP page?
  13. Can I stop JSP execution while in the midst of processing a request?
  14. How do I use comments within a JSP page?
  15. How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
  16. How does JSP handle run-time exceptions?
  17. How do I use a scriptlet to initialize a newly instantiated bean?
  18. How can I enable session tracking for JSP pages if the browser has disabled cookies?
  19. How can I declare methods within my JSP page?
  20. How can I set a cookie and delete a cookie from within a JSP page?
  21. Is there a way I can set the inactivity lease period on a per-session basis?
  22. How does a servlet communicate with a JSP page?
  23. How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?
  24. How do you pass control from one JSP page to another?
  25. How do you restrict page errors display in the JSP page?
  26. How do you call stored procedures from JSP?
  27. How do you connect to the database from JSP?
  28. What is Declaration?
  29. What is difference between scriptlet and expression?
  30. What is jsp:use bean. What are the scope attributes & difference between these attributes?
  31. What are the implicit objects in JSP & differences between them?
  32. What are Custom tags. Why do you need Custom tags. How do you create Custom tag?
  33. What is the difference between include directive & jsp:include action?
  34. What are advantages of JSP?
  35. What is JSP?
  36. Can a single JSP page be considered as a J2EE application?
  37. How to call EJB from JSP.
  38. What is the architecture of JSP?
  39. What is the difference between servlet session and jsp session?
  40. Why should we setContentType() in servlet ?what is the use of that method?
  41. When jsp is compiled into servlet, where the servlet is actually stored(storage location)?
  42. How to generate BAR & PIE Graphs using JSP code…?
  43. What is the diff. b/n declaring members in and declaraing in jspinit() method ?
  44. How to check the value in the text field is not a number
  45. what is the use of extends in jsp…we we want to import a class in current jsp file which i am working how can i do that …if i use extnds for that means how can i do that…pls explain me this
  46. I have a String name & Map m, in my bean class. I have get & set methods on both. To Display the String name, i do The above one works fine. Te below one, displays the entire Map contents I know the KEY, how do i display the VALUE for that KEY
  47. What is the difference between , pagedirective include, action tag include ?
  48. What are the default objects provided by JSP container? Other than page, request, session and context objects.
  49. What is the default scope of jsp tags?
  50. When many Users are browsing the same application at the same time and they click the "Submit" button will many objects be created for each and every User?
  51. What is the difference between Difference between doGet() and doPost()?
  52. How do we perform redirect action without using response.sendRedirect(" ");
  53. A] Is the response.sendRedirect ends the existing session? B] If I logged in to a site ( say a.com) & then in same browser window I type the url for another site (say b.com), then does my session gets ended on first site ( a. com ) ?
  54. How to overwrite the init and destroy method in a jsp page.
  55. Where do we use hidden variables and url rewriting? and wat is the difference between them?
  56. What is the difference between session and cookie ?
  57. How to pass java script array to jsp page?
  58. What is the difference betweeen JSP forward and servlet forward methods?
  59. Where can we find the compiled file of jsp in the directory struture.
  60. How we abort jsp page from a servlet
  61. What is difference between getAttribute() and getParameter()?
  62. What is the diff. b/w PAGE,APPLICATION and SESSION implicit objects of JSP?
  63. Wat is the difference between and in jsp..wen translate into servlet..wer it is stored in servlet..can we create global variables in jsp..if yes then how??
  64. How can i restrict the user from Clicking of Back button in any browser
  65. In one class i stored the key and values in the hashmap.so using key value i have to check wheter the value for key is correct or not.so how to retreive the key and values in jsp page
  66. What is the differnce between application server and web server
  67. What is use of implict Objects?why the container is given those one?
  68. How to delete cookies in JSP?
  69. In Oracle table some fields are "null".By default it will show as "null" in JSP page text box.But i dont want that. I want as blank textbox.What i can do for that?
  70. In Internet explorer if we give a jsp , How the server will know it has to execute?
  71. How the jsp changes will be effected in servlet file after converting?
  72. When to use struts technology? What type of applications are developed using struts frame work?
  73. What is the need of taglibraries?
  74. Explain online banking system using java.that means i need architecture of online banking system.please sir i want full details
  75. Text in textarea cant be copy by anyone while it is running in the browser (i.e,the text cant be copy and then paste on the other page) give me suggestion?
  76. How can i clear values in sessions. if i open a jsp page it is containing previous values. then i need to open a new page then only i am getting a fresh page
  77. What data is stored in the variable appname when we give the folowing statement String appname=("manager".equalsIgnoreCAse(request.getContextPath()))?"/manager":"/portal";
  78. Web browser concept using jsp
  79. Why we can't implement interface in JSP? Why we can only extend classes in JSP?
  80. How can we implement logoutpage using jsp ..? and Is there any method to force the browser to show the same page again and again after logout..?
  81. How to Upload a textfile from JSP to Servlet
  82. My html form contains an INPUT "text" element that accepts Date, i want to catch that date and want to query it using JSP? In short, how can i use that HTML form element with Prepared Statements in JSP?
  83. Types of indexing used in oracle applications ? and when and how we decide to implement indexing to database ?
  84. What is the need of implicit objects?
  85. When we design some login form how we manage security for those forms?which technology used for that purpose?
  86. How Do you implement interface in JSP?
  87. How can initialize interface in JSP?
  88. How do u maintain a Session?
  89. What is the differences between JSP LifeCycle and Servlet LifeCycle?
  90. Can I call an interface in a JSP?
  91. What is the Difference between sendRedirect() and Forward?
  92. I want to place two buttons one for save and one for delete.i am using DispatchAction as controller,how can i find which button i am pressing and how to diffrentiate?
  93. What is JSP
  94. What is the difference betweeen a statis and dynamic include?
  95. How can my JSP communicate with java class file
  96. I want to accomplish the following scenario: 1) user submits a jpg/gif file from an html form (using in the form, the user can browse to a file of their choice) 2) upload the jpg/gif file through a combination of Java and JSP's 3) put the jpg/gif into a database on a server and/or into a folder on my local system.
  97. How to pop up a jsp page?refreshing every two seconds.
  98. What is difference between scriptlet and expression
  99. What does < %= obj.getXXX() %> the following expression get evaluated to ?
  100. How can we move from one JSP page to another(mean using what tecnique?)

IBM Top C interview questions

  1. Difference between arrays and pointers?
  2. What is the purpose of realloc( )?
  3. What is static memory allocation and dynamic memory allocation?
  4. How are pointer variables initialized?
  5. Are pointers integers?
  6. What is a pointer variable?
  7. What is a pointer value and address?
  8. What is a method?
  9. What are the advantages of the functions?
  10. What is the purpose of main( ) function?
  11. What is an argument? differentiate between formal arguments and actual arguments?
  12. What is a function and built-in function?
  13. What is modular programming?
  14. When does the compiler not implicitly generate the address of the first element of an array?
  15. What are the characteristics of arrays in C?
  16. Differentiate between a linker and linkage?
  17. What are advantages and disadvantages of external storage class?
  18. Diffenentiate between an internal static and external static variable?
  19. What are the advantages of auto variables?
  20. What is storage class and what are storage variable?
  21. Which expression always return true? Which always return false?
  22. Write the equivalent expression for x%8?
  23. Why n++ executes faster than n+1?
  24. What is a modulus operator? What are the restrictions of a modulus operator?
  25. What is the difference between a string and an array?
  26. Is it better to use a pointer to navigate an array of values,or is it better to use a subscripted array name?
  27. Can the sizeof operator be used to tell the size of an array passed to a function?
  28. Is using exit() the same as using return?
  29. Is it possible to execute code even after the program exits the main() function?
  30. What is a static function?
  31. Why should I prototype a function?
  32. How do you print an address?
  33. Can math operations be performed on a void pointer?
  34. How can you determine the size of an allocated portion of memory?
  35. What is a "null pointer assignment" error? What are bus errors, memory faults, and core dumps?
  36. What is the difference between NULL and NUL?
  37. What is the heap?
  38. Can the size of an array be declared at runtime?
  39. What is the stack?
  40. When should a far pointer be used?
  41. What is the difference between far and near?
  42. Is it better to use malloc() or calloc()?
  43. Why should we assign NULL to the elements (pointer) after freeing them?
  44. When would you use a pointer to a function?
  45. How do you use a pointer to a function?
  46. Can you add pointers together? Why would you?
  47. What does it mean when a pointer is used in an if statement?
  48. Is NULL always defined as 0?
  49. What is a void pointer?
  50. What is a null pointer?
  51. How many levels of pointers can you have?
  52. What is indirection?
  53. How do you print only part of a string?
  54. How can I convert a string to a number?
  55. How can I convert a number to a string?
  56. What is the difference between a string copy (strcpy) and a memory copy (memcpy)? When should each be used?
  57. How can you check to see whether a symbol is defined?
  58. How do you override a defined macro?
  59. What is #line used for?
  60. What is a pragma?
  61. What are the standard predefined macros?
  62. How can type-insensitive macros be created?
  63. How many levels deep can include files be nested?
  64. Can include files be nested?
  65. Can you define which header file to include at compile time?
  66. What is the difference between #include and #include "file"?
  67. Is it better to use a macro or a function?
  68. How are portions of a program disabled in demo versions?
  69. What is the benefit of using an enum rather than a #define constant?
  70. What is the benefit of using #define to declare a constant?
  71. Can a file other than a .h file be included with #include?
  72. How can you avoid including a header more than once?
  73. What will the preprocessor do for a program?
  74. What is a macro, and how do you use it?
  75. What is Preprocessor?
  76. How can I make sure that my program is the only one accessing a file?
  77. How can I open a file so that other programs can update it at the same time?
  78. How do you determine whether to use a stream function or a low-level function?
  79. What is the difference between text and binary modes?
  80. How can you restore a redirected standard stream?
  81. How do you redirect a standard stream?
  82. How can I search for data in a linked list?
  83. How can I sort a linked list?
  84. What is hashing?
  85. What is the quickest searching method to use?
  86. What is the easiest searching method to use?
  87. How can I sort things that are too large to bring into memory?
  88. What is the quickest sorting method to use?
  89. What is the easiest sorting method to use?
  90. What is the benefit of using const for declaring constants?
  91. Can static variables be declared in a header file?
  92. What is the difference between declaring a variable and defining a variable?
  93. Is it acceptable to declare/define a variable in a C header?
  94. When should a type cast not be used?
  95. When should a type cast be used?
  96. How can you determine the maximum value that a numeric variable can hold?
  97. How reliable are floating-point comparisons?
  98. Can a variable be both const and volatile?
  99. When should the volatile modifier be used?

When should the register modifier be used? Does it really help?

IBM Test Paper

Technical part is easy we can finish in 20 mins.

Aptitude was tough

out of nearly 100 members, they shorlisted 35

candidates

for interview process.

I appiled thru some ad only i think, i didn't

remember properly

thru how i appiled for this.I am listing some

questions which

i remember. Tech part no need of preparation only,

just like that u can do.

1. In 1930 a man's age is the last 2 digit of the

year intercganged

in which he born and his granpa's age also like

the same.

2.10pow10pow10

if one takes 1 sec to write a single digit then

how long will it

take to write the above _expression.

3. 2 trains coming in opposite directions in 12

km/hr

distance between the trains is 24 km.

an insect starts at the same time when the train

starts at a

speed of 18km/hr. How many km the insect might

have travelled

before it got crashed between the 2 trains.

4. less than 30 of them are there. Among those

1/3rd know french

1/4th knows english, 1/2 knows german, then 1/8 of

them donn't know

any of the languages. Then find out how many are

there totally.

5. what will be the unit digit number od 7 pow 173

6. what is the probability that 2 of them selected

randomly have

got the same month of birth?

7. in c output of one prg. Very easy

8. parity bit for what?

9. if in a graph some nodes are there ....can we

tell it is bipartite.. (question on discrete)

10-14. One comprehension and 5 questions based on

that.

15. some 3 pairs of white socks, 4 pairs of red

socks and

2 pairs of black socks among that what is the

probability that

correct pairs can be taken out?

16. YWCC is what in options they had specified

for compiler...

a big hats off to chetana mam and suri sir for

maintaining such a wonderful group just to serve

people who are in search of job. Really thru this

group we are getting the chance to know the

current openings..

IBM PLACEMENT PAPERS NEW

1) I give a jcl code with

Programmer name: smith

Jobname:ABC

Jobclass=c

Message class = a

All messages are to be displaced code it in a JCL.

A) //ABC,smith,class=c,message class=a,message level=(2,1)

B) //ABC,smith,class=c,message class=a,message level =(!,1)

C) //ABC,smith,class=c,message class=a,message level=(0,1)

D) none of these.

2) for a cobol program

Move 5 to work-sd.

A statement which says that the value of work-st is 0.

perform Para1.

……………

Para1.

Add 3 to work-sd

Add 2 to work-st

If work-st <11 go to main-para.

………………

go to para1.

Wat wud b the value of work-sd?

a) 15

b) 18

c) 10

d) none

3) given 2 tables T1 and T2.

T1 T2

A 1

B 2

3

u make a query

SELECT * FROM T1,T2.

Wat is the no: of rows that are fetched frm this query?

a) 4

b) 5

c) 6

d) 9

4) wat is the full form of RACF?

5) who is the data base manager of db2?

a) buffer register

b) runtime suprivisor

c) DBRM

d) None

5)u have a file with DISP=SHR, when u open the file in output mode

a) the records get appended

b) the records gets overwritten

c) the job abbends

d) none of these

6) u open a file with disp= MOD, when u open the file in output mode

(same options as the above question)

7) to exclude some records while sorting which parameter do we use?

a) OMIT

b) EXCLUDE

c) ….d)….

8)when u insert into db2 with cics, it works as

a) foreground

b) a job working in background

c) ..

d) …..

9)u have a dataset TIME.WORK.OCT88, u want to concatenate other datasets

like TIME.WORK.JUL88, TIME.WORK.APR88, TIME.WORK.MAY88. how do u do that?

a)//DDname DD DSN = TIME.WORK.OCT88, DISP = SHR

DD DSN = TIME.WORK.JUL88, DISP = SHR

DD DSN = TIME.WORK.APR88, DISP = SHR

DD DSN = TIME.WORK.MAY88, DISP = SHR

b)//DDname DD DSN = TIME.WORK.JUL88, DISP = SHR

DD DSN = TIME.WORK.OCT88, DISP = SHR

DD DSN = TIME.WORK.APR88, DISP = SHR

DD DSN = TIME.WORK.MAY88, DISP = SHR

c)//DDname DD DSN = TIME.WORK.APR88, DISP = SHR

DD DSN = TIME.WORK.JUL88, DISP = SHR

DD DSN = TIME.WORK.MAY88, DISP = SHR

DD DSN = TIME.WORK.OCT88, DISP = SHR

e) none of these

10) when db2 entries are made while working in cics, the enteries

should be made in

a) TCT

b) PCT

c) DCT

d) RCT

11) find the odd one out

a) KSDS

b) RRDS

c) LDS

d) PDS

12) full form of VTOC

13) question based on SKIP and COUNT parameter

IBM PLACEMENTS JAVA

Question: Name the containers which uses Border Layout as their default layout?
Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog classes.
Question: What do you understand by
Synchronization?
Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized
multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption
.
E.g. Synchronizing a function:
public synchronized void Method1 () {
     // Appropriate method-related code. 
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
    synchronized (this) { 
            // Synchronized code here.
         }
}
Question: What is Collection API?
Answer: The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. 
Example of classes:
HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces:
Collection, Set, List and Map.

Question: Is Iterator a Class or Interface? What is its use?
Answer: Iterator is an interface which is used to step through the elements of a Collection. 
Question: What is similarities/difference between an Abstract class and Interface?
Answer:  Differences are as follows:

  • Interfaces provide a form of multiple inheritance. A class can extend only one other class.
  • Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
  • A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
  • Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. 

Similarities:

  • Neither Abstract classes or Interface can be instantiated.

Question: How to define an Abstract class?
Answer: A class containing abstract method is called Abstract class. An Abstract class can't be instantiated. 
Example of Abstract class:
abstract class testAbstractClass { 
    protected String myString; 
    public String getMyString() { 
        return myString; 
        } 
    public abstract string anyAbstractFunction();
}
     

Question: How to define an Interface?
Answer: In
Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Emaple of Interface:

public interface sampleInterface {
    public void functionOne();

    public long CONSTANT_ONE = 1000;
}
   

Question: Explain the user defined Exceptions?
Answer: User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
     // The class simply has to exist to be an exception
}
  

Question: Explain the new Features of JDBC 2.0 Core API?
Answer: The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional Package API, and provides inductrial-strength
database computing capabilities.
New Features in JDBC 2.0 Core API:

  • Scrollable result sets- using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position
  • JDBC 2.0 Core API provides the Batch Updates functionality to the java applications.
  • Java applications can now use the ResultSet.updateXXX methods.
  • New data types - interfaces mapping the SQL3 data types
  • Custom  mapping of user-defined types (UTDs)
  • Miscellaneous features, including performance hints, the use of character streams, full precision for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values. 

    
 

Question: Explain garbage collection?
Answer: Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), 
JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. 
   

Question: How you can force the garbage collection?
Answer: Garbage collection automatic process and can't be forced.  
 

Question: What is OOPS?
Answer: OOP is the common abbreviation for Object-Oriented Programming.  
 

Question: Describe the principles of OOPS.
Answer: There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.  
 

Question: Explain the Encapsulation principle.
Answer: Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.  
 

Question: Explain the Inheritance principle.
Answer: Inheritance is the process by which one object acquires the properties of another object.  
 

Question: Explain the Polymorphism principle.
Answer: The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".  
 

Question: Explain the different forms of Polymorphism.
Answer: From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:

  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface

  
 

Question: What are Access Specifiers available in Java?
Answer: Access specifiers are keywords that determines the type of access to the member of a class. These are:

  • Public
  • Protected
  • Private
  • Defaults

  
 

Question: Describe the wrapper classes in Java.
Answer: Wrapper class is wrapper around a primitive
data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive

Wrapper

boolean

  java.lang.Boolean

byte

  java.lang.Byte

char

  java.lang.Character

double

  java.lang.Double

float

  java.lang.Float

int

  java.lang.Integer

long

  java.lang.Long

short

  java.lang.Short

void

  java.lang.Void

  
 

Question: Read the following program:

public class test {
public static void main(String [] args) {
    int x = 3;
    int y = 1;
   if (x = y)
    
System.out.println("Not equal");
  else
    System.out.println("Equal");
 }
}

What is the result?
   A. The output is "Equal"
   B. The output in "Not Equal"
   C. An error at " if (x = y)" causes compilation to fall.
   D. The program executes but no output is show on console.
Answer: C

Question:
what is the class variables ?
Answer: When we create a number of objects of the same class, then each object will share a common copy of variables. That means that there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class, but mind it that it should be declared outside outside a class. These variables are stored in static memory. Class variables are mostly used for constants, variable that never change its
initial value. Static variables are always called by the class name. This variable is created when the program starts i.e. it is created before the instance is created of class by using new operator and gets destroyed when the programs stops. The scope of the class variable is same a instance variable. The class variable can be defined anywhere at class level with the keyword static. It initial value is same as instance variable. When the class variable is defined as int then it's initial value is by default zero, when declared boolean its default value is false and null for object references. Class variables are associated with the class, rather than with any object. 

Question: What is the difference between the instanceof and getclass, these two are same or not ?
Answer: instanceof is a operator, not a function while getClass is a method of java.lang.Object class. Consider a condition where we use 
if(o.getClass().getName().equals("java.lang.Math")){ }
This method only checks if the classname we have passed is equal to java.lang.Math. The class java.lang.Math is loaded by the bootstrap ClassLoader. This class is an abstract class.This class loader is responsible for loading classes. Every Class object contains a reference to the ClassLoader that defines. getClass()
method returns the runtime class of an object. It fetches the java instance of the given fully qualified type name. The code we have written is not necessary, because we should not compare getClass.getName(). The reason behind it is that if the two different class loaders load the same class but for the JVM, it will consider both classes as different classes so, we can't compare their names. It can only gives the implementing class but can't compare a interface, but instanceof operator can. 
The instanceof operator compares an object to a specified type. We can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. We should try to use instanceof operator in place of getClass() method. Remember instanceof opeator and getClass are not same. Try this example, it will help you to better understand the difference between the two. 
Interface one{
}

Class Two implements one {
}
Class Three implements one {
}

public class Test {
public static void main(String args[]) {
one test1 = new Two();
one test2 = new Three();
System.out.println(test1 instanceof one); //true
System.out.println(test2 instanceof one); //true
System.out.println(Test.getClass().equals(test2.getClass())); //false
}

IBM Placements For Freshers

Combinations

Posted: Tue, 27 Nov 2007 08:20:24 -0600

Question:Computing the exact number of ways that N things can be taken M at a time can be a great challenge when N and/or M become very large.So given 5<=N<=100 5<=M<=100 and M<=N.Compute the EXACT value of: N!/(M!*(N-M)!) The final value of C will fit in a 32-bit Pascal LongInt or a C long. So deduce an approach based on this assumption given.

Solution:At a mere glance,this problem may seem to have a direct solution,though it isn't upon a long thought.The naive approach to calculate combination of N things taken M at a time is obtained by mere application of formula,which mean finding N! ,M! and (N-M)! and the putting them in the expression.But as N and M are independently large enough for overflows to occur in N! and M! calculations.
One of the approaches to solve this problem,based on prime factorization can be formulated in the following manner.

Consider a prime P whose exponents in N!,M! and (N-M)! are p1,p2 and p3 respectively.

therefore the exponent of P in N!/M!*(N-M)! is p1+p2-p3.

This way we can store the exponents of all primes <= the largest prime which divides N.

One this is done ,we can merely multiply all these primes each raised to its exponent to get the required answer.


Now getting on to the tricky part of finding the exponent of a prime P in N!

In general ,if P is any prime,then the no of P's in N! is given by
Sum (floor(n/P^i)) for P^i <= N This apparently weird formula can be explained with ease!! consider the numbers 1,2,3,.........,,N.Every Pth number is divisible by P.So all those multiples of P put together contribute floor(N/P) to the power of P. Similarly every P^2th number is divisible by P^2.And each of them have already contributed 1 to power of P in previous iteration,as each of them are divisible by P.So each of them contribute an additional 1, which means they all together contribute floor(N/P^2) to the already sum. These terms of contribution go on till we have P^i <= N,hence the summation Sum (floor(N/P^i)) for P^i <= N The Cpp implementation of above task is given below


#include<iostream>
using namespace std;
#include<cmath>
#include<cstdlib>
#include<cstdio>
#include<vector>
typedef vector<int> powers;
void insert(vector<powers> &P,int i,vector<int> V,int size)
{
vector<int> temp=P[i-1];
//calculation of exponent of each prime
for(int j=0;j <size && i!=1;j++)
{
while(i%V[j]==0)
{
temp[j]++;
i/=V[j];
}
}
P.push_back(temp);
}
int main()
{
vector<int> V;
vector<powers> P;
V.push_back(2);
bool flag;
int N,R;
for(int i=3;i<100;i+=2)
{
flag=true;
for(int j=0;V[j]*V[j] <=i;j++)
{
if(i%V[j]==0)
{
flag=false;
break;
}
}
if(flag)
{
V.push_back(i);
}
}
int size=V.size();
vector<int> temp(size,0);
P.push_back(temp);
P.push_back(temp);
for(int i=2;i<=100;i++)
{
insert(P,i,V,size);
}
while(cin >> N >>R)
{
if(N==0 && R==0)
{
return(0);
}
else
{
long sol=1;
for(int i=0;i<size;i++)
{

sol*=(long)pow((double)V[i],P[N][i]-P[R][i]
-P[N-R][i]); //Pi^(p1-p2-p3)
}
cout<<N<<" things taken
"<<R<<" at a time is
"<<sol<<" exactly."<<'\n';


}

}
return(0);
}

Solutions to Logical Puzzles-2

1)3
It is of the form 0^2+2,1^2+2,3^2+2,6^2+2,10^2+2,.....
The sequence of n is 0,1,3,6,10,... so the next n is 15 => 15^2+2

2)2
The function is S(n)=S(n-1)*(n+2) + 3 ,n>1
=6 ,n=1
3)1
It is of the form S(n)*3+2 for even and S(n)*2-3 for odd where S(n) is the nth element.
So 7th element = 239*2-3=475
4)2
The function is S(n)=(n+2)^3 -2
5)1
The numbers in the sequence is a combination of n^2 and n^3 and n is odd.
6)2
The function is S(n)=S(n-1)*n-n n>1
=3 n=1
7)
8)1
The function is S(n)=(S(n-1)-1)*(n-1) n>1
=8 n=1
9)
10)

  • Number of ways to express a number as summation of consecutive numbers

    Posted: Tue, 27 Nov 2007 09:54:40 -0600

    Question.All the positive numbers can be expressed as a sum of one, two or more consecutive positive integers. For example 9 can be expressed in three such ways, 2+3+4, 4+5 or 9. Given an integer ,you will have to determine in how many ways that number can be expressed as summation of consecutive numbers.

    Solution:
    2+3+4=(1+2+3+4)-(1)
    =(1+2+3+4+5)-(1+2+3)
    =(1+2+3+4+5+6+7+8+9)-(1+2+3+4+5+6+7+8)

    This shows that the no of solutions to this problem is the no of tuples (n,m) such that
    given number K can be expressed as K=(1+2+..........+n)-(1+2+3+...........+m)
    and n > m

    i.e K=n*(n+1)/2 -m*(m+1)/2
    =(n-m)(n+m+1)/2
    2*k=(n-m)*(n+m+1)
    If we put the factor n-m=p and (n+m+1)=q,we get S=2*k=p*q
    As p+q=2*n+1 is odd and S is even either n-m is odd otherwise n+m+1 is odd.
    This leaves out with finding out the no of odd divisors of S,which can be easily done using prime factorization.
    if S=(2^p)*(3^q)*(5^r)*(7^s)......

    then the solution is (q+1)*(r+1)*(s+1)*.. i.e the no

IBM PLACEMENTS PAPERS LATEST


Basic Questions

* What is a friend, and why do you need it?
* If this doesn't compile, why didn't it (or will it compile?) Don't show comments, which explain the problem.


template void HashTable <>::dummy()
{
K* k = NULL;
Hashable* h = k; // If this fails to compile, it's because
// K is not derived from Hashable.
}

* This will loop forever. Why? Will it really loop forever? (Answer: Base:func() does not call Base::func(). Base: is just a label, so the line always will call Derived::func() until it runs out of stack space)


class Base {
public:
Base() {}
virtual void func() { /* do something */ }
};


 


class Derived : public Base {
public:
Derived() {}
virtual void func()
{
Base:func();
/* do something else */
}
};

main()
{
Derived d;
d.func(); // Never returns!
}



More advanced questions:

* What is a vtbl ?
* What is RTTI and why do you need it?
* How do I specialize a template? Give an example.

To separate sheep from goats (for those claiming C++ Guru status):

* What is a partial template? Why would you use one?
* How to I create a binary functor in the STL?

Given the following code:


class A;
class B;

class C {
A* a_;
B* b_;

public:
};


Implement a copy constructor and assignment operator for C. A sample solution is something like:


class C {
A* a_;
B* b_;

void swap(C& rhs) { rhs.a_ = a_; rhs.b_ = b_; }

public:

C(const C& rhs) {
auto_ptr<> a(new A(rhs.a_));
auto_ptr<> b(new B(rhs.b_)):

delete a_;
delete b_;

a_ = a.release();
b_ = b.release();
}

C& operator=(const C& rhs) {
C temp(rhs);
temp.swap(*this);
return *this;
}
};



What is wrong with this class, assuming that this is its complete interface?



class C {
char *p;
public:
C() { p = new char[64]; strcpy(p, "Hello world"); }
~C() { delete p; }

void foo() { cout << "My ptr is: '" << p << "'" << endl; }
};


Since this has an overtly programmed destructor, the member wise semantics for destruction are not good enough; therefore, they are not good enough for copy and assignment either. But, the copy ctor and op= are not programmed, so we will have some serious trouble.

Gradual hinting: what happens when we make a copy? [correct answer: pointer is copied]. Now, the original goes out of scope, what happens to the copy? [pointer dangles]. How would you fix it?

[also, that delete p should be delete[ p since p was allocated with the array new]

Assuming that swap() and copy construction are part of your interface for class C, what's the cookie-cutter pattern for operator= that uses them?

answer:


C& C::operator=(const C &rhs) {
if (this != &rhs) {
C tmp(rhs);
this->swap(tmp);
}
return *this;
}
Solutions to Logical Puzzles-3

2)3,
The number obtained by dividing 48 with 4 is 12 which is even while all the others get odd number for the same.
3)4,
The sequence has to be AON,EWR,IEV,MMZ

4)2
The remaining 3 are input devices.

5)2
The remaining 3 represent an image.

6)3
Trousers can only take a plural form while others can also take a singular form.

7)

8)

9)4
All the other three lie inside a cell.

10)

11)4

12)3

13)1

14)2

15)3

16)3

17)1

18)3

19)3

20)4

  • Solutions to Logical Puzzles-1
    We need 3 cuts to cut a cube into 6 equal pieces,with one cut in each dimension.Maximum identical pieces obtained with n cuts[if n is a factor of 3] = (n/3 + 1)^3, with n/3 cuts, we form n/3 + 1 equal pieces.If we need to get maximum number of identical cubes with some number of cuts then the number of cuts in all the dimensions should be equal if possible or almost equal.
    The number of identical pieces formed with l,n,m cuts in the 3 demensions are (l+1)*(n+1)*(m+1).

    1)3,Here there are 6,7,8 cuts in each dimension

    2)2

    3)4,Here the number of cuts are 7,7,6 in the 3 dimensions.

    4)1

    5)3

    All the problems from 6-18 are based mostly on imagination.Note that 27 identical pieces have no color at all i.e they are inner pieces.

    6)3

    7)4

    8)1

    9)3

    10)2

    11)2

    12)4

    13)1

    14)4

    15)3

    16)1

    17)4

    18)1

    19)2

    20)4
  • Solutions to Basic C Interview Questions

    1)To check for it, create two pointers,and set each to the start of the list. Update each as follows:

    while (pointer1) {
    pointer1 = pointer1->next;
    pointer2 = pointer2->next;
    if (pointer2) pointer2=pointer2->next;
    if (pointer1 == pointer2) {
    print ("circular linked list\n");
    }
    }

    2)Union x : 1101791232 21.500000
    Union y : 100 d 0.000000

    3)It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object.

    4) Java,Smalltalk,Eiffel,Sather.

    5)A container class is a class that is used to hold objects in memory or
    external storage. A container class acts as a generic holder. A
    container class has a predefined behavior and a well-known interface. A
    container class is a supporting class whose purpose is to hide the
    topology used for maintaining the list of objects in memory. When a
    container class contains a group of mixed objects, the container is
    called a heterogeneous container; when the container is holding a group
    of objects that are all the same, the container is called a homogeneous
    container.

    6)fffffff0

    7)C was the C++ predecessor. As it's name implies, a lot of C remains in C++. Although not actually being more powerful than C, C++ allows the programmer to more easily manage and operate with Objects, using an OOP (Object Oriented Programming) concept.

    C++ allows the programmer to create classes, which are somewhat similar to C structures. However, to a class can be assigned methods, functions associated to it, of various prototypes, which can access and operate within the class, somewhat like C functions often operate on a supplied handler pointer.

    Although it is possible to implement anything which C++ could implement in C, C++ aids to standarize a way in which objects are created and managed, whereas the C programmer who implements the same system has a lot of liberty on how to actually implement the internals, and style among programmers will vary a lot on the design choices made.

    In C, some will prefer the handler-type, where a main function initializes a handler, and that handler can be supplied to other functions of the library as an object to operate on/through. Others will even want to have that handler link all the related function pointers within it which then must be called using a convention closer to C++.

    To finish this discussion, C++ applications are generally slower at runtime, and are much slower to compile than C programs. The low-level infrastructure for C++ binary execution is also larger. For these reasons C is always commonly used even if C++ has alot of popularity, and will probably continue to be used in projects where size and speed are primary concerns, and portable code still required (assembly would be unsuitable then).

    8)Incomplete types
    refers to pointers in which there is non availability of the
    implementation of the referenced location or it points to some location
    whose value is not available for modification.

    int *i=0x400 // i points to address 400
    *i=0; //set the value of memory location pointed by i.

    9)Printf : Call by value
    Scanf : Call by reference

    10)a const pointer means the pointer which represents the address of one value. so if you declare a pointer inside the function, it doesn't have scope outside the function. if it is also available to the outside function whenever we declare a pointer as const.

    11)Type casting must be done wheneever the data type of the variable to which u r gonna assign some values is diff from the data type of the variable on the right side.

    for instance;

    float f;
    int i = 10 , j = 5 ;

    f = (float) ( i / j ) ;

    f -------> left side variable.
    i -------> right side variable.

    but always make sure that the size of the var on the left is greater than that of the right. else there will be data loss.

    A type cast should not be used to override a const or volatile declaration. Overriding these type modifiers can cause the program to fail to run correctly.
    A type cast should not be used to turn a pointer to one type of structure or data type into another. In the
    rare events in which this action is beneficial, using a union to hold the values makes the programmer.s
    intentions clearer.

    12)he 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));

    13)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.

    14)Both the merge sort and the radix sort are good sorting algorithms to use for linked lists.

    15)The preprocessor is used to modify your program according to the preprocessor directives in your source code. Preprocessor directives (such as #define) give the preprocessor specific instructions on how to modify your source code. 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.
    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.

    16)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.
    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.

    17)
    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
    itoa() 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.

    18)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.

    19)n++ takes more than one instruction, ++n is faster. n++ has to store n, increment the variable and return n, while ++n increment n and return without storing the previous value of n.

    20) 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.

    21)expression if (a=0) always return false
    expression if (a=1) always return true

    22)Malloc is dynamic memory allocation,it allocates the memory and initialize garbage value.Calloc is similar to malloc but only difference is initialize zero

    23)A middle level language

    24)Overloading is polymorphism which is one of the characteristics of Object oriented programming. C is not and object oriented language like C++ or Java. Therefore, no overloading, inheritance, etc.

    25)Static int variable are accessed only inside the file where it is defined. Thus we can have same variable name in 2 files if the variable is defined as static. The scope of the variable is limited to the file in which it is defined.

    On the other hand if the variable is not defined as static and defined globally then it can be accessed across the files. To access the variable which is global variable and declared and defined in file A, keyword "extern" is used in front of the variable in file B. This indicated to compiler while compiling that the variable is defined in some other file other than B and continues compiling and while linking the variable it search for the actual definition and links.


IBM PLACEMENTS C PAPERS

C program to delete a tree

Write a C program to delete a tree(i.e, free up its nodes)

#include<stdio.h>
struct binarysearchtree
{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;

void tree_free(tree T)
{
if (T==NULL)
return;
else
{
tree_free(T->left);
tree_free(T->right);
free(T);
}
}

Question:Write a C program to determine the number of elements(or size) in a binary tree?
Solution:


#include<stdio.h>
struct binarysearchtree
{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;


int tree_size(tree T)
{
if(T==NULL)
return 0;
else
{
return 1+tree_size(T->left)+tree_size(T->right);
}
}


 

chtree
{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;

int max(int a,int b)
{
if(a >=b)
return a;
else
return b;
}

int height(tree T)
{
if(T==NULL)
return 0;
else
{
int h1=height(T->left);
int h2=height(T->right);
return 1+max(h1,h2);
}
}


Hi Friends,
One of my friend who is working for amazon gave me a good collection of questions which helped him to get into Amazon. I am sharing these questions to help you guys.


 

  • What are the major differences between C and C++?
  • What are the differences between new and malloc?
  • What is the difference between delete and delete[?
  • What are the differences between a struct in C and in C++?
  • What are the advantages/disadvantages of using #define?
  • What are the advantages/disadvantages of using inline and const?
  • What is the difference between a pointer and a reference?
  • When would you use a pointer? A reference?
  • What does it mean to take the address of a reference?
  • What does it mean to declare a function or variable as static?
  • What is the order of initialization for data?
  • What is name mangling/name decoration?
  • What kind of problems does name mangling cause?
  • How do you work around them?
  • What is a class?
  • What are the differences between a struct and a class in C++?
  • What is the difference between public, private, protected, and friend access?
  • For class CFoo { }; what default methods will the compiler generate for you>?
  • How can you force the compiler to not generate them?
  • What is the purpose of a constructor? Destructor?
  • What is a constructor initializer list?
  • When must you use a constructor initializer list?
  • What is a:
    * Constructor?
    * Destructor?
    * Default constructor?
    * Copy constructor?
    * Conversion constructor?
  • What does it mean to declare a...

    * member function as virtual?
    * member function as static?
    * member variable as static?
    * destructor as static?
  • Can you explain the term "resource acquisition is initialization?"
  • What is a "pure virtual" member function?
  • What is the difference between public, private, and protected inheritance?
  • What is virtual inheritance?
  • What is placement new?
  • What is the difference between operator new and the new operator?
  • What is exception handling?
  • Explain what happens when an exception is thrown in C++.
  • What happens if an exception is not caught?
  • What happens if an exception is throws from an object's constructor?
  • What happens if an exception is throws from an object's destructor?
  • What are the costs and benefits of using exceptions?
  • When would you choose to return an error code rather than throw an exception?
  • What is a template?
  • What is partial specialization or template specialization?
  • How can you force instantiation of a template?
  • What is an iterator?
  • What is an algorithm (in terms of the STL/C++ standard library)?
  • What is std::auto_ptr?
  • What is wrong with this statement?
    std::auto_ptr ptr(new char[10]);
  • It is possible to build a C++ compiler on top of a C compiler. How would you do this?