Showing posts with label Basic interview questions. Show all posts
Showing posts with label Basic interview questions. Show all posts

How do you find the duplicated number in Array

Q.An array contains n numbers ranging from 0 to n-2. There is exactly one number duplicated in the array. How do you find the duplicated number? For example, if an array with length 5 contains numbers {0, 2, 1, 3, 2}, the duplicated number is 2. 

A.Suppose that the duplicated number in the array is m. The sum of all numbers in the array, denoted as sum1, should be the result of 0+1+...+(n-2)+m. It is not difficult to get the sum result of 0+1+...+(n-2), which is denoted as sum2. The duplicated number m is the difference between sum1 and sum2. The corresponding code in Java is shown in Listing 3-2.
Listing 3-2. Java Code to Get a Duplicated Number in an Array
int duplicate(int numbers[]) {
    int length = numbers.length;
    int sum1 = 0;
    for(int i = 0; i < length; ++i) {
        if(numbers[i] < 0 || numbers[i] > length - 2)
            throw new IllegalArgumentException("Invalid numbers.");
        sum1 += numbers[i];
}
    int sum2 = ((length - 1) * (length - 2)) >> 1;
    return sum1 - sum2;
}

Test Cases:
  • Normal case: an array with size n has a duplication
  • Boundary case: an array {0, 0} with size 2
  • Some numbers are out of the range of 0 to n-2 in an array of size


    Q. An array contains n numbers ranging from 0 to n-1. There are some numbers duplicated in the array. It is not clear how many numbers are duplicated or how many times a number gets duplicated. How do you find a duplicated number in the array? For example, if an array of length 7 contains the numbers {2, 3, 1, 0, 2, 5, 3}, the implemented function (or method) should return either 2 or 3.
    A.
    A naive solution for this problem is to sort the input array because it is easy to find duplication in a sorted array. As we know, it costs O(nlogn) time to sort an array with n elements. Another solution is the utilization of a hash set. All numbers in the input array are scanned sequentially. When a number is scanned, we check whether it is already in the hash set. If it is, it is a duplicated number. Otherwise, it is inserted into the set. The data structure HashSet in Java is quite helpful in solving this problem. Even though this solution is simple and intuitive, it has costs: O(n) auxiliary memory to accommodate a hash set. Let’s explore a better solution that only needs O(1) memory. Indexes in an array with length n are in the range 0 to n-1. If there were no duplication in the n numbers ranging from 0 to n-1, we could rearrange them in sorted order, locating the number i as the ith number. Since there are duplicate numbers in the array, some locations are occupied by multiple numbers, but some locations are vacant. Now let’s rearrange the input array. All numbers are scanned one by one. When the ith number is visited, first it checks whether the value (denoted as m) is equal to i. If it is, we continue to scan the next number. Otherwise, we compare it with the mth number. If the ith number equals the mth number, duplication has been found. If not, we locate the number m in its correct place, swapping it with the mth number. We continue to scan, compare, and swap until a duplicated number is found. Take the array {2, 3, 1, 0, 2, 5, 3} as an example. The first number 2 does not equal its index 0, so it is swapped with the number with index 2. The array becomes {1, 3, 2, 0, 2, 5, 3}. The first number after swapping is 1, which does not equal its index 0, so two elements in the array are swapped again and the array becomes {3, 1, 2, 0, 2, 5, 3}. It continues to swap since the first number is still not 0. The array is {0, 1, 2, 3, 2, 5, 3} after swapping the first number and the number with index 3. Finally, the first number becomes 0.
Let’s move on to scan the next numbers. Because the following three numbers, 1, 2 and 3, are all
equal to their indexes, no swaps are necessary for them. The following number, 2, is not the same as its
index, so we check whether it is the same as the number with index 2. Duplication is found since the
number with index 2 is also 2.
 With an understanding of the detailed step-by-step analysis, it is time to implement code. Sample
code in Java is shown in Listing 3-3.
Listing 3-3. Java Code to Get a Duplicated Number in an Array
int duplicate(int numbers[]) {
    int length = numbers.length;
    for(int i = 0; i < length; ++i) {
        if(numbers[i] < 0 || numbers[i] > length - 1)
            throw new IllegalArgumentException("Invalid numbers.");
}
    for(int i = 0; i < length; ++i) {
        while(numbers[i] != i) {
            if(numbers[i] == numbers[numbers[i]]) {
                return numbers[i];
}
            // swap numbers[i] and numbers[numbers[i]]
            int temp = numbers[i];
            numbers[i] = numbers[temp];
            numbers[temp] = temp;
} }
    throw new IllegalArgumentException("No duplications.");
}

Test Cases:
  • Normal cases: an array with size n has one or more duplicated numbers
  • Boundary cases: the array {0, 0} with size 2
  • Some numbers are out of the range from 0 to n-1 in an array of size n
  • No duplication in the array
www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

Time and Space Efficiency

Outstanding developers pay a lot of attention to time and space consumption and have the passion needed to continue improving performance of their own code. When there are multiple solutions for a problem, interviewers always expect the best one. If interviewers point out that there are better solutions, candidates should try their best to find approaches to improving time and space performance, demonstrating his or her enthusiasm to pursue excellence, which is an essential spirit to have as an outstanding developer.
The first thing candidates should understand is how to analyze time and space efficiencies. Various implementations of the same algorithm may result in dramatic performance distinctions, so it is important to analyze performance of an algorithm and its implementation. Take the calculation of the Fibonacci Sequence as an example. The classical solution is based on the recursive equation f(n) = f(n-1) + f(n-2). It is not difficult to find out the time complexity increases exponentially since there are lots of duplicated calculations. However, the complexity will reduce to O(n) if it is calculated iteratively. First of all, f(1) and f(2) are calculated, and then f(3) is based on f(1) and f(2); f(4) is get based on f(2) and f(3). The sequence continues until f(n) is calculated in a loop. Please refer to the section Fibonacci Sequence for more details.
Candidates have to master pros and cons of each data structure and be able to choose the most suitable one to improve performance. For example, it seems that multiple types of data structures are available to get the median of a stream, including arrays, lists, balanced binary trees, and heaps. After analyzing the characteristics of each data type, we find that the best choice is to utilize two heaps—a maximal heap and a minimal heap (section Median in Stream).
Candidates should also be proficient in common algorithms. The most popular algorithms in interviews are about search and sort. It costs O(n) time to scan an array sequentially. However, it is reduced to O(logn) with the binary search algorithm if an array is sorted. The problem “Maximal Number in a Unimodal Array” and “Times of Occurrences in a Sorted Array”are both solved based on the binary search algorithm. The quicksort algorithm is widely used for other problems besides sorting. The Partition function in quicksort can be used to get the kth maximal number out of n numbers and solve the problem “Majority in an Array”and “Minimal k Numbers”.
www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

Cover Letters


What is the Cover Letter?
Most people hate writing a cover letter even more than they hate preparing a resume! I recently worked with a job seeker who said that he refused to apply for any graduate roles that required a cover letter to accompany the application. This is was what I liked to call a “resume bomber” – someone whose aim is to apply to as many jobs as possible and just “hope for the best”. Unfortunately, he quickly realized that most companies not only require a cover letter, but demand a cover letter. If a hiring manager sees that a cover letter is missing from the job application, it is more than likely that the resume will be deleted immediately.
From the viewpoint of a hiring manager – if the candidate cannot follow basic instructions in applying for a job, how can they be trusted to perform the job?
Before we begin to go through the importance of the cover letter, it is important to define exactly what the cover letter is and what purpose it serves.
The cover letter is an introductory letter to accompany the resume or curriculum vitae. The cover letter is not a job application, nor should it be a part of the resume or follow the conclusion of the resume. 

In the competitive job environment where first impressions count and the time we have to impress the potential reader is becoming shorter and shorter, the most effective way to ensure that your application stands out from the competition is through a professionally written cover letter. There is, however, a fine line between a cover letter that enhances your application and a cover letter that can actually do you a disservice.
Top 3 Tips to Cover Letter Writing:
First impressions:
You may have the greatest personality and the exact skills required for a particular job, but without a compelling cover letter that attracts the reader’s attention immediately you will never get the opportunity to prove that you are the perfect candidate. Establish your reason for applying to the role within the first couple of sentences. As a graduate you need to establish your “brand” and make it clear to the reader that you have unique attributes that make you the perfect person for the job.
Target your cover letter:
A “one size fits all” approach to job seeking does not work. There is no quick fix to getting a new job and a generic cover letter will be spotted from a mile away! The key to cover letter writing is to individualize the cover letter to the reader and make sure that they know that your letter has been written for their specific job. A targeted cover letter can help open doors and portray that professional image.
Forget the Clichés!
I can’t stand clichés! It’s my number one pet hate. When I read through a cover letter, I want the person’s personality to shine. The last thing I want to read is a cliché. As the hiring manager, I want to feel that what I am reading is a truthful assessment as opposed to statements that do not add any value to the person’s application.
The final point to remember...
If you are serious about your job search, you need to get serious about preparing a targeted cover letter to compliment your resume. As mentioned above, first impressions rule and to ensure that your resume is given a chance, you need your cover letter to shine. In the ultra-competitive job environment, hiring managers are looking for any excuse to delete a candidate’s application. Do not let yourself down by failing at the very first step.
 
Advantages to Preparing a Targeted Cover Letter
Preparing a highly targeted and personalized cover letter and you are already on your way to a brand new job. Obviously, you will need a professionally written resume also! By impressing the reader (hiring professional) and they will enthusiastically move onto your resume. Disappoint the reader and your resume will be deleted.
Will a perfectly written cover letter ensure that you get the job? Of course not. However, a poorly written cover letter will guarantee that your application will not get the attention that is needed to be one of the top candidates. In the current job market there are three areas of your cover letter that you need to pay special attention to: 

Target the employer’s needs:
Too many times, we write our cover letter and resume from our point of view. From the perspective of the hiring manager they want to know that you have the skills to do the job you are applying for. If the employer is looking for a candidate who is going to need to travel and spend time outside of the office then you need to emphasize that travelling is something you are willing to do (and enjoy). If you do not feel that the job is right for you, then the easy solution is not to apply for the job. However, if you do decide to apply for a certain role then target the needs of the employer and the skills that they require from the perfect candidate.
Don’t be afraid to emphasize your previous achievements:
When applying for a job you need to prove that you are the best candidate. The only way to do this is by highlighting your achievements and all those skills that make you both unique and special. Try to establish yourself as an expert. Remember that in order to stand out, you need to be in the top 5-10% of all the candidates applying for the role. While no one likes arrogance, employers DO want to see examples of your achievements that would make you the right person for the job.
Provide examples how you will add value to the organization:
If you don’t believe that you have the skills to add value to the particular organization then why is the hiring manager going to hire you? It is not enough anymore just to present your skills and achievements but you need to prove to the reader that you are capable of adding value to the role and to the whole organization. Providing examples of the added value expertise that you can offer should be highlighted in your cover letter to help differentiate your application as compared to others. 

Your Cover Letter is Just as Important as Your Resume!
Unless you are being recruited by a family member, friend, or close acquaintance, every single hiring manager will want to look at your resume before they call you in for an interview.
I cannot stress enough how important it is to have a cover letter accompany your resume EVERY SINGLE TIME you send it in and to make sure that it’s tailored specifically to the job you’re applying for.
Think about it from a hiring manager’s point of view. They can receive hundreds of applications for a single job position that they need to fill in just a short amount of time. On top of their regular job duties, they need to sift through all of the applications and find the top 5% to call in for an interview. It’s just not possible for them to look at every single person’s application. So what do they do? They narrow down the field by using the easiest and fastest tool they have – first impressions.
Let’s relate this to a different topic – sports. You’re a coach and need to “recruit” the best players possible for your team...
You’re coaching a soccer team and need to pick 15 members for your squad out of a potential 100 and you only have 2 hours to do so. It’s impossible to take a good look at every single player’s skills in only 2 hours, so you need to quickly narrow your search before you can study the players further. In order to do so, and without knowing anything about the players, you’re going to rely on your first impressions to make the first cut. 

Take a look at the players standing before you – are they all wearing proper soccer attire and equipment? Do they look excited and enthusiastic about being here? Think about it – if there’s someone dressed in a soccer uniform and cleats and another one wearing jeans, a t-shirt, and sandals, one of them definitely appears to be more interested in joining your team than the other. Building on that, and only considering first impressions, one looks a lot more capable than the other. While there may be a hundred explanations for this difference, it really doesn’t matter when you have a limited amount of time – the ones who don’t look interested are not going to make the first cut.
Consider the above situation and think about it from a hiring manager’s point of view. You have 50 applications before you and you need to call 5 people in for an interview. You have a limited amount of time to decide, so you need to eliminate some applications quickly. What can we see without even reading the details of each application? Some have cover letters along with the resume and some do not. The applications without cover letters are a little bit like the people showing up to soccer tryouts with jeans and no equipment. They make a terrible first impression – they don’t appear as interested as the other ones, so why should anyone bother with them?
Applications without cover letters are always the first ones discarded. The presence of a cover letter shows a genuine interest in a job position because you actually took the time to write it. The current economic climate is not exactly one that is overflowing with jobs; it’s not like companies are hiring for the sake of it. Make sure you show a hiring manager that you have taken the time to merely write a letter to show your interest in their job position. If you don’t bother showing an interest in them, the hiring manager will have no interest in you. 

Secret Cover Letter Tips
It’s no secret that the job application process has changed significantly in the past 10 years. Applicants used to send hard copies of their resumes and cover letters to hiring managers via email or fax, but most jobs today are posted online and applications are sent to hiring managers via email.
Applications still consist of cover letters, but the format of cover letters has changed a little bit in the online revolution. Cover letters used to be written in a standard letter format, and while this standard format is still widely accepted today and is by no means wrong, a lot of people are adapting their cover letters to complement the use of email in the application process.
One thing I always encourage people to do is to place their cover letter in the body of their email in addition to attaching a copy. I suggest this for 2 reasons. One, it speeds up the process for the recruiter (as they will only have to open up one attachment instead of two) and two, it helps eliminate the possibility (in the recruiter’s mind) that your email could be spam. Think about it – if you received an email with attachments, you would be more likely to open the attachments if there were some personalized text in the body. There will also be times where the recipient is unable to open your resume attachment, and they are much more likely to respond and request another copy if there is some text in the body of your email.
I do also suggest that you ALSO include a copy of your cover letter as an attachment just in case the recruiter would like to print it and show it to people.
In the grand scheme of things, these suggestions seem pretty minute, but with the competition as high as it is right now, why not pull out all the stops?
 
Three Words That Will Kill Your Cover Letter
It’s pretty easy to recognize a terrible cover letter within the first 2 seconds of reading one. People tend to forget that this document is a sales tool – you use it to sell yourself to a prospective employer. That being said, it’s very easy to ruin your potential sale with just a few simple words.
The most important thing you need to do when writing your cover letter is remember that the person reading it cares about what you have to offer them, not about who you are in general. When you start off with “My name is...” a hiring manager is immediately going to think that he or she is about to read a life story, and they won’t be particularly interested. While it may be anything but a mini-autobiography, it doesn’t matter when you’ve already turned off the reader with those 3 words.
Starting off with “My name is...” is pretty irrelevant when you think about it. Your name is already at the top of the page, or it’s listed as the return name in your email message; you don’t need to remind them a third time. Instead, you need to focus on why you are writing this letter, and stick to just that. 

It’s important to keep cover letters short and very straight-forward. Hiring managers are very busy and they don’t have time to read more than a few short paragraphs. Your writing needs to be engaging and interesting; you want the reader to feel compelled to read the entire thing – you don’t want them to get turned off immediately. Hiring managers tend to skim through cover letters quickly, so it’s important to highlight the most important details: why you are contacting them and why you are qualified. They aren’t interested in much more, so make sure you keep it simple.
Your goals (in addition to eventually getting hired) are to have your resume read and to be called in for an interview, so try to use all the tools you can to make that possible. Remember these tips when writing your cover letter, and I guarantee you’ll find more success in getting called for an interview.
Top 5 Cover Letter Mistakes
If you’re going to take the extra time to write a cover letter that you include along with your resume, you might as well write it properly! We talked to a few recruiters and found out that they frequently find mistakes so annoying that cause them to immediately discard some applications all together. Here’s a sample of some of the mistakes they mentioned:
Letter addressed to the wrong person or company: It doesn’t annoy hiring managers that you’re probably applying for other jobs, but it does annoy them when you don’t take the time to check that your cover letter is addressed properly. Sending it to the wrong person or company will get your application deleted immediately.
Spelling and/or grammar mistakes: You’re probably tired of being told to check and re-check your work, but it is extremely important! When spelling or grammar errors show up on your cover letter, the person reading it is going to think that you either don’t know how to write properly or that you didn’t bother to check it over. Either way, it’s bad news for you.
It’s too long: Cover letters should be short and to the point. They should provide some basic information about how you are specifically qualified for the job in question. That’s pretty much it. Anything longer than a few paragraphs starts to look more like an essay, and it’s an immediate turn-off.
No contact details: It happens quite frequently – people forget to include their name, let alone a way to contact them. While your details may be on your resume, no one wants to take extra time to fish for information that should have been provided for them right away.
No cover letter: This is the worst mistake of all. You’re competing against dozens of other applicants who have instantly shown that they took more time to apply than you.
At the end of the day, you just want to give yourself the best chance possible to be called for an interview. Think about what a potential employer wants to know most about you, and try to convert this into a cover letter.
 




www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

Arrays in C

1. Do array subscripts always start with zero?
Yes. If you have an array a[MAX] (in which MAX is some value known at compile time), the first element is a[0], and the last element is a[MAX-1]. This arrangement is different from what you would find in some other languages. In some languages, such as some versions of BASIC, the elements would be a[1] through a[MAX], and in other languages, such as Pascal, you can have it either way.
This variance can lead to some confusion. The "first element" in non-technical terms is the "zero'th" element according to its array index. If you're using spoken words, use "first" as the opposite of "last." If that's not precise enough, use pseudo-C. You might say, "The elements a sub one through a sub eight," or, "The second through ninth elements of a."
There's something you can do to try to fake array subscripts that start with one. Don't do it. The technique is described here only so that you'll know why not to use it.
Because pointers and arrays are almost identical, you might consider creating a pointer that would refer to the same elements as an array but would use indices that start with one. For example:
/* don't do this!!! */
int     a0[ MAX ];
int     *a1 = a0 - 1;   /* & a[ -1 ] */
Thus, the first element of a0 (if this worked, which it might not) would be the same as a1[1]. The last element of a0, a0[MAX-1], would be the same as a1[MAX]. There are two reasons why you shouldn't do this.
The first reason is that it might not work. According to the ANSI/ISO standard, it's undefined (which is a Bad Thing). The problem is that &a[-1] might not be a valid address; Your program might work all the time with some compilers, and some of the time with all compilers. Is that good enough?
The second reason not to do this is that it's not C-like. Part of learning C is to learn how array indices work. Part of reading (and maintaining) someone else's C code is being able to recognize common C idioms. If you do weird stuff like this, it'll be harder for people to understand your code. (It'll be harder for you to understand your own code, six months later.)
2. Is it valid to address one element beyond the end of an array?
It's valid to address it, but not to see what's there. (The really short answer is, "Yes, so don't worry about it.") With most compilers, if you say
int i, a[MAX], j;
then either i or j is at the part of memory just after the last element of the array. The way to see whether i or j follows the array is to compare their addresses with that of the element following the array. The way to say this in C is that either
& i == & a[ MAX ]
is true or
& a[ MAX ] == & j
is true. This isn't guaranteed; it's just the way it usually works. The point is, if you store something in a[MAX], you'll usually clobber something outside the a array. Even looking at the value of a[MAX] is technically against the rules, although it's not usually a problem. Why would you ever want to say &a[MAX]? There's a common idiom of going through every member of a loop using a pointer. Instead of
for ( i = 0; i < MAX; ++i )
{
        /* do something */;
}
C programmers often write this:
for ( p = a; p < & a[ MAX ]; ++p )
{
        /* do something */;
}
The kind of loop shown here is so common in existing C code that the C standard says it must work.
3. Can the sizeof operator be used to tell the size of an array passed to a function?
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. This is a Good Thing. It means that passing pointers and arrays to C functions is very efficient.
It also means that the programmer must use some mechanism to tell how big such an array is. There are two common ways to do that. The first method is to pass a count along with the array. This is what memcpy() does, for example:
char    source[ MAX ], dest[ MAX ];
/* ... */
memcpy( dest, source, MAX );
The second method is to have some convention about when the array ends. For example, a C "string" is just a pointer to the first character; the string is terminated by an ASCII NUL ('\0') character. This is also commonly done when you have an array of pointers; the last is the null pointer. Consider the following function, which takes an array of char*s. The last char* in the array is NULL; that's how the function knows when to stop.
void printMany( char *strings[] )
{
        int     i;
        i = 0;
        while ( strings[ i ] != NULL )
        {
             puts( strings[ i ] );
             ++i;
        }
}
Most C programmers would write this code a little more cryptically:
void  printMany( char *strings[] )
{
        while ( *strings )
        {
                puts( *strings++ );
        }
}
C programmers often use pointers rather than indices. You can't change the value of an array tag, but because strings is an array parameter, it's really the same as a pointer. That's why you can increment strings. Also,
while ( *strings )
means the same thing as
while ( *strings != NULL )
and the increment can be moved up into the call to puts().
If you document a function (if you write comments at the beginning, or if you write a "manual page" or a design document), it's important to describe how the function "knows" the size of the arrays passed to it. This description can be something simple, such as "null terminated," or "elephants has numElephants elements." (Or "arr should have 13 elements," if your code is written that way. Using hard coded numbers such as 13 or 64 or 1024 is not a great way to write C code, though.)
4. Is it better to use a pointer to navigate an array of values, or is it better to use a subscripted array name?
It's easier for a C compiler to generate good code for pointers than for subscripts.
Say that you have this:
/* X is some type */
X       a[ MAX ];       /* array */
X       *p;     /* pointer */
X       x;      /* element */
int     i;      /* index */
Here's one way to loop through all elements:
/* version (a) */
for ( i = 0; i < MAX; ++i )
{
        x = a[ i ];
        /* do something with x */
}
On the other hand, you could write the loop this way:
/* version (b) */
for ( p = a; p < & a[ MAX ]; ++p )
{
        x = *p;
        /* do something with x */
}
What's different between these two versions? The initialization and increment in the loop are the same. The comparison is about the same; more on that in a moment. The difference is between x=a[i] and x=*p. The first has to find the address of a[i]; to do that, it needs to multiply i by the size of an X and add it to the address of the first element of a. The second just has to go indirect on the p pointer. Indirection is fast; multiplication is relatively slow.
This is "micro efficiency." It might matter, it might not. If you're adding the elements of an array, or simply moving information from one place to another, much of the time in the loop will be spent just using the array index. If you do any I/O, or even call a function, each time through the loop, the relative cost of indexing will be insignificant.
Some multiplications are less expensive than others. If the size of an X is 1, the multiplication can be optimized away (1 times anything is the original anything). If the size of an X is a power of 2 (and it usually is if X is any of the built-in types), the multiplication can be optimized into a left shift. (It's like multiplying by 10 in base 10.)
What about computing &a[MAX] every time though the loop? That's part of the comparison in the pointer version. Isn't it as expensive computing a[i] each time? It's not, because &a[MAX] doesn't change during the loop. Any decent compiler will compute that, once, at the beginning of the loop, and use the same value each time. It's as if you had written this:
/* how the compiler implements version (b) */
X       *temp = & a[ MAX ];     /* optimization */
for ( p = a; p < temp; ++p )
{
        x = *p;
        /* do something with x */
}
This works only if the compiler can tell that a and MAX can't change in the middle of the loop. There are two other versions; both count down rather than up. That's no help for a task such as printing the elements of an array in order. It's fine for adding the values or something similar. The index version presumes that it's cheaper to compare a value with zero than to compare it with some arbitrary value:
/* version (c) */
for ( i = MAX - 1; i >= 0; --i )
{
        x = a[ i ];
        /* do something with x */
}
The pointer version makes the comparison simpler:
/* version (d) */
for ( p = & a[ MAX - 1 ]; p >= a; --p )
{
        x = *p;
        /* do something with x */
}
Code similar to that in version (d) is common, but not necessarily right. The loop ends only when p is less than a. That might not be possible.
The common wisdom would finish by saying, "Any decent optimizing compiler would generate the same code for all four versions." Unfortunately, there seems to be a lack of decent optimizing compilers in the world. A test program (in which the size of an X was not a power of 2 and in which the "do something" was trivial) was built with four very different compilers. Version (b) always ran much faster than version (a), sometimes twice as fast. Using pointers rather than indices made a big difference. (Clearly, all four compilers optimize &a[MAX] out of the loop.)
How about counting down rather than counting up? With two compilers, versions (c) and (d) were about the same as version (a); version (b) was the clear winner. (Maybe the comparison is cheaper, but decrementing is slower than incrementing?) With the other two compilers, version (c) was about the same as version (a) (indices are slow), but version (d) was slightly faster than version (b).
So if you want to write portable efficient code to navigate an array of values, using a pointer is faster than using subscripts. Use version (b); version (d) might not work, and even if it does, it might be compiled into slower code.
Most of the time, though, this is micro-optimizing. The "do something" in the loop is where most of the time is spent, usually. Too many C programmers are like half-sloppy carpenters; they sweep up the sawdust but leave a bunch of two-by-fours lying around.
 www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

Memory Leak interview question c programming


Memory Leak interview question

Question: Will the following code result in memory leak?
#include

void main(void)
{
    char *ptr = (char*)malloc(10);

    if(NULL == ptr)
    {
        printf("\n Malloc failed \n");
        return;
    }
    else
    {
        // Do some processing
    }

    return;
}
Answer: Well, Though the above code is not freeing up the memory allocated to ‘ptr’ but still this would not cause a memory leak as after the processing is done the program exits. Since the program terminates so all the memory allocated by the program is automatically freed as part of cleanup. But if the above code was all inside a while loop then this would have caused serious memory leaks.


www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

Basic .NET, ASP.NET, OOPS and SQL Server Interview questions

Basic .NET, ASP.NET, OOPS and SQL Server Interview questions
  • What is IL code, CLR, CTS, GAC & GC?
  • How can we do Assembly versioning?
  • can you explain how ASP.NET application life cycle and page life cycle events fire?
  • What is the problem with Functional Programming?
  • Can you define OOP and the 4 principles of OOP?
  • What are Classes and Objects?
  • What is Inheritance?
  • What is Polymorphism, overloading, overriding and virtual?
  • Can you explain encapsulation and abstraction?
  • What is an abstract class?
  • Define Interface & What is the diff. between abstract & interface?
  • What problem does Delegate Solve ?
  • What is a Multicast delegate ?
  • What are events and what's the difference between delegates and events?
  • How can we make Asynchronous method calls using delegates ?
  • What is a stack, Heap, Value types and Reference types ?
  • What is boxing and unboxing ?
  • Can you explain ASP.NET application and Page life cycle ?
  • What is Authentication, Authorization, Principal & Identity objects?
  • How can we do Inproc and outProc session management ?
  • How can we windows , forms and passport authentication and authorization in ASP.NET ?
  • In a parent child relationship which constructor fires first ?

Deshaw Fresher C part Interview Questions,Basic Interview Questions

Deshaw Fresher C part Interview Questions,Basic Interview Questions
Write the programs for the following problems in C.
1. Swap two variables x,y without using a temporary variable.
2. Write algorithm for finding the GCD of a number.
3.Write a program for reversing the given string.
4. The integers from 1 to n are stored in an array in a random
fashion. but one integer is missing. Write a program to find the
missing integer.
Ans): Hint : The sum of n natural numbers is = n(n+1)/2.
if we subtract the above sum from the sum of all the
numbers in the array , the result is nothing but the
missing number.

5. Some bit type of questions has been given on pointers asking to
to find whether it is correct from syntax point of view. and if
it is correct explain what it will do. (around 15 bits).
6. For the following C program
#define AND &&
#define ARRANGE (a>25 AND a<50)
main()
{int a = 30;
if (ARRANGE)
printf("within range");
else
printf("out of range");
}

What is the output?
7. For the following C program
#define AREA(x)(3.14*x*x)
main()
{float r1=6.25,r2=2.5,a;
a=AREA(r1);
printf("\n Area of the circle is %f", a);
a=AREA(r2);
printf("\n Area of the circle is %f", a);
}

What is the output?
Ans. Area of the circle is 122.656250
Area of the circle is 19.625000

8. What do the following statements indicate. Explain.
*

int(*p)[10]
*

int*f()
*

int(*pf)()
*

int*p[10]

Refer to:
-- Kernighan & Ritchie page no. 122
-- Schaum series page no. 323
9. Write a C program to find whether a stack is progressing in forward
or reverse direction.
10. Write a C program that reverses the linked list.