C FAQ From Crack The Interview
C FAQ From Crack The Interview
Write a C
program to do the same.
Singly linked lists
Method1 (Iterative)
p = head;
q = p->next;
p->next = NULL;
while (q != NULL)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
int main()
{
// Construct the linked list.
// Reverse it.
temp = reverse_recurse(head);
temp->next = NULL;
}
#include<stdio.h>
#include<ctype.h>
int main()
{
head=NULL;
tail=NULL;
add_node(1);
add_node(2);
add_node(3);
add_node(4);
add_node(5);
print_list();
reverse();
print_list();
return(1);
if(head == NULL)
{
for(cur=head;cur->next!=NULL;cur=cur->next);
cur->next=temp;
temp->prev=cur;
temp->value=value;
tail=temp;
void print_list()
{
mynode *temp;
printf("\n--------------------------------\n");
for(temp=head;temp!=NULL;temp=temp->next)
{
printf("\n[%d]\n",temp->value);
}
void reverse()
{
mynode *cur, *temp, *save_next;
if(head==tail)return;
if(head==NULL || tail==NULL)return;
for(cur=head;cur!=NULL;)
{
printf("\ncur->value : [%d]\n",cur->value);
temp=cur->next;
save_next=cur->next;
cur->next=cur->prev;
cur->prev=temp;
cur=save_next;
}
temp=head;
head=tail;
tail=temp;
}
2)Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
Copy the data from the next node into this node and delete the next node!. Ofcourse this wont work if
this is the last node. Mark it as dummy in that case! Try writing your own C program to solve this
problem.
3)How do you sort a linked list? Write a C program to sort a linked list.
Method1 (Usual method)
The general idea is to decide upon a sorting algorithm (say bubble sort). Then, one needs to come up
with different scenarios to swap two nodes in the linked list when they are not in the required order.
The different scenarios would be something like
1. When the nodes being compared are not adjacent and one of them is the first
node.
2. When the nodes being compared are not adjacent and none of them is the first
node
3. When the nodes being compared are adjacent and one of them is the first node.
4. When the nodes being compared are adjacent and none of them is the first node.
One example bubble sort for a linked list goes like this
As you can see, the code becomes quite messy because of the pointer logic. Thats why I have not
elaborated too much on the code, nor on variations such as soring a doubly linked list. You have to do
it yourself once to understand it.
if(size<=2)
{
if(size==1)
{
// Nothing to sort!
return(list);
}
else
{
if(list->value < list->next->value
{
// These 2 nodes are already in right order, no need to sort
return(list);
}
else
{
// Need to swap these 2 nodes
/* Here we have 2 nodes
*
* node 1 -> node2 -> NULL
*
* This should be converted to
*
* node2 -> node1 -> NULL
*
*/
tempnode1 = list;
tempnode2 = list->next;
tempnode2->next = tempnode1;
tempnode1->next = NULL;
return(tempnode2);
}
}
}
else
{
// The size of the linked list is more than 2.
// Need to split this linked list, sort the
// left and right sub-linked lists and merge.
// Split.
// tempnode1 will have the first half of the linked list of size "size1".
// tempnode2 will have the second half of the linked list of size "size2".
// Now merge the sorted lists back, let tempnode3 point to that new list.
<CODE TO MERGE THE 2 LINKED LISTS BACK INTO A SINGLE SORTED LINKED LIST>
return(tempnode3);
}
}
The code to merge the two already sorted sub-linked lists into a sorted linked list could be something
like this..
i = a;
j = b;
c = getNewNode();
k = getNewNode();
if(i!=NULL)
k->next=i;
else
k->next=j;
return(c->next);
struct node {
int value;
struct node *next;
};
typedef struct node *mynode;
typedef struct {
int value;
mynode next;
} *mynode;
The typedef is not defined at the point where the "next" field is declared.
struct node {
int value;
struct node next;
};
typedef struct node mynode;
You can only have pointer to structures, not the structure itself as its recursive!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char c[] = { 'a', 'b', 'c', 'd' };
int i[] = { 1, 2, 3, 4 };
char *str[] = { "hello1", "hello2", "hello3", "hello4" };
printf("Printing characters:");
print(list1, printchar);
printf(" : done\n\n");
printf("Printing integers:");
print(list2, printint);
printf(" : done\n\n");
printf("Printing strings:");
print(list3, printstr);
printf(" : done\n\n");
printf("Printing composite:");
print(list4, printcomp);
printf(" : done\n");
return 0;
}
while(current->next != NULL)
{
mynode *temp = head;
while(temp->next != NULL && temp != current)
{
if(current->next == temp)
{
printf("\nFound a loop.");
return current;
}
temp = temp->next;
}
current = current->next;
}
return NULL;
}
Visited flag
Have a visited flag in each node of the linked list. Flag it as visited when you reach the node. When
you reach a node and the flag is already flagged as visited, then you know there is a loop in the linked
list.
Fastest method
Have 2 pointers to start of the linked list. Increment one pointer by 1 node and the other by 2 nodes. If
there's a loop, the 2nd pointer will meet the 1st pointer somewhere. If it does, then you know there's
one.
p=head;
q=head->next;
// No loop.
8)How do you find the middle of a linked list? Write a C program to return the middle of a
linked list
Here are a few C program snippets to give you an idea of the possible solutions.
Method1
p=head;
q=head;
if(q->next->next!=NULL)
{
p=p->next;
q=q->next->next;
}
Here p moves one step, where as q moves two steps, when q reaches end, p will be at the middle of the
linked list.
Method2
return middle;
}
In a similar way, we can find the 1/3 th node of linked list by changing (i%2==1) to (i%3==1) and in
the same way we can find nth node of list by changing (i%2==1) to (i%n==1) but make sure ur (n<=i).
9)If you are using C language to implement the heterogeneous linked list, what pointer type will
you use?
The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to
connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void
pointer is capable of storing pointer to any type as it is a generic pointer type.
10)How to compare two linked lists? Write a C program to compare two linked lists.
Here is a simple C program to accomplish the same.
11)How to create a copy of a linked list? Write a C program to create a copy of a linked list.
Check out this C program which creates an exact copy of a linked list.
Do you know what exactly makes the binary search on an array so fast and efficient? Its the ability to
access any element in the array in constant time. This is what makes it so fast. You can get to the
middle of the array just by saying array[middle]!. Now, can you do the same with a linked list? The
answer is No. You will have to write your own, possibly inefficient algorithm to get the value of the
middle node of a linked list. In a linked list, you loosse the ability to get the value of any node in a
constant time.
Here is a C program which explains a different way of coding the atoi() function in the C language.
#include<stdioi.h>
int main()
{
printf("\n%d\n", myatoi("1998"));
getch();
return(0);
}
}
return(i);
}
Try working it out with a small string like "1998", you will find out it does work!.
This can be done either by going from right to left or left to right in the string
if (string)
{
while (*string && (*string <= '9' && *string >= '0'))
{
value = (value * 10) + (*string - '0');
string++;
}
}
return value;
}
15)Implement the memmove() function. What is the difference between the memmove() and
memcpy() function?
memmove() offers guaranteed behavior if the source and destination arguments overlap. memcpy()
makes no such guarantee, and may therefore be more efficient to implement. It's always safer to use
memmove().
This is a very elaborate implementation of memmove(). It also has C code which proves that the results
are the same irrespective of the Endian-ness of the machine. Check out this C program...
/* ------------------------------------------------------
* memmove() implementation
* ----------------------------------------------------*/
#include<stdio.h>
int main()
{
/* ----------------------------------------
*
* CASE 1 : From (SRC) < To (DEST)
*
* +--+---------------------+--+
* | | | |
* +--+---------------------+--+
* ^ ^
* | |
* From To
*
* --------------------------------------- */
p1 = (char *) calloc(1,12);
size=10;
strcpy(p1,"ABCDEFGHI");
p2 = p1 + 2;
printf("\n--------------------------------\n");
printf("\nFrom (before) = [%s]",p1);
printf("\nTo (before) = [%s]",p2);
mymove(p1,p2,size);
printf("\n--------------------------------\n");
/* ----------------------------------------
*
* CASE 1 : From (SRC) > To (DEST)
*
* +--+---------------------+--+
* | | | |
* +--+---------------------+--+
* ^ ^
* | |
* To From
*
* --------------------------------------- */
p3 = (char *) calloc(1,12);
p4 = p3 + 2;
strcpy(p4, "ABCDEFGHI");
printf("\n--------------------------------\n");
printf("\n\n");
return(0);
}
if(from==to)
{
printf("\n\nNothing to copy!\n");
}
else if(from>to)
{
diff=from-to;
if(diff>size)
{
printf("\nThe memories dont overlap, can use memcpy() here!\n");
}
for(i=diff;i<=size+diff-1;i++)
{
printf("\n->Copying from[%d] -> to[%d]",
(i-diff),
(i-diff));
to[i-diff] = from[(i-diff)];
}
}
else
{
diff=to-from;
if(diff>size)
{
printf("\nThe memories dont overlap, can use memcpy() here!\n");
}
for(i=size+diff-1;i>=diff;i--)
{
printf("\n->Copying from[%d] -> to[%d]",
(i-diff),
(i-diff));
to[(i-diff)] = from[(i-diff)];
}
}
}
--------------------------------
From (before) = [ABCDEFGHI]
To (before) = []
--------------------------------
--------------------------------
So whats the difference between the implementation of memmove() and memcpy(). Its just that
memcpy() will not care if the memories overlap and will either copy from left to right or right to left
without checking which method to used depending on the type of the overlap.
There are a number of ways to find a string inside another string. Its important to be aware of these
algorithms than to memorize them. Some of the fastest algorithms are quite tough to understand!.
Method1
The first method is the classic Brute force method. The Brute Force algorithm checks, at all positions
in the text between 0 and (n-m), if an occurrence of the pattern starts at that position or not. Then, after
each successfull or unsuccessful attempt, it shifts the pattern exactly one position to the right. The time
complexity of this searching phase is O(mn). The expected number of text character comparisons is 2n.
Here 'n' is the size of the string in which the substring of size 'm' is being searched for.
#include<stdio.h>
/* Searching */
for (j = 0; j <= (n - m); ++j)
{
for (i = 0; i < m && x[i] == y[i + j]; ++i);
if (i >= m) {printf("\nMatch found at\n\n->[%d]\n->[%s]\n",j,y+j);}
}
}
int main()
{
char *string = "hereroheroero";
char *pattern = "hero";
BF(pattern,strlen(pattern),string,strlen(string));
printf("\n\n");
return(0);
}
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
|||| ----> Match!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
Method2
Instead of checking at each position of the text if the pattern occurs or not, it is better to check first if
the contents of the current string "window" looks like the pattern or not. In order to check the
resemblance between these two patterns, a hashing function is used. Hashing a string involves
computing a numerical value from the value of its characters using a hash function.
The Rabin-Karp method uses the rule that if two strings are equal, their hash values must also be equal.
Note that the converse of this statement is not always true, but a good hash function tries to reduce the
number of such hash collisions. Rabin-Karp computes hash value of the pattern, and then goes through
the string computing hash values of all of its substrings and checking if the pattern's hash value is equal
to the substring hash value, and advancing by 1 character every time. If the two hash values are the
same, then the algorithm verifies if the two string really are equal, rather than this being a fluke of the
hashing scheme. It uses regular string comparison for this final check. Rabin-Karp is an algorithm of
choice for multiple pattern search. If we want to find any of a large number, say k, fixed length
patterns in a text, a variant Rabin-Karp that uses a hash table to check whether the hash of a given
string belongs to a set of hash values of patterns we are looking for. Other algorithms can search for a
single pattern in time order O(n), hence they will search for k patterns in time order O(n*k). The
variant Rabin-Karp will still work in time order O(n) in the best and average case because a hash table
allows to check whether or not substring hash equals any of the pattern hashes in time order of O(1).
hashing_function()
{
// A hashing function to compute the hash values of the strings.
....
}
printf("\nstring : [%s]"
"\nlength : [%d]"
"\npattern : [%s]"
"\nlength : [%d]\n\n", y,n,x,m);
/* Preprocessing phase */
Do preprocessing here..
/* Searching */
j = 0;
while (j <= n-m)
{
if (hx == hy && memcmp(x, y + j, m) == 0)
{
// Hashes match and so do the actual strings!
printf("\nMatch found at : [%d]\n",j);
}
int main()
{
char *string="hereroheroero";
char *pattern="hero";
KarpRabin(pattern,strlen(pattern),string,strlen(string));
printf("\n\n");
return(0);
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
|||| ----> Hash values match, so do the strings!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
Method3
The Knuth-Morris-Pratt or the Morris-Pratt algorithms are extensions of the basic Brute Force
algorithm. They use precomputed data to skip forward not by 1 character, but by as many as possible
for the search to succeed.
Here is some code
while (i < m)
{
while (j > -1 && x[i] != x[j])
j = Next[j];
Next[++i] = ++j;
}
}
/* Preprocessing */
preComputeData(x, m, Next);
/* Searching */
i = j = 0;
while (j < n)
{
while (i > -1 && x[i] != y[j])
i = Next[i];
i++;
j++;
if (i >= m)
{
printf("\nMatch found at : [%d]\n",j - i);
i = Next[i];
}
}
}
int main()
{
char *string="hereroheroero";
char *pattern="hero";
MorrisPrat(pattern,strlen(pattern),string,strlen(string));
printf("\n\n");
return(0);
}
This is how the comparison happens visually
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
|||| ----> Match found!
hero
hereroheroero
!
hero
Method4
The Boyer Moore algorithm is the fastest string searching algorithm. Most editors use this algorithm.
It compares the pattern with the actual string from right to left. Most other algorithms compare from
left to right. If the character that is compared with the rightmost pattern symbol does not occur in the
pattern at all, then the pattern can be shifted by m positions behind this text symbol.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b b a d a b a c b a
| |
b a b a c |
<------ |
|
b a b a c
The comparison of "d" with "c" at position 4 does not match. "d" does not occur in the pattern.
Therefore, the pattern cannot match at any of the positions 0,1,2,3,4, since all corresponding windows
contain a "d". The pattern can be shifted to position 5. The best case for the Boyer-Moore algorithm
happens if, at each search attempt the first compared character does not occur in the pattern. Then the
algorithm requires only O(n/m) comparisons .
This method is called bad character heuristics. It can also be applied if the bad character (the character
that causes a mismatch), occurs somewhere else in the pattern. Then the pattern can be shifted so that it
is aligned to this text symbol. The next example illustrates this situation.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b b a b a b a c b a
|
b a b a c
<----
|
b a b a c
Comparison between "b" and "c" causes a mismatch. The character "b" occurs in the pattern at
positions 0 and 2. The pattern can be shifted so that the rightmost "b" in the pattern is aligned to "b".
Sometimes the bad character heuristics fails. In the following situation the comparison between "a" and
"b" causes a mismatch. An alignment of the rightmost occurence of the pattern symbol a with the text
symbol a would produce a negative shift. Instead, a shift by 1 would be possible. However, in this case
it is better to derive the maximum possible shift distance from the structure of the pattern. This method
is called good suffix heuristics.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b a a b a b a c b a
| | |
c a b a b
<----
| | |
c a b a b
The suffix "ab" has matched. The pattern can be shifted until the next occurence of ab in the pattern is
aligned to the text symbols ab, i.e. to position 2.
In the following situation the suffix "ab" has matched. There is no other occurence of "ab" in the
pattern.Therefore, the pattern can be shifted behind "ab", i.e. to position 5.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b c a b a b a c b a
| | |
c b a a b
c b a a b
In the following situation the suffix "bab" has matched. There is no other occurence of "bab" in the
pattern. But in this case the pattern cannot be shifted to position 5 as before, but only to position 3,
since a prefix of the pattern "ab" matches the end of "bab". We refer to this situation as case 2 of the
good suffix heuristics.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a a b a b a b a c b a
| | | |
a b b a b
a b b a b
The pattern is shifted by the longest of the two distances that are given by the bad character and the
good suffix heuristics.
The Boyer-Moore algorithm uses two different heuristics for determining the maximum possible shift
distance in case of a mismatch: the "bad character" and the "good suffix" heuristics. Both heuristics can
lead to a shift distance of m. For the bad character heuristics this is the case, if the first comparison
causes a mismatch and the corresponding text symbol does not occur in the pattern at all. For the good
suffix heuristics this is the case, if only the first comparison was a match, but that symbol does not
occur elsewhere in the pattern.
#include<stdio.h>
#include<stdarg.h>
main()
{
void myprintf(char *,...);
char * convert(unsigned int, int);
int i=65;
char str[]="This is my string";
myprintf("\nMessage = %s%d%x",str,i,i);
}
char *p;
int i;
unsigned u;
char *s;
va_list argp;
va_start(argp, fmt);
p=fmt;
for(p=fmt; *p!='\0';p++)
{
if(*p=='%')
{
putchar(*p);continue;
}
p++;
switch(*p)
{
case 'c' : i=va_arg(argp,int);putchar(i);break;
case 'd' : i=va_arg(argp,int);
if(i<0){i=-i;putchar('-');}puts(convert(i,10));break;
case 'o': i=va_arg(argp,unsigned int); puts(convert(i,8));break;
case 's': s=va_arg(argp,char *); puts(s); break;
case 'u': u=va_arg(argp,argp, unsigned int); puts(convert(u,10));break;
case 'x': u=va_arg(argp,argp, unsigned int); puts(convert(u,16));break;
case '%': putchar('%');break;
}
}
va_end(argp);
}
ptr=&buf[sizeof(buff)-1];
*ptr='\0';
do
{
*--ptr="0123456789abcdef"[num%base];
num/=base;
}while(num!=0);
return(ptr);
}
Method1
Method2
int main()
{
char str1[] = "India";
char str2[25];
file_path_from = "<something>";
file_path_to = "<something_else>";
if (!feof(f_from)){exit(1);}
return(0);
}
A-Z - 65-90
a-z - 97-122
Note that these routines dont have much error handling incorporated in them.
toupper()
toupper(ch)
{
if(ch>='a' && c<='z')
return('A' + ch - 'a');
else
return(ch);
}
isupper()
boolean isupper(ch)
{
if(ch>='A' && ch <='Z')
return(TRUE);
else
return(FALSE);
}
while(*p!='\0')
p++;
return(p-s);
}
int a,b,t;
t = a;
a = b;
b = t;
There is no way better than this as you will find out soon. There are a few slick expressions that do
swap variables without using temporary storage. But they come with their own set of problems.
Although the code above works fine for most of the cases, it tries to modify variable 'a' two times
between sequence points, so the behavior is undefined. What this means is it wont work in all the
cases. This will also not work for floating-point values. Also, think of a scenario where you have
written your code like this
Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess
what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up
setting the variable to zero (ideally it should have swapped the variable with itself). This scenario is
quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to
some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be
swapped are already equal to each other.
Method2
a=a+b;
b=a-b;
a=a-b;
But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this
might end up giving you wrong results.
Method3
One can also swap two variables using a macro. However, it would be required to pass the type of the
variable to the macro. Also, there is an interesting problem using macros. Suppose you have a swap
macro which looks something like this
int temp;
temp=temp;
temp=b;
b=temp;
Which means it sets the value of "b" to both the variables!. It never swapped them! Scary, isn't it?
So the moral of the story is, dont try to be smart when writing code to swap variables. Use a temporary
variable. Its not only fool proof, but also easier to understand and maintain.
Suppose we have an array t[8] which keeps track of which column is occupied in which row of the
chess board. That is, if t[0]==5, then it means that the queen has been placed in the fifth column of the
first row. We need to couple the backtracking algorithm with a procedure that checks whether the tuple
is completable or not, i.e. to check that the next placed queen 'i' is not menaced by any of the already
placed 'j' (j < i):
#include<stdio.h>
static int t[10]={-1};
void queens(int i);
int empty(int i);
void print_solution();
int main()
{
queens(1);
print_solution();
return(0);
}
void queens(int i)
{
for(t[i]=1;t[i]<=8;t[i]++)
{
if(empty(i))
{
if(i==8)
{
print_solution();
/* If this exit is commented, it will show ALL possible combinations */
exit(0);
}
else
{
// Recurse!
queens(i+1);
}
}// if
}// for
}
int empty(int i)
{
int j;
j=1;
return((i==j)?1:0);
}
void print_solution()
{
int i;
for(i=1;i<=8;i++)printf("\nt[%d] = [%d]",i,t[i]);
}
t[1] = [1] // This means the first square of the first row.
t[2] = [5] // This means the fifth square of the second row.
t[3] = [8] ..
t[4] = [6] ..
t[5] = [3] ..
t[6] = [7] ..
t[7] = [2] ..
t[8] = [4] // This means the fourth square of the last row.
>-----------+
|
+---->--+ |
| | |
| | |
| <---+ |
| |
+-----------+
#include<stdio.h>
/* HELICAL MATRIX */
int main()
{
int arr[][4] = { {1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13, 14, 15, 16}
};
int i, j, k,middle,size;
printf("\n\n");
size = 4;
middle = (size-1)/2;
if (size % 2 == 1) printf("%d", arr[middle][middle]);
printf("\n\n");
return 1;
}
Also note that there is a similar question about reversing the words in a sentence, but still keeping the
words in place. That is
I am a good boy
would become
boy good a am I
This is dealt with in another question. Here I only concentrate on reversing strings. That is
I am a good boy
would become
yob doog a ma I
#include <stdio.h>
if(pos<(strlen(str)/2))
{
char ch;
// Now recurse!
reverse(pos+1);
}
}
Method2
Method4
Method5
public static String reverse(String s)
{
int N = s.length();
char[] a = new char[N];
for (int i = 0; i < N; i++)
a[i] = s.charAt(N-i-1);
String reverse = new String(a);
return reverse;
}
I am a good boy
boy good a am I
I really dont know what is the use of this!, but its still asked. Here are a few sample C programs for
your reference....
Method1
First reverse the whole string and then individually reverse the words
I am a good boy
<------------->
yob doog a ma I
<-> <--> <-> <-> <->
boy good a am I
Method2
Now its a simple question of reversing the linked list!. There are plenty of algorithms to reverse a
linked list easily. This also keeps track of the number of spaces between the words.
30)Write a C program generate permutations.
Iterative C program
#include <stdio.h>
#define SIZE 3
int main(char *argv[],int argc)
{
char list[3]={'a','b','c'};
int i,j,k;
for(i=0;i<SIZE;i++)
for(j=0;j<SIZE;j++)
for(k=0;k<SIZE;k++)
if(i!=j && j!=k && i!=k)
printf("%c%c%c\n",list[i],list[j],list[k]);
return(0);
}
Recursive C program
#include <stdio.h>
#define N 5
if(k==m)
{
/* PRINT A FROM k to m! */
for(i=0;i<N;i++){printf("%c",list[i]);}
printf("\n");
}
else
{
for(i=k;i<m;i++)
{
/* swap(a[i],a[m-1]); */
temp=list[i];
list[i]=list[m-1];
list[m-1]=temp;
permute(list,k,m-1);
/* swap(a[m-1],a[i]); */
temp=list[m-1];
list[m-1]=list[i];
list[i]=temp;
}
}
}
fact(n)
{
int fact;
if(n==1)
return(1);
else
fact = n * fact(n-1);
return(fact);
}
#include<stdio.h>
#define TRUE 1
#define FALSE 0
int main()
{
char *string = "hereheroherr";
char *pattern = "*hero*";
if(wildcard(string, pattern)==TRUE)
{
printf("\nMatch Found!\n");
}
else
{
printf("\nMatch not found!\n");
}
return(0);
}
You are given a large array X of integers (both positive and negative) and you need to find the
maximum sum found in any contiguous subarray of X.
There are various methods to solve this problem, some are listed below
Brute force
maxSum = 0
for L = 1 to N
{
for R = L to N
{
sum = 0
for i = L to R
{
sum = sum + X[i]
}
maxSum = max(maxSum, sum)
}
}
O(N^3)
Quadratic
Note that sum of [L..R] can be calculated from sum of [L..R-1] very easily.
maxSum = 0
for L = 1 to N
{
sum = 0
for R = L to N
{
sum = sum + X[R]
maxSum = max(maxSum, sum)
}
}
Using divide-and-conquer
O(N log(N))
maxSum(L, R)
{
if L > R then
return 0
if L = R then
return max(0, X[L])
M = (L + R)/2
sum = 0; maxToLeft = 0
for i = M downto L do
{
sum = sum + X[i]
maxToLeft = max(maxToLeft, sum)
}
sum = 0; maxToRight = 0
for i = M to R do
{
sum = sum + X[i]
maxToRight = max(maxToRight, sum)
}
int main()
{
int i,j,k;
int maxSum, sum;
/*---------------------------------------
* CUBIC - O(n*n*n)
*---------------------------------------*/
maxSum = 0;
for(i=0; i<N; i++)
{
for(j=i; j<N; j++)
{
sum = 0;
for(k=i ; k<j; k++)
{
sum = sum + list[k];
}
maxSum = (maxSum>sum)?maxSum:sum;
}
}
/*-------------------------------------
* Quadratic - O(n*n)
* ------------------------------------ */
maxSum = 0;
for(i=0; i<N; i++)
{
sum=0;
for(j=i; j<N ;j++)
{
sum = sum + list[j];
maxSum = (maxSum>sum)?maxSum:sum;
}
}
/*----------------------------------------
* Divide and Conquer - O(nlog(n))
* -------------------------------------- */
return(0);
}
int maxSubSum(int left, int right)
{
int mid, sum, maxToLeft, maxToRight, maxCrossing, maxInA, maxInB;
int i;
if(left>right){return 0;}
if(left==right){return((0>list[left])?0:list[left]);}
mid = (left + right)/2;
sum=0;
maxToLeft=0;
for(i=mid; i>=left; i--)
{
sum = sum + list[i];
maxToLeft = (maxToLeft>sum)?maxToLeft:sum;
}
sum=0;
maxToRight=0;
for(i=mid+1; i<=right; i++)
{
sum = sum + list[i];
maxToRight = (maxToRight>sum)?maxToRight:sum;
}
35)How to generate fibonacci numbers? How to find out if a given number is a fibonacci number or
not? Write C programs to do both.
int fib(int n)
{
int f[n+1];
f[1] = f[2] = 1;
int fib(int n)
{
if (n <= 2) return 1
else return fib(n-1) + fib(n-2)
}
Here is an iterative way to just compute and return the nth number (without storing the previous
numbers).
int fib(int n)
{
int a = 1, b = 1;
for (int i = 3; i <= n; i++)
{
int c = a + b;
a = b;
b = c;
}
return a;
}
There are a few slick ways to generate fibonacci numbers, a few of them are listed below
Method1
n
[ 1 1 ] = [ F(n+1) F(n) ]
[ 1 0 ] [ F(n) F(n-1) ]
or
or
n
(f(0) f(1)) [ 0 1 ] = (f(n) f(n+1))
[ 1 1 ]
The n-th power of the 2 by 2 matrix can be computed efficiently in O(log n) time. This implies an
O(log n) algorithm for computing the n-th Fibonacci number.
int fib(int n)
{
matrixpower(n-1);
return Matrix[0][0];
}
void matrixpower(int n)
{
if (n > 1)
{
matrixpower(n/2);
Matrix = Matrix * Matrix;
}
if (n is odd)
{
Matrix = Matrix * {{1,1}{1,0}}
}
}
#include<stdio.h>
int M[2][2]={{1,0},{0,1}};
int A[2][2]={{1,1},{1,0}};
int C[2][2]={{0,0},{0,0}}; // Temporary matrix used for multiplication.
int main()
{
int n;
n=6;
matMul(n-1);
void matMul(int n)
{
if(n>1)
{
matMul(n/2);
mulM(0); // M * M
}
if(n%2!=0)
{
mulM(1); // M * {{1,1}{1,0}}
}
}
void mulM(int m)
{
int i,j,k;
if(m==0)
{
// C = M * M
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
C[i][j]=0;
for(k=0;k<2;k++)
C[i][j]+=M[i][k]*M[k][j];
}
}
else
{
// C = M * {{1,1}{1,0}}
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
C[i][j]=0;
for(k=0;k<2;k++)
C[i][j]+=A[i][k]*M[k][j];
}
}
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
M[i][j]=C[i][j];
}
}
Method2
The cumbersome way is to generate fibonacci numbers till this number and see if this number is one of
them. But there is another slick way to check if a number is a fibonacci number or not.
To check if a number is a perfect square or not, one can take the square root, round it to the nearest
integer and then square the result. If this is the same as the original whole number then the original was
a perfect square.
This is one of the classical problems of computer science. There is a rat trapped in a maze. There are
multiple paths in the maze from the starting point to the ending point. There is some cheese at the exit.
The rat starts from the entrance of the maze and wants to get to the cheese.
111111111111111111111
100000000000000000001
100000010000000000001
100000010000000000001
100000000100001000001
100001000010000000001
100000000100000000001
100000000000000000001
111111111111111111111
· The rat can move in four directions at any point in time (well, right, left, up, down). Please
note that the rat can't move diagonally. Imagine a real maze and not a matrix. In matrix
language
· Moving right means adding {0,1} to the current coordinates.
· Moving left means adding {0,-1} to the current coordinates.
· Moving up means adding {-1,0} to the current coordinates.
· Moving right means adding {1,0} to the current coordinates.
· The rat can start off at the first row and the first column as the entrance point.
· From there, it tries to move to a cell which is currently free. A cell is free if it has a zero in it.
· It tries all the 4 options one-by-one, till it finds an empty cell. If it finds one, it moves to that
cell and marks it with a 1 (saying it has visited it once). Then it continues to move ahead from
that cell to other cells.
· If at a particular cell, it runs out of all the 4 options (that is it cant move either right, left, up
or down), then it needs to backtrack. It backtracks till a point where it can move ahead and be
closer to the exit.
· If it reaches the exit point, it gets the cheese, ofcourse.
· The complexity is O(m*m).
findpath()
{
Position offset[4];
Offset[0].row=0; offset[0].col=1;//right;
Offset[1].row=1; offset[1].col=0;//down;
Offset[2].row=0; offset[2].col=-1;//left;
Offset[3].row=-1; offset[3].col=0;//up;
Position here;
Here.row=1;
Here.col=1;
maze[1][1]=1;
int option = 0;
int lastoption = 3;
while(here.row!=m || here.col!=m)
{
//Find a neighbor to move
int r,c;
while (option<=LastOption)
{
r=here.row + offset[position].row;
c=here.col + offset[option].col;
if(maze[r][c]==0)break;
option++;
}
37)What Little-Endian and Big-Endian? How can I determine whether a machine's byte order is big-
endian or little endian? How can we convert from one to another?
Little Endian means that the lower order byte of the number is stored in memory at the lowest address,
and the higher order byte is stored at the highest address. That is, the little end comes first.
Base_Address+0 Byte0
Base_Address+1 Byte1
Base_Address+2 Byte2
Base_Address+3 Byte3
"Big Endian" means that the higher order byte of the number is stored in memory at the lowest address,
and the lower order byte at the highest address. The big end comes first.
Base_Address+0 Byte3
Base_Address+1 Byte2
Base_Address+2 Byte1
Base_Address+3 Byte0
In "Little Endian" form, code which picks up a 1, 2, 4, or longer byte number proceed in the same way
for all formats. They first pick up the lowest order byte at offset 0 and proceed from there. Also,
because of the 1:1 relationship between address offset and byte number (offset 0 is byte 0), multiple
precision mathematic routines are easy to code. In "Big Endian" form, since the high-order byte comes
first, the code can test whether the number is positive or negative by looking at the byte at offset zero.
Its not required to know how long the number is, nor does the code have to skip over any bytes to find
the byte containing the sign information. The numbers are also stored in the order in which they are
printed out, so binary to decimal routines are particularly efficient.
int num = 1;
if(*(char *)&num == 1)
{
printf("\nLittle-Endian\n");
}
else
{
printf("Big-Endian\n");
}
return((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | (byte3 << 0));
}
main()
{
towers_of_hanio(n,'L','R','C');
}
char *myfunction(int n)
{
char buffer[20];
sprintf(buffer, "%d", n);
return retbuf;
}
char *myfunc1()
{
char temp[] = "string";
return temp;
}
char *myfunc2()
{
char temp[] = {'s', 't', 'r', 'i', 'n', 'g', '\0'};
return temp;
}
int main()
{
puts(myfunc1());
puts(myfunc2());
}
The returned pointer should be to a static buffer (like static char buffer[20];), or to a buffer passed in
by the caller function, or to memory obtained using malloc(), but not to a local array.
char *myfunc()
{
char *temp = "string";
return temp;
}
int main()
{
puts(someFun());
}
So will this
calling_function()
{
char *string;
return_string(&string);
printf(?\n[%s]\n?, string);
}
40)Write a C program which produces its own source code as its output
41)Write a C progam to convert from decimal to any base (binary, hex, oct etc...)
#include <stdio.h>
int main()
{
decimal_to_anybase(10, 2);
decimal_to_anybase(255, 16);
getch();
}
while(n)
{
m=n%base;
digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m];
n=n/base;
i++;
}
Even this is one of the most frequently asked interview questions. I really dont know whats so great in
it. Nevertheless, here is a C program
Method1
Method2
if(((~i+1)&i)==i)
{
//Power of 2!
}
return(m);
}
max = ((a>b)?a:b)>c?((a>b)?a:b):c;
This is one of the very popular interview questions, so take a good look at it!.
myfunction(int *ptr)
{
int myvar = 100;
ptr = &myvar;
}
main()
{
int *myptr;
myfunction(myptr);
Arguments in C are passed by value. The called function changed the passed copy of the pointer, and
not the actual pointer.
Method1
Pass in the address of the pointer to the function (the function needs to accept a pointer-to-a-pointer).
calling_function()
{
char *string;
return_string(/* Pass the address of the pointer */&string);
printf(?\n[%s]\n?, string);
}
Method2
char *myfunc()
{
char *temp = "string";
return temp;
}
int main()
{
puts(myfunc());
}
48)Write C code to dynamically allocate one, two and three dimensional arrays (using malloc())
Its pretty simple to do this in the C language if you know how to use C pointers. Here are some
example C code snipptes....
Method1
Method3
int *myarray = malloc(no_of_rows * no_of_columns * sizeof(int));
main()
{
int ***p,i,j;
p=(int ***) malloc(MAXX * sizeof(int ***));
for(i=0;i<MAXX;i++)
{
p[i]=(int **)malloc(MAXY * sizeof(int *));
for(j=0;j<MAXY;j++)
p[i][j]=(int *)malloc(MAXZ * sizeof(int));
}
for(k=0;k<MAXZ;k++)
for(i=0;i<MAXX;i++)
for(j=0;j<MAXY;j++)
p[i][j][k]=<something>;
49)How would you find the size of structure without using sizeof()?
struct MyStruct
{
int i;
int j;
};
int main()
{
struct MyStruct *p=0;
int size = ((char*)(p+1))-((char*)p);
printf("\nSIZE : [%d]\nSIZE : [%d]\n", size);
return 0;
}
50)Write a C program to multiply two matrices.
Are you sure you know this? A lot of people think they already know this, but guess what? So take a
good look at this C program. Its asked in most of the interviews as a warm up question.
// Matrix A (m*n)
// Matrix B (n*k)
// Matrix C (m*k)
There a number of ways in which we can find out if a string is a palidrome or not. Here are a few
sample C programs...
Method1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
isPalindrome("avon sees nova");
isPalindrome("a");
isPalindrome("avon sies nova");
isPalindrome("aa");
isPalindrome("abc");
isPalindrome("aba");
isPalindrome("3a2");
exit(0);
}
if(string)
{
start = string;
end = string + strlen(string) - 1;
if(*start!=*end)
{
printf("\n[%s] - This is not a palidrome!\n", string);
}
else
{
printf("\n[%s] - This is a palidrome!\n", string);
}
}
printf("\n\n");
}
Method2
N = strlen(string);
end = N-1;
return(TRUE);
}
52)Write a C program to convert a decimal number into a binary number.
99% of the people who attend interviews can't answer this question, believe me!. Here is a C program
which does this....
#include<stdio.h>
generatebits(int num)
{
int temp;
if(num)
{
temp = num % 2;
bit(num >>= 1);
printf("%d",temp);
}
}
int main()
{
int num;
while(1)
{
scanf("Enter a number : %d",&num);
printf("\n\n");
generatebits(num);
}
getch();
return(0);
}
BinarySearch(a,n)
{
int left=0;
int right=n-1;
while(left<=right)
{
int middle=(left + right)/2;
if(x==a[middle])return(middle);
if(x>a[middle])left=middle+1;
else{right=middle-1;}
}
return(-1);
}
Complexity is O(log(n)).
return(sum);
}
p1 = h1->next;
while(p1!=h1)
{
x1 = p1->px;
y1 = p1->py;
cf1 = p1->cf;
p2 = h2->next;
while(p2 != h2)
{
x2 = p2->px;
y2 = p2->py;
cf2 = p2->cf;
p2 = p2->next;
if(p2 != h2)
{
// We found something in the second polynomial.
cf = cf1 + cf2;
p2->flag = 1;
if(cf!=0){h3=addNode(cf,x1,y1,h3);}
}
else
{
h3=addNode(cf,x1,y1,h3);
}
p1 = p1->next;
}//while
while(p2 != h2)
{
if(p2->flag==0)
{
h3=addNode(p2->cf, p2->px, p2->py, h3);
}
p2=p2->next;
}
return(h3);
}
56)Write a program to add two long positive numbers (each represented by linked lists).
Check out this simple implementation
carry = 0;
c1 = h1->next;
c2 = h2->next;
h3 = insertNode(digit, h3);
c1 = c1->next;
c2 = c2->next;
}
if(c1 != h1)
{
c = c1;
h = h1;
}
else
{
c = c2;
h = h2;
}
while(c != h)
{
sum = c->value + carry;
digit = sum % 10;
carry = sum / 10;
h3 = insertNode(digit, h3);
c = c->next;
}
if(carry==1)
{
h3 = insertNode(carry, h3);
}
return(h3);
}
57)How do you compare floating point numbers?
This is Wrong!.
double a, b;
if(a == b)
{
...
}
The above code might not work always. Thats because of the way floating point numbers are stored.
A good way of comparing two floating point numbers is to have a accuracy threshold which is relative
to the magnitude of the two floating point numbers being compared.
#include <math.h>
if(fabs(a - b) <= accurary_threshold * fabs(a))
There is a lot of material on the net to know how floating point numbers can be compared. Got for it if
you really want to understand.
The character '\r' is a carriage return without the usual line feed, this helps to overwrite the current line.
The character '\b' acts as a backspace, and will move the cursor one position to the left.
#include <stdio.h>
int main(void)
{
int old, new=3;
return 0;
}
Try this
#include <stdio.h>
int main(void)
{
char ch=0x34;
printf("\nThe exchanged value is %x",swap_nibbles(ch));
return 0;
}
Use
scanf("%[^\n]", address);
This question is also quite popular, because it has real practical uses, specially during patching when
version comparison is required
---------------------------------------------------------------------
compare_versions()
This function compare two versions in pl-sql language. This function can compare
Versions like 115.10.1 vs. 115.10.2 (and say 115.10.2 is greater), 115.10.1 vs.
115.10 (and say
115.10.1 is greater), 115.10 vs. 115.10 (and say both are equal)
---------------------------------------------------------------------
function compare_releases(release_1 in varchar2, release_2 in varchar2)
return boolean is
release_1_str varchar2(132);
release_2_str varchar2(132);
release_1_ver number;
release_2_ver number;
ret_status boolean := TRUE;
begin
return(ret_status);
end compare_releases;
Usage example
static char stamp[] = "***\nmodule " __FILE__ "\ncompiled " __TIMESTAMP__ "\n***";
...
int main()
{
...
...
}
Try
(num<<3 - num)
This is same as
num*8 - num = num * (8-1) = num * 7
This is a big string which I want to split at equal intervals, without caring about
the words.
Now, to split this string say into smaller strings of 20 characters each, try this
#define maxLineSize 20
split(char *string)
{
int i, length;
char dest[maxLineSize + 1];
i = 0;
length = strlen(string);
68)Is there a way to multiply matrices in lesser than o(n^3) time complexity?
Yes. Divide and conquer method suggests Strassen's matrix multiplication method to be used. If we
follow this method, the time complexity is O(n^2.81) times rather O(n^3) times.
Now, this guy called Strassen's somehow :) came up with a bunch of equations to calculate the 4
elements of the resultant matrix
If you are aware, the rudimentary matrix multiplication goes something like this
void matrix_mult()
{
for (i = 1; i <= N; i++)
{
for (j = 1; j <= N; j++)
{
compute Ci,j;
}
}
}
So, essentially, a 2x2 matrix multiplication can be accomplished using 8 multiplications. And the
complexity becomes
2^log 8 =2^3
Strassen showed that 2x2 matrix multiplication can be accomplished in 7 multiplications and 18
additions or subtractions. So now the complexity becomes
2^log7 =2^2.807
P1 = (A11+ A22)(B11+B22)
P2 = (A21 + A22) * B11
P3 = A11 * (B12 - B22)
P4 = A22 * (B21 - B11)
P5 = (A11 + A12) * B22
P6 = (A21 - A11) * (B11 + B12)
P7 = (A12 - A22) * (B21 + B22)
C11 = P1 + P4 - P5 + P7
C12 = P3 + P5
C21 = P2 + P4
C22 = P1 + P3 - P2 + P6
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("\nThe pointer is [%lu] bytes\n", sizeof (void *));
return (0);
}
This should show "4" incase of a 32-bit machine and "8" incase of a 64-bit machine.
70)Write a program to have the output go two places at once (to the screen and to a file also)
You can write a wrapper function for printf() which prints twice.
myprintf(...)
{
// printf(); -> To screen.
// write_to_file(); -> To file.
}
# include<stdio.h>
void main()
{
int num=123456;
int sum=0;
# include<stdio.h>
void main()
{
int num=123456;
int sum=0;
74)Write a program to merge two arrays in sorted order, so that if an integer is in both the arrays, it
gets added into the final array only once.
Try noting down the address of a local variable. Call another function with a local variable declared in
it and check the address of that local variable and compare!.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int local1;
stack(&local1);
exit(0);
}
SUM = A XOR B
CARRY = A AND B
On a wicked note, you can add two numbers wihtout using the + operator as follows
a - (- b)
:)
77)How to generate prime numbers? How to generate the next prime after a given prime?
This is a very vast subject. There are numerous methods to generate primes or to find out if a given
number is a prime number or not. Here are a few of them. I strongly recommend you to search on the
Internet for more elaborate information.
Brute Force
Test each number starting with 2 and continuing up to the number of primes we want to generate. We
divide each numbr by all divisors upto the square root of that number. If no factors are found, its a
prime.
Table method
Suppose we want to find all the primes between 1 and 64. We write out a table of these numbers, and
proceed as follows. 2 is the first integer greater than 1, so its obviously prime. We now cross out all
multiples of two. The next number we haven't crossed out is 3. We circle it and cross out all its
multiples. The next non-crossed number is 5, sp we circle it and cross all its mutiples. We only have to
do this for all numbers less than the square root of our upper limit, since any composite in the table
must have atleast one factor less than the square root of the upper limit. Whats left after this process of
elimination is all the prime numbers between 1 and 64.
78)Write a C program to find the depth or height of a tree.
tree_height(mynode *p)
{
if(p==NULL)return(0);
if(p->left){h1=tree_height(p->left);}
if(p=>right){h2=tree_height(p->right);}
return(max(h1,h2)+1);
}
The degree of the leaf is zero. The degree of a tree is the max of its element degrees. A binary tree of
height n, h > 0, has at least h and at most (2^h -1) elements in it. The height of a binary tree that
contains n, n>0, elements is at most n and atleast log(n+1) to the base 2.
n = (2^h - 1)
Here is some sample C code. The idea is to keep on moving till you hit the left most node in the tree
return(current->data);
}
On similar lines, to find the maximum value, keep on moving till you hit the right most node of the
tree.
84)Write a C program to create a mirror copy of a tree (left nodes become right and right nodes
become left)!
if(root==NULL)return(NULL);
temp->left = copy(root->right);
temp->right = copy(root->left);
return(temp);
}
This code will will only print the mirror of the tree
if (node==NULL)
{
return;
}
else
{
tree_mirror(node->left);
tree_mirror(node->right);
85)Write C code to return a pointer to the nth node of an inorder traversal of a BST.
mynode *root;
static ctr;
int main()
{
mynode *temp;
root = NULL;
printf("\n[%d]\n, temp->value);
return(0);
}
// Get the pointer to the nth inorder node in "nthnode"
void nthinorder(mynode *root, int n, mynode **nthnode)
{
static whichnode;
static found;
if(!found)
{
if(root)
{
nthinorder(root->left, n , nthnode);
if(++whichnode == n)
{
printf("\nFound %dth node\n", n);
found = 1;
*nthnode = root; // Store the pointer to the nth node.
}
nthinorder(root->right, n , nthnode);
}
}
}
inorder(mynode *root)
{
// Plain old inorder traversal
}
temp = malloc(sizeof(mynode));
temp->value = value;
temp->left = NULL;
temp->right = NULL;
if(root == NULL)
{
root = temp;
}
else
{
prev = NULL;
cur = root;
while(cur)
{
prev = cur;
cur = (value < cur->value)? cur->left : cur->right;
}
There seems to be an easier way to do this, or so they say. Suppose each node also has a weight
associated with it. This weight is the number of nodes below it and including itself. So, the root will
have the highest weight (weight of its left subtree + weight of its right subtree + 1). Using this data, we
can easily find the nth inorder node.
Note that for any node, the (weight of the leftsubtree of a node + 1) is its inorder rankin the tree!. Thats
simply because of how the inorder traversal works (left->root->right). So calculate the rank of each
node and you can get to the nth inorder node easily. But frankly speaking, I really dont know how this
method is any simpler than the one I have presented above. I see more work to be done here (calculate
thw weights, then calculate the ranks and then get to the nth node!).
Also, if (n > weight(root)), we can error out saying that this tree does not have the nth node you are
looking for.
86)Write C code to implement the preorder(), inorder() and postorder() traversals. Whats their time
complexities?
Preorder
preorder(mynode *root)
{
if(root)
{
printf("Value : [%d]", root->value);
preorder(root->left);
preorder(root->right);
}
}
Postorder
postorder(mynode *root)
{
if(root)
{
postorder(root->left);
printf("Value : [%d]", root->value);
postorder(root->right);
}
}
Inorder
inorder(mynode *root)
{
if(root)
{
inorder(root->left);
inorder(root->right);
printf("Value : [%d]", root->value);
}
}
if(root==NULL)return(NULL);
temp->left = copy(root->left);
temp->right = copy(root->right);
return(temp);
}
88)Write C code to check if a given binary tree is a binary search tree or not?
Here is a C program which checks if a given tree is a Binary Search Tree or not...
int isThisABST(struct node* mynode)
{
if (mynode==NULL) return(true);
if (node->left!=NULL && maxValue(mynode->left) > mynode->data)
return(false);
if (node->right!=NULL && minValue(mynode->right) <= mynode->data)
return(false);
if (!isThisABST(node->left) || !isThisABST(node->right))
return(false);
return(true);
}
1
2 3
5 6 7 8
1 2 3 5 6 7 8
Pseduocode
Level_order_traversal(p)
{
while(p)
{
Visit(p);
If(p->left)Q.Add(p->left);
If(p->right)Q.Add(p->right);
Delete(p);
}
}
· The node does not exist in the tree - In this case you have nothing to delete.
· The node to be deleted has no children - The memory occupied by this node must be freed
and either the left link or the right link of the parent of this node must be set to NULL.
· The node to be deleted has exactly one child - We have to adjust the pointer of the parent of
the node to be deleted such that after deletion it points to the child of the node being deleted.
· The node to be deleted has two children - We need to find the inorder successor of the node to
be deleted. The data of the inorder successor must be copied into the node to be deleted and a
pointer should be setup to the inorder successor. This inorder successor would have one or zero
children. This node should be deleted using the same procedure as for deleting a one child or a
zero child node. Thus the whole logic of deleting a node with two children is to locate the
inorder successor, copy its data and reduce the problem to a simple deletion of a node with one
or zero children.
Situation 1
100 (parent)
50 (cur == psuc)
20 80 (suc)
90
85 95
Situation 2
100 (parent)
50 (cur)
20 90
80
70 (suc)
75
72 76
if(head->left==NULL){printf("\nEmpty tree!\n");return(head);}
parent = head;
cur = head->left;
if(cur == NULL)
{
printf("\nItem to be deleted not found!\n");
return(head);
}
if(cur->left == NULL)
q = cur->right;
else if(cur->right == NULL)
q = cur->left;
else
{
// Obtain the inorder successor and its parent
psuc = cur;
cur = cur->left;
while(suc->left!=NULL)
{
psuc = suc;
suc = suc->left;
}
if(cur==psuc)
{
// Situation 1
suc->left = cur->right;
}
else
{
// Situation 2
suc->left = cur->left;
psuc->left = suc->right;
suc->right = cur->right;
}
q = suc;
if(parent->left == cur)
parent->left=q;
else
parent->rlink=q;
freeNode(cur);
return(head);
}
return(root);
}
Here is another way to do the same
count_leaf(root->right);
}
}
93)Write C code for iterative preorder, inorder and postorder tree traversals
No
Consider 2 trees below
Tree1
a
b
Tree 2
a
b
preorder = ab
postorder = ba
Preorder and postorder do not uniquely define a binary tree. Nor do preorder and level order (same
example). Nor do postorder and level order.
95)Construct a tree given its inorder and preorder traversal strings. Similarly construct a tree given its
inorder and post order traversal strings.
inorder = g d h b e i a f j c
preorder = a b d g h e i c f j
Scan the preorder left to right using the inorder sequence to separate left and right subtrees. For
example, "a" is the root of the tree; "gdhbei" are in the left subtree; "fjc" are in the right subtree. "b" is
the next root; "gdh" are in the left subtree; "ei" are in the right subtree. "d" is the next root; "g" is in the
left subtree; "h" is in the right subtree.
Scan postorder from right to left using inorder to separate left and right subtrees.
inorder = g d h b e i a f j c
postorder = g h d i e b j f c a
Tree root is "a"; "gdhbei" are in left subtree; "fjc" are in right subtree.
Scan level order from left to right using inorder to separate left and right subtrees.
inorder = g d h b e i a f j c
level order = a b c d e f g h i j
Tree root is "a"; "gdhbei" are in left subtree; "fjc" are in right subtree.
Here is some working code which creates a tree out of the Inorder and Postorder
traversals. Note that here the tree has been represented as an array. This really simplifies the whole
implementation.
A
B C
D E F G
That is, for every node at position j in the array, its left child will be stored at position (2*j) and right
child at (2*j + 1). The root starts at position 1.
#include<stdio.h>
#include<string.h>
#include<ctype.h>
/*-------------------------------------------------------------
* Algorithm
*
* Inorder And Preorder
* inorder = g d h b e i a f j c
* preorder = a b d g h e i c f j
* Scan the preorder left to right using the inorder to separate left
* and right subtrees. a is the root of the tree; gdhbei are in the
* left subtree; fjc are in the right subtree.
*------------------------------------------------------------*/
void copy_str(char dest[], char src[], int pos, int start, int end);
void print_t();
for(i=0;i<strlen(io);i++)
{
if(io[i]==po[0])
{
copy_str(t[1],io,1,i,i); // We have the root here
copy_str(t[2],io,2,0,i-1); // Its left subtree
copy_str(t[3],io,3,i+1,strlen(io)); // Its right subtree
print_t();
}
}
copy_str(t[2*j],t[j],2*j,0,posn-1);
copy_str(t[2*j+1],t[j],2*j+1,posn+1,strlen(t[j]));
copy_str(t[j],t[j],j,posn,posn);
print_t();
}
}
}
}
void copy_str(char dest[], char src[], int pos, int start, int end)
{
char mysrc[100];
strcpy(mysrc,src);
dest[0]='\0';
strncat(dest,mysrc+start,end-start+1);
if(pos>hpos)hpos=pos;
}
void print_t()
{
int i;
for(i=1;i<=hpos;i++)
{
printf("\nt[%d] = [%s]", i, t[i]);
}
printf("\n");
}
97)Given an expression tree, evaluate the expression and obtain a paranthesized form of the
expression.
infix_exp(p)
{
if(p)
{
printf("(");
infix_exp(p->left);
printf(p->data);
infix_exp(p->right);
printf(")");
}
}
if(isalnum(symbol))
st[k++] = temp;
else
{
temp->right = st[--k];
temp->left = st[--k];
st[k++] = temp;
}
}
return(st[--k]);
}
Evaluate a tree
switch(root->value)
{
case '+' : return(eval(root->left) + eval(root->right)); break;
case '-' : return(eval(root->left) - eval(root->right)); break;
case '/' : return(eval(root->left) / eval(root->right)); break;
case '*' : return(eval(root->left) * eval(root->right)); break;
case '$' : return(eval(root->left) $ eval(root->right)); break;
default : if(isalpha(root->value))
{
printf("%c = ", root->value);
scanf("%f", &num);
return(num);
}
else
{
return(root->value - '0');
}
}
}
A
B C
D E F G
That is, for every node at position i in the array, its left child will be stored at position (2*i) and right
child at (2*i + 1). The root starts at position 1.
Its
2^n - n
So, if there are 10 nodes, you will have (1024 - 10) = 1014 different trees!! Confirm it yourself with a
small number if you dont believe the formula.
101)A full N-ary tree has M non-leaf nodes, how many leaf nodes does it have?
M + (N ^ (n-1)) = (1 - (N ^ n)) / (1 - N)
Leaf nodes = M * (N - 1) + 1
A
B C D
E F G H I J K L M
Leaf nodes = M * (N - 1) + 1 = 4 * (3 - 1) + 1 = 9
102)Implement Breadth First Search (BFS) and Depth First Search (DFS)
BFS
{
Initialize Q to be a queue with v in it.
While (Q is not empty)
{
Delete a vertex w from the queue;
Let u be a vertex (if any) adjacent from w;
While (u)
{
if(u has not been labeled)
Add u to the queue;
Label u has reached;
U=next vertex that is adjacent from w;
}
}
}
DFS
{
int u = Begin(v);
while(u)
{
if(!reache[u])DFS(u);
u=nextVertex(v);
}
}
prev=NULL;
cur=root;
while(cur!=NULL)
{
prev=cur;
cur=(value<cur->value)?cur->left:cur->right;
}
Since traversing the three is the most frequent operation, a method must be devised to improve the
speed. This is where Threaded tree comes into picture. If the right link of a node in a tree is NULL, it
can be replaced by the address of its inorder successor. An extra field called the rthread is used. If
rthread is equal to 1, then it means that the right link of the node points to the inorder success. If its
equal to 0, then the right link represents an ordinary link connecting the right subtree.
struct node
{
int value;
struct node *left;
struct node *right;
int rthread;
}
temp = x->right;
if(x->rthread==1)return(temp);
while(temp->left!=NULL)temp = temp->left;
return(temp);
}
if(head->left==head)
{
printf("\nTree is empty!\n");
return;
}
temp = head;
for(;;)
{
temp = inorder_successor(temp);
if(temp==head)return;
printf("%d ", temp->value);
}
temp=getnode();
temp->info=item;
r=x->right;
x->right=temp;
x->rthread=0;
temp->left=NULL;
temp->right=r;
temp->rthread=1;
}
Function to find the inorder predecessor (for a left threaded binary three)
temp = x->left;
if(x->lthread==1)return(temp);
while(temp->right!=NULL)
temp=temp->right;
return(temp);
}
This is one of the most frequently asked interview questions of all times...
There are a number of ways to count the number of bits set in an integer. Here are some C programs to
do the same.
Method1
#include<stdio.h>
int main()
{
int num=10;
int ctr=0;
for(;num!=0;num>>=1)
{
if(num&1)
{
ctr++;
}
}
Method2
This is a slightly faster way of doing the same thing. Here the control goes into the while loop only as
many times as the number of bits set to 1 in the integer!.
#include<stdio.h>
int main()
{
int num=10;
int ctr=0;
while(num)
{
ctr++;
num = num & (num - 1); // This clears the least significant bit set.
}
Method3
This method is very popular because it uses a lookup table. This speeds up the computation. What it
does is it keeps a table which hardcodes the number of bits set in each integer from 0 to 256.
For example
0 - 0 Bit(s) set.
1 - 1 Bit(s) set.
2 - 1 Bit(s) set.
3 - 2 Bit(s) set.
...
106)What purpose do the bitwise and, or, xor and the shift operators serve?
Truth Table
-----------
0 AND 0 = 0
0 AND 1 = 0
1 AND 0 = 0
1 AND 1 = 1
x AND 0 = 0
x AND 1 = x
We use bitwise "and" to test if certain bit(s) are one or not. And'ing a value against a pattern with ones
only in the bit positions you are interested in will give zero if none of them are on, nonzero if one or
more is on. We can also use bitwise "and" to turn off (set to zero) any desired bit(s). If you "and" a
pattern against a variable, bit positions in the pattern that are ones will leave the target bit unchanged,
and bit positions in the pattern that are zeros will set the target bit to zero.
The OR operator
Truth Table
-----------
0 OR 0 = 0
0 OR 1 = 1
1 OR 0 = 1
1 OR 1 = 1
x OR 0 = x
x OR 1 = 1
Use bitwise "or" to turn on (set to one) desired bit(s).
0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
x XOR 0 = x
x XOR 1 = ~x
Use bitwise "exclusive or" to flip or reverse the setting of desired bit(s) (make it a one if it was zero or
make it zero if it was one).
Operators >> and << can be used to shift the bits of an operand to the right or left a desired number of
positions. The number of positions to be shifted can be specified as a constant, in a variable or as an
expression. Bits shifted out are lost. For left shifts, bit positions vacated by shifting always filled with
zeros. For right shifts, bit positions vacated by shifting filled with zeros for unsigned data type and
with copy of the highest (sign) bit for signed data type. The right shift operator can be used to achieve
quick multiplication by a power of 2. Similarly the right shift operator can be used to do a quick
division by power of 2 (unsigned types only). The operators >> and <<, dont change the operand at all.
However, the operators >>= and <=< also change the operand after doing the shift operations.
x << y - Gives value x shifted left y bits (Bits positions vacated by shift are
filled with zeros).
x <<= y - Shifts variable x left y bits (Bits positions vacated by shift are filled
with zeros).
For the right shift, All bits of operand participate in the shift. For unsigned
data type,
bits positions vacated by shift are filled with zeros. For signed data type, bits
positions
vacated by shift are filled with the original highest bit (sign bit). Right
shifting n bits
divides by 2 raise to n. Shifting signed values may fail because for negative
values the result never
gets past -1:
-5 >> 3 is -1 and not 0 like -5/8.
A simple C command line utility takes a series of command line options. The options are given to the
utility like this : <utility_name> options=[no]option1,[no]options2,[no]option3?... Write C code using
bitwise operators to use these flags in the code.
//Each option will have a bit reserved in the global_options_bits integer. The
global_options_bits
// integer will have a bit set or not set depending on how the option was specified
by the user.
// For example, if the user said nooption1, the bit for OPTION1 in
global_options_bits
// will be 0. Likewise, if the user specified option3, the bit for OPTION3 in
global_options_bits
// will be set to 1.
// Assume you have already parsed the command line option and that
// parsed_argument_without_no has option1 or option2 or option3 (depending on what
has
// been provided at the command line) and the variable negate_argument says if the
// option was negated or not (i.e, if it was option1 or nooption1)
if (negate_argument)
{
// Setting the bit for this particular option to 0 as the option has
// been negated.
action_mask= ~(OPTION1_BITPOS) & ALL_BITPOS;
tmp_action= tmp_action & action_mask;
}
else
{
//Setting the bit for this particular option to 1.
action_mask= (OPTION1_BITPOS);
tmp_action= tmp_action | action_mask;
}
//Now someone who wishes to check if a particular option was set or not can use the
// following type of code anywhere else in the code.
if(((global_options_bits & OPTION1_BITPOS) == OPTION1_BITPOS)
{
//Do processing for the case where OPTION1 was active.
}
else
{
//Do processing for the case where OPTION1 was NOT active.
}
Method1
int i;
Method2
In this method, we use a lookup table.
A Heap is an almost complete binary tree.In this tree, if the maximum level is i, then, upto the (i-1)th
level should be complete. At level i, the number of nodes can be less than or equal to 2^i. If the
number of nodes is less than 2^i, then the nodes in that level should be completely filled, only from left
to right.
The property of an ascending heap is that, the root is the lowest and given any other node i, that node
should be less than its left child and its right child. In a descending heap, the root should be the highest
and given any other node i, that node should be greater than its left child and right child.
To sort the elements, one should create the heap first. Once the heap is created, the root has the highest
value. Now we need to sort the elements in ascending order. The root can not be exchanged with the
nth element so that the item in the nth position is sorted. Now, sort the remaining (n-1) elements. This
can be achieved by reconstructing the heap for (n-1) elements.
heapsort()
{
n = array(); // Convert the tree into an array.
makeheap(n); // Construct the initial heap.
makeheap(n)
{
heapsize=n;
for(i=n/2; i>=1; i--)
keepheap(i);
}
keepheap(i)
{
l = 2*i;
r = 2*i + 1;
p = s[l];
q = s[r];
t = s[i];
m = s[largest];
if(largest != i)
{
swap(s[i], s[largest]);
keepheap(largest);
}
}
Both Merge-sort and Quick-sort have same time complexity i.e. O(nlogn). In merge sort the file a[1:n]
was divided at its midpoint into sub-arrays which are independently sorted and later merged. Whereas,
in quick sort the division into two sub-arrays is made so that the sorted sub-arrays do not need to be
merged latter.
while(i<=m)
c[k++]=a[i++];
while(j<=n)
c[k++]=a[j++];
}
113)Implement the bubble sort algorithm. How can it be improved? Write the code for selection sort,
quick sort, insertion sort.
To improvise this basic algorithm, keep track of whether a particular pass results in any swap or not. If
not, you can break out without wasting more cycles.
if(flag==0)break;
}
}
temp = a[pos];
a[pos] = a[i];
a[i] = temp;
}
}
key = a[low];
i = low + 1;
j = high;
while(1)
{
while(i < high && key >= a[i])i++;
if(i < j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
else
{
temp = a[low];
a[low] = a[j];
a[j] = temp;
return(j);
}
}
}
int main()
{
// Populate the array a
quicksort(a, 0, n - 1);
}
a[j + 1] = item;
}
}
The postfix "++" operator has higher precedence than prefix "*" operator. Thus, *p++ is same as *(p+
+); it increments the pointer p, and returns the value which p pointed to before p was incremented. If
you want to increment the value pointed to by p, try (*p)++.
115)What is a NULL pointer? How is it different from an unitialized pointer? How is a NULL pointer
defined?
A null pointer simply means "I am not allocated yet!" and "I am not pointing to anything yet!".
The C language definition states that for every available pointer type, there is a special value which is
called the null pointer. It is guaranteed to compare unequal to a pointer to any object or function.
A null pointer is very different from an uninitialized pointer. A null pointer does not point to any
object or function; but an uninitialized pointer can point anywhere.
There is usually a null pointer for each type of a pointer, and the internal values of these null pointers
for different pointer types may be different, its up to the compiler. The & operator will never yield a
null pointer, nor will a successful call to malloc() (malloc() does return a null pointer when it fails).
In this call to execl(), the last argument has been explicitly casted to force the 0 to be treated as a
pointer.
if(ptr){}
and
if(!ptr){}
Make sure you are able to distinguish between the following : the null pointer, the internal
representation of a null pointer, the null pointer constant (i.e, 0), the NULL macro, the ASCII null
character (NUL), the null string ("").
This error means that the program has written, through a null (probably because its an uninitialized)
pointer, to a location thats invalid.
More to come....
117)Does an array always get converted to a pointer? What is the difference between arr and &arr?
How does one declare a pointer to an entire array?
In C, the array and pointer arithmetic is such that a pointer can be used to access an array or to simulate
an array. What this means is whenever an array appears in an expression, the compiler automatically
generates a pointer to the array's first element (i.e, &a[0]).
Also, on a side note, the rule by which arrays decay into pointers is not applied recursively!. An array
of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer.
int myarray[NO_OF_ROWS][NO_OF_COLUMNS];
myfunc(myarray);
or
Since the called function does not allocate space for the array, it does not need to know the overall
size, so the number of rows, NO_OF_ROWS, can be omitted. The width of the array is still important,
so the column dimension
NO_OF_COLUMNS must be present.
An array is never passed to a function, but a pointer to the first element of the array is passed to the
function. Arrays are automatically allocated memory. They can't be relocated or resized later. Pointers
must be assigned to allocated memory (by using (say) malloc), but pointers can be reassigned and
made to point to other memory chunks.
In C, &arr yields a pointer to the entire array. On the other hand, a simple reference to arr returns a
pointer to the first element of the array arr. Pointers to arrays (as in &arr) when subscripted or
incremented, step over entire arrays, and are useful only when operating on arrays of arrays. Declaring
a pointer to an entire array can be done like int (*arr)[N];, where N is the size of the array.
Also, note that sizeof() will not report the size of an array when the array is a parameter to a function,
simply because the compiler pretends that the array parameter was declared as a
pointer and sizeof reports the size of the pointer.
Before ANSI C introduced the void * generic pointer, these casts were required because older
compilers used to return a char pointer.
int *myarray;
myarray = (int *)malloc(no_of_elements * sizeof(int));
But, under ANSI Standard C, these casts are no longer necessary as a void pointer can be assigned to
any pointer. These casts are still required with C++, however.
119)What does malloc() , calloc(), realloc(), free() do? What are the common problems with malloc()?
Is there a way to find out how much memory a pointer was allocated?
calloc(m, n) is also used to allocate memory, just like malloc(). But in addition, it also zero fills the
allocated memory area. The zero fill is all-bits-zero. calloc(m.n) is essentially equivalent to
p = malloc(m * n);
memset(p, 0, m * n);
The malloc() function allocates raw memory given a size in bytes. On the other hand, calloc() clears
the requested memory to zeros before return a pointer to it. (It can also compute the request size given
the size of the base data structure and the number of them desired.)
Any memory allocated using malloc() realloc() must be freed using free(). In general, for every call to
malloc(), there should be a corresponding call to free(). When you call free(), the memory pointed to
by the passed pointer is freed. However, the value of the pointer in the caller remains unchanged. Its a
good practice to set the pointer to NULL after freeing it to prevent accidental usage. The
malloc()/free() implementation keeps track of the size of each block as it is allocated, so it is not
required to remind it of the size when freeing it using free(). You can't use dynamically-allocated
memory after you free it.
Unfortunately there is no standard or portable way to know how big an allocated block is using the
pointer to the block!. God knows why this was left out in C.
Yes, it is!
120)What's the difference between const char *p, char * const p and char * const * p?
const char *p - Cannot change the value pointed to by p, but can change the pointer
p itself.
*p = 'A' is illegal.
p = "Hello" is legal.
const * char p - Cannot change the pointer p, but can change the value pointed to
by p.
*p = 'A' is legal.
p = "Hello" is illegal.
const char * const p - Cannot change the value pointed to by p nor the pointer.
Errata The question wrongly mentions char * const *p, which is not legal. Instead it should be const
char * const p. This will be corrected the next time the FAQ is updated.
The void data type is used when no other data type is appropriate. A void pointer is a pointer that may
point to any kind of object at all. It is used when a pointer must be specified but its type is unknown.
The compiler doesn't know the size of the pointed-to objects incase of a void * pointer. Before
performing arithmetic, convert the pointer either to char * or to the pointer type you're trying to
manipulate
122)What do Segmentation fault, access violation, core dump and Bus error mean?
The segmentation fault, core dump, bus error kind of errors usually mean that the program tried to
access memory it shouldn't have.
Probable causes are overflow of local arrays; improper use of null pointers; corruption of the malloc()
data structures; mismatched function arguments (specially variable argument functions like sprintf(),
fprintf(), scanf(), printf()).
For example, the following code is a sure shot way of inviting a segmentation fault in your program:
sprintf(buffer,
"%s %d",
"Hello");
So whats the difference between a bus error and a segmentation fault?
A bus error is a fatal failure in the execution of a machine language instruction resulting from the
processor
detecting an anomalous condition on its bus.
A bus error triggers a processor-level exception, which Unix translates into a "SIGBUS" signal,which
if not caught, will terminate the current process. It looks like a SIGSEGV, but the difference between
the two is that SIGSEGV indicates an invalid access to valid memory, while SIGBUS indicates an
access to an invalid address.
Bus errors mean different thing on different machines. On systems such as Sparcs a bus error occurs
when you access memory that is not positioned correctly.
int main(void)
{
char *c;
long int *i;
c = (char *) malloc(sizeof(char));
c++;
i = (long int *)c;
printf("%ld", *i);
return 0;
}
On Sparc machines long ints have to be at addresses that are multiples of four (because they are four
bytes long), while chars do not (they are only one byte long so they can be put anywhere). The
example code uses the char to create an invalid address, and assigns the long int to the invalid address.
This causes a bus error when the long int is dereferenced.
A segfault occurs when a process tries to access memory that it is not allowed to, such as the memory
at address 0 (where NULL usually points). It is easy to get a segfault, such as the following example,
which dereferences NULL.
#include < stdio.h>
int main(void)
{
char *p;
p = NULL;
putchar(*p);
return 0;
}
int *p[10];
int (*p)[10];
Its an scenario where the program has lost a reference to an area in the memory. Its a programming
term describing the loss of memory. This happens when the program allocates some memory but fails
to return it to the system
125)What are brk() and sbrk() used for? How are they different from malloc()?
brk() and sbrk() are the only calls of memory management in UNIX. For one value of the address,
beyond the last logical data page of the process, the MMU generates a segmentation violation interrupt
and UNIX kills the process. This address is known as the break address of a process. Addition of a
logical page to the data space implies raising of the break address (by a multiple of a page size).
Removal of an entry from the page translation table automatically lowers the break address.
Both calls return the old break address to the process. In brk(), the new break address desired needs to
be specified as the parameter. In sbrk(), the displacement (+ve or -ve) is the difference between the
new and the old break address. sbrk() is very similar to malloc() when it allocates memory (+ve
displacement).
malloc() is really a memory manager and not a memory allocator since, brk/sbrk only can do memory
allocations under UNIX. malloc() keeps track of occupied and free peices of memory. Each malloc
request is expected to give consecutive bytes and hence malloc selects the smallest free pieces that
satisfy a request. When free is called, any consecutive free pieces are coalesced into a large free piece.
These is done to avoid fragmentation.
realloc() can be used only with a preallocated/malloced/realloced memory. realloc() will automatically
allocate new memory and transfer maximum possible contents if the new space is not available. Hence
the returned value of realloc must always be stored back into the old pointer itself.
126)What is a dangling pointer? What are reference counters with respect to pointers?
A pointer which points to an object that no longer exists. Its a pointer referring to an area of memory
that has been deallocated. Dereferencing such a pointer usually produces garbage.
Using reference counters which keep track of how many pointers are pointing to this memory location
can prevent such issues. The reference counts are incremented when a new pointer starts to point to the
memory location and decremented when they no longer need to point to that memory. When the
reference count reaches zero, the memory can be safely freed. Also, once freed, the corresponding
pointer must be set to NULL.
Since addresses are always whole numbers, pointers always contain whole numbers.
Yes
*(*(p+i)+j) == p[i][j].
So is
129)What operations are valid on pointers? When does one get the Illegal use of pointer in function
error?
px<py
px>=py
px==py
px!=py
px==NULL
px=px+n
px=px-n
px-py
Something like
j = j * 2;
k = k / 2;
The extern in a function's declaration is sometimes used to indicate that the function's definition is in
some other source file, but there is no difference between
and
int function_name();
You can pass pointers to locations which the function being called can populate, or have the function
return a structure containing the desired values, or use global variables.
Function overload is not present in C. In C, either use different names or pass a union of supported
types (with additional identifier that give hints of the type to be used).
Most people think its supported because they might unknowingly be using a C++ compiler to compile
their C code and C+= does have function overloading.
The inline comment is a request to the compiler to copy the code into the object at every place the
function is called. That is, the function is expanded at each point of call. Most of the advantage of
inline functions comes from avoiding the overhead of calling an actual function. Such overhead
includes saving registers, setting up stack frames, and so on. But with large functions the overhead
becomes less important. Inlining tends to blow up the size of code, because the function is expanded at
each point of call.
int myfunc(int a)
{
...
}
Inlined functions are not the fastest, but they are the kind of better than macros (which people use
normally to write small functions).
#define myfunc(a) \
{ \
... \
}
The problem with macros is that the code is literally copied into the location it was called from. So if
the user passes a "double" instead of an "int" then problems could occur. However, if this senerio
happens with an inline function the compiler will complain about incompatible types. This will save
you debugging time stage.
char *(*(*a[N])())();
138)Can we declare a function that can return a pointer to a function of the same type?
We cannot do it directly. Either have the function return a generic function pointer, with casts to adjust
the types as the pointers are passed around; or have it return a structure containing only a pointer to a
function returning that structure.
139)How can I write a function that takes a variable number of arguments? What are the limitations
with this? What is vprintf()?
The header stdarg.h provides this functionality. All functions like printf(), scanf() etc use this
functionality.
The program below uses a var_arg type of function to count the overall length of strings passed to the
function.
#include <stdarg.h>
length = strlen(first_argument);
while((p = va_arg(argp, char *)) != NULL)
{
length = length + strlen(p);
}
va_end(argp);
return(length);
}
int main()
{
int length;
length = myfunction("Hello","Hi","Hey!",(char *)NULL);
return(0);
}
Any function which takes a variable number of arguments must be able to determine from the
arguments themselves, how many of them there have been passed. printf() and some similar functions
achieve this by looking for the format string. This is also why these functions fail badly if the format
string does not match the argument list. Another common technique, applicable when the arguments
are all of the same type, is to use a sentinel value (often 0, -1, or an appropriately-cast null pointer) at
the end of the list. Also, one can pass an explicit count of the number of variable arguments. Some
older compilers did provided a nargs() function, but it was never portable.
Is this allowed?
int f(...)
{
...
}
No! Standard C requires at least one fixed argument, in part so that you can hand it to va_start().
va_arg(argp, float);
va_arg(argp, double)
Similarly, use
va_arg(argp, int)
How can I create a function which takes a variable number of arguments and passes them to some
other function (which takes a variable number of arguments)?
You should provide a version of that other function which accepts a va_list type of pointer.
So how can I call a function with an argument list built up at run time?
There is no portable way to do this. Instead of an actual argument list, you might want to pass an array
of generic (void *) pointers. The called function can then step through the array, much like main()
steps through char *argv[].
Below, the myerror() function prints an error message, preceded by the string "error: " and terminated
with a newline:
#include <stdio.h>
#include <stdarg.h>
void myerror(char *fmt, ...)
{
va_list argp;
fprintf(stderr, "error: ");
va_start(argp, fmt);
vfprintf(stderr, fmt, argp);
va_end(argp);
fprintf(stderr, "\n");
}
140)With respect to function parameter passing, what is the difference between call-by-value and call-
by-reference? Which method does C use?
In the case of call-by-reference, a pointer reference to a variable is passed into a function instead of the
actual value. The function's operations will effect the variable in a global as well as local sense. Call-
by-value (C's method of parameter passing), by contrast, passes a copy of the variable's value into the
function. Any changes to the variable made by function have only a local effect and do not alter the
state of the variable passed into the function.
No.
C uses pass by value, but it can pretend doing pass by reference, by having functions that have pointer
arguments and by using the & operator when calling the function. This way, the compiler will simulate
this feature (like when you pass an array to a function, it actually passes a pointer instead). C does not
have something like the formal pass by reference or C++ reference parameters.
141)If I have the name of a function in the form of a string, how can I invoke that function?
struct
{
char *name;
int (*func_ptr)();
} func_table[] = {"myfunc1", myfunc1,
"myfunc2", myfunc2,};
Search the table for the name, and call via the associated function pointer.
If there is no declaration in scope then it is assumed to be declared as returning an int and without any
argument type information. This can lead to discrepancies if the function is later declared or defined.
Such functions must be declared before they are called. Also check if there is another function in some
header file with the same name.
143)How can I pass the variable argument list passed to one function to another function.
Good question
#include <stdarg.h>
main()
{
display("Hello", 4, 12, 13, 14, 44);
}
display(char *s,...)
{
show(s,...);
}
show(char *t,...)
{
va_list ptr;
int a;
va_start(ptr,t);
a = va_arg(ptr, int);
printf("%f", a);
}
#include <stdarg.h>
main()
{
display("Hello", 4, 12, 13, 14, 44);
}
display(char *s,...)
{
va_list ptr;
va_start(ptr, s);
show(s,ptr);
}
144)How do I pass a variable number of function pointers to a variable argument (va_arg) function?
#include <stdarg.h>
main()
{
int (*p1)();
int (*p2)();
int fun1(), fun2();
p1 = fun1;
p2 = fun2;
display("Bye", p1, p2);
}
display(char *s,...)
{
int (*pp1)(), (*pp2)();
va_list ptr;
typedef int (*f)(); //This typedef is very important.
va_start(ptr,s);
pp1 = va_arg(ptr, f); // va_arg(ptr, int (*)()); would NOT have worked!
pp2 = va_arg(ptr, f);
(*pp1)();
(*pp2)();
}
fun1()
{
printf("\nHello!\n");
}
fun2()
{
printf("\nHi!\n");
}
It wont if the prototpe is around. It will ideally scream out with an error like
or
#include <stdio.h>
/*
int foo(int a);
int foo2(int a, int b);
*/
int main(int a)
{
int (*fp)(int a);
a = foo();
a = foo2(1);
exit(0);
}
int foo(int a)
{
return(a);
}
What this means is that the right hand side of the expression is not evaluated if the left hand side
determines the outcome. That is if the left hand side is true for || or false for &&, the right hand side is
not evaluated.
Although its surprising that an expression like i=i+1; is completely valid, something like a[i]=i+1; is
not. This is because all accesses to an element must be to change the value of that variable. In the
statement a[i]=i+1; , the access to i is not for itself, but for a[i] and so its invalid. On similar lines, i=i+
+; or i=++i; are invalid. If you want to increment the value of i, use i=i+1; or i+=1; or i++; or ++i; and
not some combination.
A sequence point is a state in time (just after the evaluation of a full expression, or at the ||, &&, ?:, or
comma operators, or just before a call to a function) at which there are no side effects.
Between the previous and next sequence point an object shall have its stored
value modified at most once by the evaluation of an expression. Furthermore,
the prior value shall be accessed only to determine the value to be stored.
148)Does the ?: (ternary operator) return a lvalue? How can I assign a value to the output of the
ternary operator?
Try doing something like this if you want to assign a value to the output of this operator
*((mycondition) ? &var1 : &var2) = myexpression;
Yes!
But frankly, this feature is of no use to anyone. Anyone asking this question is more or less a fool
trying to be cool.
The directive provides a single, well-defined "escape hatch" which can be used for all sorts of
(nonportable) implementation-specific controls and extensions: source listing control, structure
packing, warning suppression (like lint's old /* NOTREACHED */ comments), etc.
For example
#pragma once
inside a header file is an extension implemented by some preprocessors to help make header files
idempotent (to prevent a header file from included twice).
Nothing!. But, it's a good trick to prevent the common error of writing
if(x = 0)
The error above is the source of a lot of serious bugs and is very difficult to catch. If you cultivate the
habit of writing the constant before the ==, the compiler will complain if you accidentally type
if(0 = x)
You should use gotos wherever it suits your needs really well. There is nothing wrong in using them.
Really.
There are cases where each function must have a single exit point. In these cases, it makes much sense
to use gotos.
myfunction()
{
if(error_condition1)
{
// Do some processing.
goto failure;
}
if(error_condition2)
{
// Do some processing.
goto failure;
}
success:
return(TRUE);
failure:
// Do some cleanup.
return(FALSE);
}
Also, a lot of coding problems lend very well to the use of gotos. The only argument against gotos is
that it can make the code a little un-readable. But if its commented properly, it works quite fine.
Any good compiler will and should generate identical code for ++i, i += 1, and i = i + 1. Compilers are
meant to optimize code. The programmer should not be bother about such things. Also, it depends on
the processor and compiler you are using. One needs to check the compiler's assembly language
output, to see which one of the different approcahes are better, if at all.
Note that speed comes Good, well written algorithms and not from such silly tricks.
An lvalue is an expression that could appear on the left-hand sign of an assignment (An object that has
a location). An rvalue is any expression that has a value (and that can appear on the right-hand sign of
an assignment).
The lvalue refers to the left-hand side of an assignment expression. It must always evaluate to a
memory location. The rvalue represents the right-hand side of an assignment expression; it may have
any meaningful combination of variables and constants.
Casting is a mechanism built into C that allows the programmer to force the conversion of data types.
This may be needed because most C functions are very particular about the data types they process. A
programmer may wish to override the default way the C compiler promotes data types.
A statement is a single C expression terminated with a semicolon. A block is a series of statements, the
group of which is enclosed in curly-braces.
The process by which the C compiler ensures that functions and operators use data of the appropriate
type(s). This form of check helps ensure the semantic correctness of the program.
struct salary
{
char empname[20];
struct
{
int dearness;
}
allowance;
}employee;
It is a reference to a variable or function before it is defined to the compiler. The cardinal rule of
structured languages is that everything must be defined before it can be used. There are rare occasions
where this is not possible. It is possible (and sometimes necessary) to define two functions in terms of
each other. One will obey the cardinal rule while the other will need a forward declaration of the
former in order to know of the former's existence.
161)What is the difference between the & and && operators and the | and || operators?
& and | are bitwise AND and OR operators respectively. They are usually used to manipulate the
contents of a variable on the bit level. && and || are logical AND and OR operators respectively. They
are usually used in conditionals
162)Is C case sensitive (ie: does C differentiate between upper and lower case letters)?
Yes, ofcourse!
No!
main()
{
int i=1;
while (i<=5)
{
printf("%d",i);
if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf("PP");
}
The following preprocessor directives are used for conditional compilation. Conditional compilation
allows statements to be included or omitted based on conditions at compile time.
#if
#else
#elif
#endif
#ifdef
#ifndef
In the following example, the printf statements are compiled when the symbol DEBUG is defined, but
not compiled otherwise
#ifdef DEBUG
printf( "x=%d\n" );
#endif...
y = ....;
#ifdef DEBUG
printf( "y=%d\n" );
#endif...
#if directive
Expression examples
#if 1
#if 0
#if ABE == 3
#if ZOO < 12
#if ZIP == 'g'
#if (ABE + 2 - 3 * ZIP) > (ZIP - 2)
#else directive
· #else marks the beginning of statement(s) to be compiled if the preceding #if or #elif
expression is zero (false)
· Statements following #else are bounded by matching #endif
Examples
#if OS = 'A'
system( "clear" );
#else
system( "cls" );
#endif
#elif directive
Examples
#if TST == 1
z = fn1( y );
#elif TST == 2
z = fn2( y, x );
#elif TST == 3
z = fn3( y, z, w );
#endif
...
#if ZIP == 'g'
rc = gzip( fn );
#elif ZIP == 'q'
rc = qzip( fn );
#else
rc = zip( fn );
#endif
· #ifdef is used to include or omit statements from compilation depending of whether a macro
name is defined or not.
· Often used to allow the same source module to be compiled in different environments (UNIX/
DOS/MVS), or with different options (development/production).
· #ifndef similar, but includes code when macro name is not defined.
Examples
#ifdef TESTENV
printf( "%d ", i );
#endif
#ifndef DOS
#define LOGFL "/tmp/loga.b";
#else
#define LOGFL "c:\\tmp\\log.b";
#endif
defined() operator
· defined(mac), operator is used with #if and #elif and gives 1 (true) if macro name mac is
defined, 0 (false) otherwise.
· Equivalent to using #ifdef and #ifndef, but many shops prefer #if with defined(mac) or !
defined(mac)
Examples
#if defined(TESTENV)
printf( "%d ", i );
#endif
#if !defined(DOS)
#define LOGFL "/tmp/loga.b";
#else
#define LOGFL "c:\\tmp\\log.b";
#endif
166)Can we use variables inside a switch statement? Can we use floating point numbers? Can we use
expressions?
No
The only things that case be used inside a switch statement are constants or enums. Anything else will
give you a
switch(i)
{
case "string1" : // Something;
break;
case "string2" : // Something;
break;
}
switch(i)
{
case 1: // Something;
break;
case 1*2+4: // Something;
break;
}
switch(i)
{
case 1: // Something;
break;
case t: // Something;
break;
}
Also note that the default case does not require a break; if and only if its at the end of the switch()
statement. Otherwise, even the default case requires a break;
167)What is more efficient? A switch() or an if() else()?
168)How to write functions which accept two-dimensional arrays when the width is not known before
hand?
It declares an array of size three, initialized with the three characters 'a', 'b', and 'c', without the usual
terminating '\0' character. The array is therefore not a true C string and cannot be used with strcpy,
printf %s, etc. But its legal.
No
Doing a++ is asking the compiler to change the base address of the array. This the only thing that the
compiler remembers about an array once its declared and it wont allow you to change the base address.
If it allows, it would be unable to remember the beginning of the array.
171)What is the difference between the declaration and the definition of a variable?
The definition is the one that actually allocates space, and provides an initialization value, if any.
There can be many declarations, but there must be exactly one definition. A definition tells the
compiler to set aside storage for the variable. A declaration makes the variable known to parts of the
program that may wish to use it. A variable might be defined and declared in the same statement.
Uninitialized variables declared with the "static" keyword are initialized to zero. Such variables are
implicitly initialized to the null pointer if they are pointers, and to 0.0F if they are floating point
numbers.
Local variables start out containing garbage, unless they are explicitly initialized.
Memory obtained with malloc() and realloc() is likely to contain junk, and must be initialized. Memory
obtained with calloc() is all-bits-0, but this is not necessarily useful for pointer or floating-point values
(This is in contrast to Global pointers and Global floating point numbers, which start as zeroes of the
right type).
No, C does not have a boolean variable type. One can use ints, chars, #defines or enums to achieve the
same in C.
#define TRUE 1
#define FALSE 0
An enum may be good if the debugger shows the names of enum constants when examining variables.
174)
1)How do you reverse a singly linked list? How do you reverse a doubly linked list? Write a C
program to do the same.
Singly linked lists
Method1 (Iterative)
p = head;
q = p->next;
p->next = NULL;
while (q != NULL)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
int main()
{
// Construct the linked list.
// Reverse it.
temp = reverse_recurse(head);
temp->next = NULL;
}
#include<stdio.h>
#include<ctype.h>
int main()
{
head=NULL;
tail=NULL;
add_node(1);
add_node(2);
add_node(3);
add_node(4);
add_node(5);
print_list();
reverse();
print_list();
return(1);
if(head == NULL)
{
for(cur=head;cur->next!=NULL;cur=cur->next);
cur->next=temp;
temp->prev=cur;
temp->value=value;
tail=temp;
void print_list()
{
mynode *temp;
printf("\n--------------------------------\n");
for(temp=head;temp!=NULL;temp=temp->next)
{
printf("\n[%d]\n",temp->value);
}
void reverse()
{
mynode *cur, *temp, *save_next;
if(head==tail)return;
if(head==NULL || tail==NULL)return;
for(cur=head;cur!=NULL;)
{
printf("\ncur->value : [%d]\n",cur->value);
temp=cur->next;
save_next=cur->next;
cur->next=cur->prev;
cur->prev=temp;
cur=save_next;
}
temp=head;
head=tail;
tail=temp;
}
2)Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
Copy the data from the next node into this node and delete the next node!. Ofcourse this wont work if
this is the last node. Mark it as dummy in that case! Try writing your own C program to solve this
problem.
3)How do you sort a linked list? Write a C program to sort a linked list.
Method1 (Usual method)
The general idea is to decide upon a sorting algorithm (say bubble sort). Then, one needs to come up
with different scenarios to swap two nodes in the linked list when they are not in the required order.
The different scenarios would be something like
1. When the nodes being compared are not adjacent and one of them is the first
node.
2. When the nodes being compared are not adjacent and none of them is the first
node
3. When the nodes being compared are adjacent and one of them is the first node.
4. When the nodes being compared are adjacent and none of them is the first node.
One example bubble sort for a linked list goes like this
As you can see, the code becomes quite messy because of the pointer logic. Thats why I have not
elaborated too much on the code, nor on variations such as soring a doubly linked list. You have to do
it yourself once to understand it.
if(size<=2)
{
if(size==1)
{
// Nothing to sort!
return(list);
}
else
{
if(list->value < list->next->value
{
// These 2 nodes are already in right order, no need to sort
return(list);
}
else
{
// Need to swap these 2 nodes
/* Here we have 2 nodes
*
* node 1 -> node2 -> NULL
*
* This should be converted to
*
* node2 -> node1 -> NULL
*
*/
tempnode1 = list;
tempnode2 = list->next;
tempnode2->next = tempnode1;
tempnode1->next = NULL;
return(tempnode2);
}
}
}
else
{
// The size of the linked list is more than 2.
// Need to split this linked list, sort the
// left and right sub-linked lists and merge.
// Split.
// tempnode1 will have the first half of the linked list of size "size1".
// tempnode2 will have the second half of the linked list of size "size2".
// Now merge the sorted lists back, let tempnode3 point to that new list.
<CODE TO MERGE THE 2 LINKED LISTS BACK INTO A SINGLE SORTED LINKED LIST>
return(tempnode3);
}
}
The code to merge the two already sorted sub-linked lists into a sorted linked list could be something
like this..
i = a;
j = b;
c = getNewNode();
k = getNewNode();
if(i!=NULL)
k->next=i;
else
k->next=j;
return(c->next);
struct node {
int value;
struct node *next;
};
typedef struct node *mynode;
typedef struct {
int value;
mynode next;
} *mynode;
The typedef is not defined at the point where the "next" field is declared.
struct node {
int value;
struct node next;
};
typedef struct node mynode;
You can only have pointer to structures, not the structure itself as its recursive!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char c[] = { 'a', 'b', 'c', 'd' };
int i[] = { 1, 2, 3, 4 };
char *str[] = { "hello1", "hello2", "hello3", "hello4" };
printf("Printing characters:");
print(list1, printchar);
printf(" : done\n\n");
printf("Printing integers:");
print(list2, printint);
printf(" : done\n\n");
printf("Printing strings:");
print(list3, printstr);
printf(" : done\n\n");
printf("Printing composite:");
print(list4, printcomp);
printf(" : done\n");
return 0;
}
while(current->next != NULL)
{
mynode *temp = head;
while(temp->next != NULL && temp != current)
{
if(current->next == temp)
{
printf("\nFound a loop.");
return current;
}
temp = temp->next;
}
current = current->next;
}
return NULL;
}
Visited flag
Have a visited flag in each node of the linked list. Flag it as visited when you reach the node. When
you reach a node and the flag is already flagged as visited, then you know there is a loop in the linked
list.
Fastest method
Have 2 pointers to start of the linked list. Increment one pointer by 1 node and the other by 2 nodes. If
there's a loop, the 2nd pointer will meet the 1st pointer somewhere. If it does, then you know there's
one.
p=head;
q=head->next;
// No loop.
8)How do you find the middle of a linked list? Write a C program to return the middle of a
linked list
Here are a few C program snippets to give you an idea of the possible solutions.
Method1
p=head;
q=head;
if(q->next->next!=NULL)
{
p=p->next;
q=q->next->next;
}
Here p moves one step, where as q moves two steps, when q reaches end, p will be at the middle of the
linked list.
Method2
return middle;
}
In a similar way, we can find the 1/3 th node of linked list by changing (i%2==1) to (i%3==1) and in
the same way we can find nth node of list by changing (i%2==1) to (i%n==1) but make sure ur (n<=i).
9)If you are using C language to implement the heterogeneous linked list, what pointer type will
you use?
The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to
connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void
pointer is capable of storing pointer to any type as it is a generic pointer type.
10)How to compare two linked lists? Write a C program to compare two linked lists.
Here is a simple C program to accomplish the same.
11)How to create a copy of a linked list? Write a C program to create a copy of a linked list.
Check out this C program which creates an exact copy of a linked list.
Do you know what exactly makes the binary search on an array so fast and efficient? Its the ability to
access any element in the array in constant time. This is what makes it so fast. You can get to the
middle of the array just by saying array[middle]!. Now, can you do the same with a linked list? The
answer is No. You will have to write your own, possibly inefficient algorithm to get the value of the
middle node of a linked list. In a linked list, you loosse the ability to get the value of any node in a
constant time.
Here is a C program which explains a different way of coding the atoi() function in the C language.
#include<stdioi.h>
int main()
{
printf("\n%d\n", myatoi("1998"));
getch();
return(0);
}
}
return(i);
}
Try working it out with a small string like "1998", you will find out it does work!.
This can be done either by going from right to left or left to right in the string
if (string)
{
while (*string && (*string <= '9' && *string >= '0'))
{
value = (value * 10) + (*string - '0');
string++;
}
}
return value;
}
15)Implement the memmove() function. What is the difference between the memmove() and
memcpy() function?
memmove() offers guaranteed behavior if the source and destination arguments overlap. memcpy()
makes no such guarantee, and may therefore be more efficient to implement. It's always safer to use
memmove().
This is a very elaborate implementation of memmove(). It also has C code which proves that the results
are the same irrespective of the Endian-ness of the machine. Check out this C program...
/* ------------------------------------------------------
* memmove() implementation
* ----------------------------------------------------*/
#include<stdio.h>
int main()
{
/* ----------------------------------------
*
* CASE 1 : From (SRC) < To (DEST)
*
* +--+---------------------+--+
* | | | |
* +--+---------------------+--+
* ^ ^
* | |
* From To
*
* --------------------------------------- */
p1 = (char *) calloc(1,12);
size=10;
strcpy(p1,"ABCDEFGHI");
p2 = p1 + 2;
printf("\n--------------------------------\n");
printf("\nFrom (before) = [%s]",p1);
printf("\nTo (before) = [%s]",p2);
mymove(p1,p2,size);
printf("\n--------------------------------\n");
/* ----------------------------------------
*
* CASE 1 : From (SRC) > To (DEST)
*
* +--+---------------------+--+
* | | | |
* +--+---------------------+--+
* ^ ^
* | |
* To From
*
* --------------------------------------- */
p3 = (char *) calloc(1,12);
p4 = p3 + 2;
strcpy(p4, "ABCDEFGHI");
printf("\n--------------------------------\n");
printf("\n\n");
return(0);
}
if(from==to)
{
printf("\n\nNothing to copy!\n");
}
else if(from>to)
{
diff=from-to;
if(diff>size)
{
printf("\nThe memories dont overlap, can use memcpy() here!\n");
}
for(i=diff;i<=size+diff-1;i++)
{
printf("\n->Copying from[%d] -> to[%d]",
(i-diff),
(i-diff));
to[i-diff] = from[(i-diff)];
}
}
else
{
diff=to-from;
if(diff>size)
{
printf("\nThe memories dont overlap, can use memcpy() here!\n");
}
for(i=size+diff-1;i>=diff;i--)
{
printf("\n->Copying from[%d] -> to[%d]",
(i-diff),
(i-diff));
to[(i-diff)] = from[(i-diff)];
}
}
}
--------------------------------
From (before) = [ABCDEFGHI]
To (before) = []
--------------------------------
--------------------------------
So whats the difference between the implementation of memmove() and memcpy(). Its just that
memcpy() will not care if the memories overlap and will either copy from left to right or right to left
without checking which method to used depending on the type of the overlap.
There are a number of ways to find a string inside another string. Its important to be aware of these
algorithms than to memorize them. Some of the fastest algorithms are quite tough to understand!.
Method1
The first method is the classic Brute force method. The Brute Force algorithm checks, at all positions
in the text between 0 and (n-m), if an occurrence of the pattern starts at that position or not. Then, after
each successfull or unsuccessful attempt, it shifts the pattern exactly one position to the right. The time
complexity of this searching phase is O(mn). The expected number of text character comparisons is 2n.
Here 'n' is the size of the string in which the substring of size 'm' is being searched for.
#include<stdio.h>
/* Searching */
for (j = 0; j <= (n - m); ++j)
{
for (i = 0; i < m && x[i] == y[i + j]; ++i);
if (i >= m) {printf("\nMatch found at\n\n->[%d]\n->[%s]\n",j,y+j);}
}
}
int main()
{
char *string = "hereroheroero";
char *pattern = "hero";
BF(pattern,strlen(pattern),string,strlen(string));
printf("\n\n");
return(0);
}
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
|||| ----> Match!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
Method2
Instead of checking at each position of the text if the pattern occurs or not, it is better to check first if
the contents of the current string "window" looks like the pattern or not. In order to check the
resemblance between these two patterns, a hashing function is used. Hashing a string involves
computing a numerical value from the value of its characters using a hash function.
The Rabin-Karp method uses the rule that if two strings are equal, their hash values must also be equal.
Note that the converse of this statement is not always true, but a good hash function tries to reduce the
number of such hash collisions. Rabin-Karp computes hash value of the pattern, and then goes through
the string computing hash values of all of its substrings and checking if the pattern's hash value is equal
to the substring hash value, and advancing by 1 character every time. If the two hash values are the
same, then the algorithm verifies if the two string really are equal, rather than this being a fluke of the
hashing scheme. It uses regular string comparison for this final check. Rabin-Karp is an algorithm of
choice for multiple pattern search. If we want to find any of a large number, say k, fixed length
patterns in a text, a variant Rabin-Karp that uses a hash table to check whether the hash of a given
string belongs to a set of hash values of patterns we are looking for. Other algorithms can search for a
single pattern in time order O(n), hence they will search for k patterns in time order O(n*k). The
variant Rabin-Karp will still work in time order O(n) in the best and average case because a hash table
allows to check whether or not substring hash equals any of the pattern hashes in time order of O(1).
hashing_function()
{
// A hashing function to compute the hash values of the strings.
....
}
printf("\nstring : [%s]"
"\nlength : [%d]"
"\npattern : [%s]"
"\nlength : [%d]\n\n", y,n,x,m);
/* Preprocessing phase */
Do preprocessing here..
/* Searching */
j = 0;
while (j <= n-m)
{
if (hx == hy && memcmp(x, y + j, m) == 0)
{
// Hashes match and so do the actual strings!
printf("\nMatch found at : [%d]\n",j);
}
int main()
{
char *string="hereroheroero";
char *pattern="hero";
KarpRabin(pattern,strlen(pattern),string,strlen(string));
printf("\n\n");
return(0);
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
|||| ----> Hash values match, so do the strings!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
Method3
The Knuth-Morris-Pratt or the Morris-Pratt algorithms are extensions of the basic Brute Force
algorithm. They use precomputed data to skip forward not by 1 character, but by as many as possible
for the search to succeed.
Here is some code
while (i < m)
{
while (j > -1 && x[i] != x[j])
j = Next[j];
Next[++i] = ++j;
}
}
/* Preprocessing */
preComputeData(x, m, Next);
/* Searching */
i = j = 0;
while (j < n)
{
while (i > -1 && x[i] != y[j])
i = Next[i];
i++;
j++;
if (i >= m)
{
printf("\nMatch found at : [%d]\n",j - i);
i = Next[i];
}
}
}
int main()
{
char *string="hereroheroero";
char *pattern="hero";
MorrisPrat(pattern,strlen(pattern),string,strlen(string));
printf("\n\n");
return(0);
}
This is how the comparison happens visually
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
|||| ----> Match found!
hero
hereroheroero
!
hero
Method4
The Boyer Moore algorithm is the fastest string searching algorithm. Most editors use this algorithm.
It compares the pattern with the actual string from right to left. Most other algorithms compare from
left to right. If the character that is compared with the rightmost pattern symbol does not occur in the
pattern at all, then the pattern can be shifted by m positions behind this text symbol.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b b a d a b a c b a
| |
b a b a c |
<------ |
|
b a b a c
The comparison of "d" with "c" at position 4 does not match. "d" does not occur in the pattern.
Therefore, the pattern cannot match at any of the positions 0,1,2,3,4, since all corresponding windows
contain a "d". The pattern can be shifted to position 5. The best case for the Boyer-Moore algorithm
happens if, at each search attempt the first compared character does not occur in the pattern. Then the
algorithm requires only O(n/m) comparisons .
This method is called bad character heuristics. It can also be applied if the bad character (the character
that causes a mismatch), occurs somewhere else in the pattern. Then the pattern can be shifted so that it
is aligned to this text symbol. The next example illustrates this situation.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b b a b a b a c b a
|
b a b a c
<----
|
b a b a c
Comparison between "b" and "c" causes a mismatch. The character "b" occurs in the pattern at
positions 0 and 2. The pattern can be shifted so that the rightmost "b" in the pattern is aligned to "b".
Sometimes the bad character heuristics fails. In the following situation the comparison between "a" and
"b" causes a mismatch. An alignment of the rightmost occurence of the pattern symbol a with the text
symbol a would produce a negative shift. Instead, a shift by 1 would be possible. However, in this case
it is better to derive the maximum possible shift distance from the structure of the pattern. This method
is called good suffix heuristics.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b a a b a b a c b a
| | |
c a b a b
<----
| | |
c a b a b
The suffix "ab" has matched. The pattern can be shifted until the next occurence of ab in the pattern is
aligned to the text symbols ab, i.e. to position 2.
In the following situation the suffix "ab" has matched. There is no other occurence of "ab" in the
pattern.Therefore, the pattern can be shifted behind "ab", i.e. to position 5.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b c a b a b a c b a
| | |
c b a a b
c b a a b
In the following situation the suffix "bab" has matched. There is no other occurence of "bab" in the
pattern. But in this case the pattern cannot be shifted to position 5 as before, but only to position 3,
since a prefix of the pattern "ab" matches the end of "bab". We refer to this situation as case 2 of the
good suffix heuristics.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a a b a b a b a c b a
| | | |
a b b a b
a b b a b
The pattern is shifted by the longest of the two distances that are given by the bad character and the
good suffix heuristics.
The Boyer-Moore algorithm uses two different heuristics for determining the maximum possible shift
distance in case of a mismatch: the "bad character" and the "good suffix" heuristics. Both heuristics can
lead to a shift distance of m. For the bad character heuristics this is the case, if the first comparison
causes a mismatch and the corresponding text symbol does not occur in the pattern at all. For the good
suffix heuristics this is the case, if only the first comparison was a match, but that symbol does not
occur elsewhere in the pattern.
#include<stdio.h>
#include<stdarg.h>
main()
{
void myprintf(char *,...);
char * convert(unsigned int, int);
int i=65;
char str[]="This is my string";
myprintf("\nMessage = %s%d%x",str,i,i);
}
char *p;
int i;
unsigned u;
char *s;
va_list argp;
va_start(argp, fmt);
p=fmt;
for(p=fmt; *p!='\0';p++)
{
if(*p=='%')
{
putchar(*p);continue;
}
p++;
switch(*p)
{
case 'c' : i=va_arg(argp,int);putchar(i);break;
case 'd' : i=va_arg(argp,int);
if(i<0){i=-i;putchar('-');}puts(convert(i,10));break;
case 'o': i=va_arg(argp,unsigned int); puts(convert(i,8));break;
case 's': s=va_arg(argp,char *); puts(s); break;
case 'u': u=va_arg(argp,argp, unsigned int); puts(convert(u,10));break;
case 'x': u=va_arg(argp,argp, unsigned int); puts(convert(u,16));break;
case '%': putchar('%');break;
}
}
va_end(argp);
}
ptr=&buf[sizeof(buff)-1];
*ptr='\0';
do
{
*--ptr="0123456789abcdef"[num%base];
num/=base;
}while(num!=0);
return(ptr);
}
Method1
Method2
int main()
{
char str1[] = "India";
char str2[25];
file_path_from = "<something>";
file_path_to = "<something_else>";
if (!feof(f_from)){exit(1);}
return(0);
}
A-Z - 65-90
a-z - 97-122
Note that these routines dont have much error handling incorporated in them.
toupper()
toupper(ch)
{
if(ch>='a' && c<='z')
return('A' + ch - 'a');
else
return(ch);
}
isupper()
boolean isupper(ch)
{
if(ch>='A' && ch <='Z')
return(TRUE);
else
return(FALSE);
}
while(*p!='\0')
p++;
return(p-s);
}
int a,b,t;
t = a;
a = b;
b = t;
There is no way better than this as you will find out soon. There are a few slick expressions that do
swap variables without using temporary storage. But they come with their own set of problems.
Although the code above works fine for most of the cases, it tries to modify variable 'a' two times
between sequence points, so the behavior is undefined. What this means is it wont work in all the
cases. This will also not work for floating-point values. Also, think of a scenario where you have
written your code like this
Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess
what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up
setting the variable to zero (ideally it should have swapped the variable with itself). This scenario is
quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to
some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be
swapped are already equal to each other.
Method2
a=a+b;
b=a-b;
a=a-b;
But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this
might end up giving you wrong results.
Method3
One can also swap two variables using a macro. However, it would be required to pass the type of the
variable to the macro. Also, there is an interesting problem using macros. Suppose you have a swap
macro which looks something like this
int temp;
temp=temp;
temp=b;
b=temp;
Which means it sets the value of "b" to both the variables!. It never swapped them! Scary, isn't it?
So the moral of the story is, dont try to be smart when writing code to swap variables. Use a temporary
variable. Its not only fool proof, but also easier to understand and maintain.
Suppose we have an array t[8] which keeps track of which column is occupied in which row of the
chess board. That is, if t[0]==5, then it means that the queen has been placed in the fifth column of the
first row. We need to couple the backtracking algorithm with a procedure that checks whether the tuple
is completable or not, i.e. to check that the next placed queen 'i' is not menaced by any of the already
placed 'j' (j < i):
#include<stdio.h>
static int t[10]={-1};
void queens(int i);
int empty(int i);
void print_solution();
int main()
{
queens(1);
print_solution();
return(0);
}
void queens(int i)
{
for(t[i]=1;t[i]<=8;t[i]++)
{
if(empty(i))
{
if(i==8)
{
print_solution();
/* If this exit is commented, it will show ALL possible combinations */
exit(0);
}
else
{
// Recurse!
queens(i+1);
}
}// if
}// for
}
int empty(int i)
{
int j;
j=1;
return((i==j)?1:0);
}
void print_solution()
{
int i;
for(i=1;i<=8;i++)printf("\nt[%d] = [%d]",i,t[i]);
}
t[1] = [1] // This means the first square of the first row.
t[2] = [5] // This means the fifth square of the second row.
t[3] = [8] ..
t[4] = [6] ..
t[5] = [3] ..
t[6] = [7] ..
t[7] = [2] ..
t[8] = [4] // This means the fourth square of the last row.
>-----------+
|
+---->--+ |
| | |
| | |
| <---+ |
| |
+-----------+
#include<stdio.h>
/* HELICAL MATRIX */
int main()
{
int arr[][4] = { {1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13, 14, 15, 16}
};
int i, j, k,middle,size;
printf("\n\n");
size = 4;
middle = (size-1)/2;
if (size % 2 == 1) printf("%d", arr[middle][middle]);
printf("\n\n");
return 1;
}
Also note that there is a similar question about reversing the words in a sentence, but still keeping the
words in place. That is
I am a good boy
would become
boy good a am I
This is dealt with in another question. Here I only concentrate on reversing strings. That is
I am a good boy
would become
yob doog a ma I
#include <stdio.h>
if(pos<(strlen(str)/2))
{
char ch;
// Now recurse!
reverse(pos+1);
}
}
Method2
Method4
Method5
public static String reverse(String s)
{
int N = s.length();
char[] a = new char[N];
for (int i = 0; i < N; i++)
a[i] = s.charAt(N-i-1);
String reverse = new String(a);
return reverse;
}
I am a good boy
boy good a am I
I really dont know what is the use of this!, but its still asked. Here are a few sample C programs for
your reference....
Method1
First reverse the whole string and then individually reverse the words
I am a good boy
<------------->
yob doog a ma I
<-> <--> <-> <-> <->
boy good a am I
Method2
Now its a simple question of reversing the linked list!. There are plenty of algorithms to reverse a
linked list easily. This also keeps track of the number of spaces between the words.
30)Write a C program generate permutations.
Iterative C program
#include <stdio.h>
#define SIZE 3
int main(char *argv[],int argc)
{
char list[3]={'a','b','c'};
int i,j,k;
for(i=0;i<SIZE;i++)
for(j=0;j<SIZE;j++)
for(k=0;k<SIZE;k++)
if(i!=j && j!=k && i!=k)
printf("%c%c%c\n",list[i],list[j],list[k]);
return(0);
}
Recursive C program
#include <stdio.h>
#define N 5
if(k==m)
{
/* PRINT A FROM k to m! */
for(i=0;i<N;i++){printf("%c",list[i]);}
printf("\n");
}
else
{
for(i=k;i<m;i++)
{
/* swap(a[i],a[m-1]); */
temp=list[i];
list[i]=list[m-1];
list[m-1]=temp;
permute(list,k,m-1);
/* swap(a[m-1],a[i]); */
temp=list[m-1];
list[m-1]=list[i];
list[i]=temp;
}
}
}
fact(n)
{
int fact;
if(n==1)
return(1);
else
fact = n * fact(n-1);
return(fact);
}
#include<stdio.h>
#define TRUE 1
#define FALSE 0
int main()
{
char *string = "hereheroherr";
char *pattern = "*hero*";
if(wildcard(string, pattern)==TRUE)
{
printf("\nMatch Found!\n");
}
else
{
printf("\nMatch not found!\n");
}
return(0);
}
You are given a large array X of integers (both positive and negative) and you need to find the
maximum sum found in any contiguous subarray of X.
There are various methods to solve this problem, some are listed below
Brute force
maxSum = 0
for L = 1 to N
{
for R = L to N
{
sum = 0
for i = L to R
{
sum = sum + X[i]
}
maxSum = max(maxSum, sum)
}
}
O(N^3)
Quadratic
Note that sum of [L..R] can be calculated from sum of [L..R-1] very easily.
maxSum = 0
for L = 1 to N
{
sum = 0
for R = L to N
{
sum = sum + X[R]
maxSum = max(maxSum, sum)
}
}
Using divide-and-conquer
O(N log(N))
maxSum(L, R)
{
if L > R then
return 0
if L = R then
return max(0, X[L])
M = (L + R)/2
sum = 0; maxToLeft = 0
for i = M downto L do
{
sum = sum + X[i]
maxToLeft = max(maxToLeft, sum)
}
sum = 0; maxToRight = 0
for i = M to R do
{
sum = sum + X[i]
maxToRight = max(maxToRight, sum)
}
int main()
{
int i,j,k;
int maxSum, sum;
/*---------------------------------------
* CUBIC - O(n*n*n)
*---------------------------------------*/
maxSum = 0;
for(i=0; i<N; i++)
{
for(j=i; j<N; j++)
{
sum = 0;
for(k=i ; k<j; k++)
{
sum = sum + list[k];
}
maxSum = (maxSum>sum)?maxSum:sum;
}
}
/*-------------------------------------
* Quadratic - O(n*n)
* ------------------------------------ */
maxSum = 0;
for(i=0; i<N; i++)
{
sum=0;
for(j=i; j<N ;j++)
{
sum = sum + list[j];
maxSum = (maxSum>sum)?maxSum:sum;
}
}
/*----------------------------------------
* Divide and Conquer - O(nlog(n))
* -------------------------------------- */
return(0);
}
int maxSubSum(int left, int right)
{
int mid, sum, maxToLeft, maxToRight, maxCrossing, maxInA, maxInB;
int i;
if(left>right){return 0;}
if(left==right){return((0>list[left])?0:list[left]);}
mid = (left + right)/2;
sum=0;
maxToLeft=0;
for(i=mid; i>=left; i--)
{
sum = sum + list[i];
maxToLeft = (maxToLeft>sum)?maxToLeft:sum;
}
sum=0;
maxToRight=0;
for(i=mid+1; i<=right; i++)
{
sum = sum + list[i];
maxToRight = (maxToRight>sum)?maxToRight:sum;
}
35)How to generate fibonacci numbers? How to find out if a given number is a fibonacci number or
not? Write C programs to do both.
int fib(int n)
{
int f[n+1];
f[1] = f[2] = 1;
int fib(int n)
{
if (n <= 2) return 1
else return fib(n-1) + fib(n-2)
}
Here is an iterative way to just compute and return the nth number (without storing the previous
numbers).
int fib(int n)
{
int a = 1, b = 1;
for (int i = 3; i <= n; i++)
{
int c = a + b;
a = b;
b = c;
}
return a;
}
There are a few slick ways to generate fibonacci numbers, a few of them are listed below
Method1
n
[ 1 1 ] = [ F(n+1) F(n) ]
[ 1 0 ] [ F(n) F(n-1) ]
or
or
n
(f(0) f(1)) [ 0 1 ] = (f(n) f(n+1))
[ 1 1 ]
The n-th power of the 2 by 2 matrix can be computed efficiently in O(log n) time. This implies an
O(log n) algorithm for computing the n-th Fibonacci number.
int fib(int n)
{
matrixpower(n-1);
return Matrix[0][0];
}
void matrixpower(int n)
{
if (n > 1)
{
matrixpower(n/2);
Matrix = Matrix * Matrix;
}
if (n is odd)
{
Matrix = Matrix * {{1,1}{1,0}}
}
}
#include<stdio.h>
int M[2][2]={{1,0},{0,1}};
int A[2][2]={{1,1},{1,0}};
int C[2][2]={{0,0},{0,0}}; // Temporary matrix used for multiplication.
int main()
{
int n;
n=6;
matMul(n-1);
void matMul(int n)
{
if(n>1)
{
matMul(n/2);
mulM(0); // M * M
}
if(n%2!=0)
{
mulM(1); // M * {{1,1}{1,0}}
}
}
void mulM(int m)
{
int i,j,k;
if(m==0)
{
// C = M * M
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
C[i][j]=0;
for(k=0;k<2;k++)
C[i][j]+=M[i][k]*M[k][j];
}
}
else
{
// C = M * {{1,1}{1,0}}
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
C[i][j]=0;
for(k=0;k<2;k++)
C[i][j]+=A[i][k]*M[k][j];
}
}
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
M[i][j]=C[i][j];
}
}
Method2
The cumbersome way is to generate fibonacci numbers till this number and see if this number is one of
them. But there is another slick way to check if a number is a fibonacci number or not.
To check if a number is a perfect square or not, one can take the square root, round it to the nearest
integer and then square the result. If this is the same as the original whole number then the original was
a perfect square.
This is one of the classical problems of computer science. There is a rat trapped in a maze. There are
multiple paths in the maze from the starting point to the ending point. There is some cheese at the exit.
The rat starts from the entrance of the maze and wants to get to the cheese.
111111111111111111111
100000000000000000001
100000010000000000001
100000010000000000001
100000000100001000001
100001000010000000001
100000000100000000001
100000000000000000001
111111111111111111111
· The rat can move in four directions at any point in time (well, right, left, up, down). Please
note that the rat can't move diagonally. Imagine a real maze and not a matrix. In matrix
language
· Moving right means adding {0,1} to the current coordinates.
· Moving left means adding {0,-1} to the current coordinates.
· Moving up means adding {-1,0} to the current coordinates.
· Moving right means adding {1,0} to the current coordinates.
· The rat can start off at the first row and the first column as the entrance point.
· From there, it tries to move to a cell which is currently free. A cell is free if it has a zero in it.
· It tries all the 4 options one-by-one, till it finds an empty cell. If it finds one, it moves to that
cell and marks it with a 1 (saying it has visited it once). Then it continues to move ahead from
that cell to other cells.
· If at a particular cell, it runs out of all the 4 options (that is it cant move either right, left, up
or down), then it needs to backtrack. It backtracks till a point where it can move ahead and be
closer to the exit.
· If it reaches the exit point, it gets the cheese, ofcourse.
· The complexity is O(m*m).
findpath()
{
Position offset[4];
Offset[0].row=0; offset[0].col=1;//right;
Offset[1].row=1; offset[1].col=0;//down;
Offset[2].row=0; offset[2].col=-1;//left;
Offset[3].row=-1; offset[3].col=0;//up;
Position here;
Here.row=1;
Here.col=1;
maze[1][1]=1;
int option = 0;
int lastoption = 3;
while(here.row!=m || here.col!=m)
{
//Find a neighbor to move
int r,c;
while (option<=LastOption)
{
r=here.row + offset[position].row;
c=here.col + offset[option].col;
if(maze[r][c]==0)break;
option++;
}
37)What Little-Endian and Big-Endian? How can I determine whether a machine's byte order is big-
endian or little endian? How can we convert from one to another?
Little Endian means that the lower order byte of the number is stored in memory at the lowest address,
and the higher order byte is stored at the highest address. That is, the little end comes first.
Base_Address+0 Byte0
Base_Address+1 Byte1
Base_Address+2 Byte2
Base_Address+3 Byte3
"Big Endian" means that the higher order byte of the number is stored in memory at the lowest address,
and the lower order byte at the highest address. The big end comes first.
Base_Address+0 Byte3
Base_Address+1 Byte2
Base_Address+2 Byte1
Base_Address+3 Byte0
In "Little Endian" form, code which picks up a 1, 2, 4, or longer byte number proceed in the same way
for all formats. They first pick up the lowest order byte at offset 0 and proceed from there. Also,
because of the 1:1 relationship between address offset and byte number (offset 0 is byte 0), multiple
precision mathematic routines are easy to code. In "Big Endian" form, since the high-order byte comes
first, the code can test whether the number is positive or negative by looking at the byte at offset zero.
Its not required to know how long the number is, nor does the code have to skip over any bytes to find
the byte containing the sign information. The numbers are also stored in the order in which they are
printed out, so binary to decimal routines are particularly efficient.
int num = 1;
if(*(char *)&num == 1)
{
printf("\nLittle-Endian\n");
}
else
{
printf("Big-Endian\n");
}
return((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | (byte3 << 0));
}
main()
{
towers_of_hanio(n,'L','R','C');
}
char *myfunction(int n)
{
char buffer[20];
sprintf(buffer, "%d", n);
return retbuf;
}
char *myfunc1()
{
char temp[] = "string";
return temp;
}
char *myfunc2()
{
char temp[] = {'s', 't', 'r', 'i', 'n', 'g', '\0'};
return temp;
}
int main()
{
puts(myfunc1());
puts(myfunc2());
}
The returned pointer should be to a static buffer (like static char buffer[20];), or to a buffer passed in
by the caller function, or to memory obtained using malloc(), but not to a local array.
char *myfunc()
{
char *temp = "string";
return temp;
}
int main()
{
puts(someFun());
}
So will this
calling_function()
{
char *string;
return_string(&string);
printf(?\n[%s]\n?, string);
}
40)Write a C program which produces its own source code as its output
41)Write a C progam to convert from decimal to any base (binary, hex, oct etc...)
#include <stdio.h>
int main()
{
decimal_to_anybase(10, 2);
decimal_to_anybase(255, 16);
getch();
}
while(n)
{
m=n%base;
digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m];
n=n/base;
i++;
}
Even this is one of the most frequently asked interview questions. I really dont know whats so great in
it. Nevertheless, here is a C program
Method1
Method2
if(((~i+1)&i)==i)
{
//Power of 2!
}
return(m);
}
max = ((a>b)?a:b)>c?((a>b)?a:b):c;
This is one of the very popular interview questions, so take a good look at it!.
myfunction(int *ptr)
{
int myvar = 100;
ptr = &myvar;
}
main()
{
int *myptr;
myfunction(myptr);
Arguments in C are passed by value. The called function changed the passed copy of the pointer, and
not the actual pointer.
Method1
Pass in the address of the pointer to the function (the function needs to accept a pointer-to-a-pointer).
calling_function()
{
char *string;
return_string(/* Pass the address of the pointer */&string);
printf(?\n[%s]\n?, string);
}
Method2
char *myfunc()
{
char *temp = "string";
return temp;
}
int main()
{
puts(myfunc());
}
48)Write C code to dynamically allocate one, two and three dimensional arrays (using malloc())
Its pretty simple to do this in the C language if you know how to use C pointers. Here are some
example C code snipptes....
Method1
Method3
int *myarray = malloc(no_of_rows * no_of_columns * sizeof(int));
main()
{
int ***p,i,j;
p=(int ***) malloc(MAXX * sizeof(int ***));
for(i=0;i<MAXX;i++)
{
p[i]=(int **)malloc(MAXY * sizeof(int *));
for(j=0;j<MAXY;j++)
p[i][j]=(int *)malloc(MAXZ * sizeof(int));
}
for(k=0;k<MAXZ;k++)
for(i=0;i<MAXX;i++)
for(j=0;j<MAXY;j++)
p[i][j][k]=<something>;
49)How would you find the size of structure without using sizeof()?
struct MyStruct
{
int i;
int j;
};
int main()
{
struct MyStruct *p=0;
int size = ((char*)(p+1))-((char*)p);
printf("\nSIZE : [%d]\nSIZE : [%d]\n", size);
return 0;
}
50)Write a C program to multiply two matrices.
Are you sure you know this? A lot of people think they already know this, but guess what? So take a
good look at this C program. Its asked in most of the interviews as a warm up question.
// Matrix A (m*n)
// Matrix B (n*k)
// Matrix C (m*k)
There a number of ways in which we can find out if a string is a palidrome or not. Here are a few
sample C programs...
Method1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
isPalindrome("avon sees nova");
isPalindrome("a");
isPalindrome("avon sies nova");
isPalindrome("aa");
isPalindrome("abc");
isPalindrome("aba");
isPalindrome("3a2");
exit(0);
}
if(string)
{
start = string;
end = string + strlen(string) - 1;
if(*start!=*end)
{
printf("\n[%s] - This is not a palidrome!\n", string);
}
else
{
printf("\n[%s] - This is a palidrome!\n", string);
}
}
printf("\n\n");
}
Method2
N = strlen(string);
end = N-1;
return(TRUE);
}
52)Write a C program to convert a decimal number into a binary number.
99% of the people who attend interviews can't answer this question, believe me!. Here is a C program
which does this....
#include<stdio.h>
generatebits(int num)
{
int temp;
if(num)
{
temp = num % 2;
bit(num >>= 1);
printf("%d",temp);
}
}
int main()
{
int num;
while(1)
{
scanf("Enter a number : %d",&num);
printf("\n\n");
generatebits(num);
}
getch();
return(0);
}
BinarySearch(a,n)
{
int left=0;
int right=n-1;
while(left<=right)
{
int middle=(left + right)/2;
if(x==a[middle])return(middle);
if(x>a[middle])left=middle+1;
else{right=middle-1;}
}
return(-1);
}
Complexity is O(log(n)).
return(sum);
}
p1 = h1->next;
while(p1!=h1)
{
x1 = p1->px;
y1 = p1->py;
cf1 = p1->cf;
p2 = h2->next;
while(p2 != h2)
{
x2 = p2->px;
y2 = p2->py;
cf2 = p2->cf;
p2 = p2->next;
if(p2 != h2)
{
// We found something in the second polynomial.
cf = cf1 + cf2;
p2->flag = 1;
if(cf!=0){h3=addNode(cf,x1,y1,h3);}
}
else
{
h3=addNode(cf,x1,y1,h3);
}
p1 = p1->next;
}//while
while(p2 != h2)
{
if(p2->flag==0)
{
h3=addNode(p2->cf, p2->px, p2->py, h3);
}
p2=p2->next;
}
return(h3);
}
56)Write a program to add two long positive numbers (each represented by linked lists).
Check out this simple implementation
carry = 0;
c1 = h1->next;
c2 = h2->next;
h3 = insertNode(digit, h3);
c1 = c1->next;
c2 = c2->next;
}
if(c1 != h1)
{
c = c1;
h = h1;
}
else
{
c = c2;
h = h2;
}
while(c != h)
{
sum = c->value + carry;
digit = sum % 10;
carry = sum / 10;
h3 = insertNode(digit, h3);
c = c->next;
}
if(carry==1)
{
h3 = insertNode(carry, h3);
}
return(h3);
}
57)How do you compare floating point numbers?
This is Wrong!.
double a, b;
if(a == b)
{
...
}
The above code might not work always. Thats because of the way floating point numbers are stored.
A good way of comparing two floating point numbers is to have a accuracy threshold which is relative
to the magnitude of the two floating point numbers being compared.
#include <math.h>
if(fabs(a - b) <= accurary_threshold * fabs(a))
There is a lot of material on the net to know how floating point numbers can be compared. Got for it if
you really want to understand.
The character '\r' is a carriage return without the usual line feed, this helps to overwrite the current line.
The character '\b' acts as a backspace, and will move the cursor one position to the left.
#include <stdio.h>
int main(void)
{
int old, new=3;
return 0;
}
Try this
#include <stdio.h>
int main(void)
{
char ch=0x34;
printf("\nThe exchanged value is %x",swap_nibbles(ch));
return 0;
}
Use
scanf("%[^\n]", address);
This question is also quite popular, because it has real practical uses, specially during patching when
version comparison is required
---------------------------------------------------------------------
compare_versions()
This function compare two versions in pl-sql language. This function can compare
Versions like 115.10.1 vs. 115.10.2 (and say 115.10.2 is greater), 115.10.1 vs.
115.10 (and say
115.10.1 is greater), 115.10 vs. 115.10 (and say both are equal)
---------------------------------------------------------------------
function compare_releases(release_1 in varchar2, release_2 in varchar2)
return boolean is
release_1_str varchar2(132);
release_2_str varchar2(132);
release_1_ver number;
release_2_ver number;
ret_status boolean := TRUE;
begin
return(ret_status);
end compare_releases;
Usage example
static char stamp[] = "***\nmodule " __FILE__ "\ncompiled " __TIMESTAMP__ "\n***";
...
int main()
{
...
...
}
Try
(num<<3 - num)
This is same as
num*8 - num = num * (8-1) = num * 7
This is a big string which I want to split at equal intervals, without caring about
the words.
Now, to split this string say into smaller strings of 20 characters each, try this
#define maxLineSize 20
split(char *string)
{
int i, length;
char dest[maxLineSize + 1];
i = 0;
length = strlen(string);
68)Is there a way to multiply matrices in lesser than o(n^3) time complexity?
Yes. Divide and conquer method suggests Strassen's matrix multiplication method to be used. If we
follow this method, the time complexity is O(n^2.81) times rather O(n^3) times.
Now, this guy called Strassen's somehow :) came up with a bunch of equations to calculate the 4
elements of the resultant matrix
If you are aware, the rudimentary matrix multiplication goes something like this
void matrix_mult()
{
for (i = 1; i <= N; i++)
{
for (j = 1; j <= N; j++)
{
compute Ci,j;
}
}
}
So, essentially, a 2x2 matrix multiplication can be accomplished using 8 multiplications. And the
complexity becomes
2^log 8 =2^3
Strassen showed that 2x2 matrix multiplication can be accomplished in 7 multiplications and 18
additions or subtractions. So now the complexity becomes
2^log7 =2^2.807
P1 = (A11+ A22)(B11+B22)
P2 = (A21 + A22) * B11
P3 = A11 * (B12 - B22)
P4 = A22 * (B21 - B11)
P5 = (A11 + A12) * B22
P6 = (A21 - A11) * (B11 + B12)
P7 = (A12 - A22) * (B21 + B22)
C11 = P1 + P4 - P5 + P7
C12 = P3 + P5
C21 = P2 + P4
C22 = P1 + P3 - P2 + P6
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("\nThe pointer is [%lu] bytes\n", sizeof (void *));
return (0);
}
This should show "4" incase of a 32-bit machine and "8" incase of a 64-bit machine.
70)Write a program to have the output go two places at once (to the screen and to a file also)
You can write a wrapper function for printf() which prints twice.
myprintf(...)
{
// printf(); -> To screen.
// write_to_file(); -> To file.
}
# include<stdio.h>
void main()
{
int num=123456;
int sum=0;
# include<stdio.h>
void main()
{
int num=123456;
int sum=0;
74)Write a program to merge two arrays in sorted order, so that if an integer is in both the arrays, it
gets added into the final array only once.
Try noting down the address of a local variable. Call another function with a local variable declared in
it and check the address of that local variable and compare!.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int local1;
stack(&local1);
exit(0);
}
SUM = A XOR B
CARRY = A AND B
On a wicked note, you can add two numbers wihtout using the + operator as follows
a - (- b)
:)
77)How to generate prime numbers? How to generate the next prime after a given prime?
This is a very vast subject. There are numerous methods to generate primes or to find out if a given
number is a prime number or not. Here are a few of them. I strongly recommend you to search on the
Internet for more elaborate information.
Brute Force
Test each number starting with 2 and continuing up to the number of primes we want to generate. We
divide each numbr by all divisors upto the square root of that number. If no factors are found, its a
prime.
Table method
Suppose we want to find all the primes between 1 and 64. We write out a table of these numbers, and
proceed as follows. 2 is the first integer greater than 1, so its obviously prime. We now cross out all
multiples of two. The next number we haven't crossed out is 3. We circle it and cross out all its
multiples. The next non-crossed number is 5, sp we circle it and cross all its mutiples. We only have to
do this for all numbers less than the square root of our upper limit, since any composite in the table
must have atleast one factor less than the square root of the upper limit. Whats left after this process of
elimination is all the prime numbers between 1 and 64.
78)Write a C program to find the depth or height of a tree.
tree_height(mynode *p)
{
if(p==NULL)return(0);
if(p->left){h1=tree_height(p->left);}
if(p=>right){h2=tree_height(p->right);}
return(max(h1,h2)+1);
}
The degree of the leaf is zero. The degree of a tree is the max of its element degrees. A binary tree of
height n, h > 0, has at least h and at most (2^h -1) elements in it. The height of a binary tree that
contains n, n>0, elements is at most n and atleast log(n+1) to the base 2.
n = (2^h - 1)
Here is some sample C code. The idea is to keep on moving till you hit the left most node in the tree
return(current->data);
}
On similar lines, to find the maximum value, keep on moving till you hit the right most node of the
tree.
84)Write a C program to create a mirror copy of a tree (left nodes become right and right nodes
become left)!
if(root==NULL)return(NULL);
temp->left = copy(root->right);
temp->right = copy(root->left);
return(temp);
}
This code will will only print the mirror of the tree
if (node==NULL)
{
return;
}
else
{
tree_mirror(node->left);
tree_mirror(node->right);
85)Write C code to return a pointer to the nth node of an inorder traversal of a BST.
mynode *root;
static ctr;
int main()
{
mynode *temp;
root = NULL;
printf("\n[%d]\n, temp->value);
return(0);
}
// Get the pointer to the nth inorder node in "nthnode"
void nthinorder(mynode *root, int n, mynode **nthnode)
{
static whichnode;
static found;
if(!found)
{
if(root)
{
nthinorder(root->left, n , nthnode);
if(++whichnode == n)
{
printf("\nFound %dth node\n", n);
found = 1;
*nthnode = root; // Store the pointer to the nth node.
}
nthinorder(root->right, n , nthnode);
}
}
}
inorder(mynode *root)
{
// Plain old inorder traversal
}
temp = malloc(sizeof(mynode));
temp->value = value;
temp->left = NULL;
temp->right = NULL;
if(root == NULL)
{
root = temp;
}
else
{
prev = NULL;
cur = root;
while(cur)
{
prev = cur;
cur = (value < cur->value)? cur->left : cur->right;
}
There seems to be an easier way to do this, or so they say. Suppose each node also has a weight
associated with it. This weight is the number of nodes below it and including itself. So, the root will
have the highest weight (weight of its left subtree + weight of its right subtree + 1). Using this data, we
can easily find the nth inorder node.
Note that for any node, the (weight of the leftsubtree of a node + 1) is its inorder rankin the tree!. Thats
simply because of how the inorder traversal works (left->root->right). So calculate the rank of each
node and you can get to the nth inorder node easily. But frankly speaking, I really dont know how this
method is any simpler than the one I have presented above. I see more work to be done here (calculate
thw weights, then calculate the ranks and then get to the nth node!).
Also, if (n > weight(root)), we can error out saying that this tree does not have the nth node you are
looking for.
86)Write C code to implement the preorder(), inorder() and postorder() traversals. Whats their time
complexities?
Preorder
preorder(mynode *root)
{
if(root)
{
printf("Value : [%d]", root->value);
preorder(root->left);
preorder(root->right);
}
}
Postorder
postorder(mynode *root)
{
if(root)
{
postorder(root->left);
printf("Value : [%d]", root->value);
postorder(root->right);
}
}
Inorder
inorder(mynode *root)
{
if(root)
{
inorder(root->left);
inorder(root->right);
printf("Value : [%d]", root->value);
}
}
if(root==NULL)return(NULL);
temp->left = copy(root->left);
temp->right = copy(root->right);
return(temp);
}
88)Write C code to check if a given binary tree is a binary search tree or not?
Here is a C program which checks if a given tree is a Binary Search Tree or not...
int isThisABST(struct node* mynode)
{
if (mynode==NULL) return(true);
if (node->left!=NULL && maxValue(mynode->left) > mynode->data)
return(false);
if (node->right!=NULL && minValue(mynode->right) <= mynode->data)
return(false);
if (!isThisABST(node->left) || !isThisABST(node->right))
return(false);
return(true);
}
1
2 3
5 6 7 8
1 2 3 5 6 7 8
Pseduocode
Level_order_traversal(p)
{
while(p)
{
Visit(p);
If(p->left)Q.Add(p->left);
If(p->right)Q.Add(p->right);
Delete(p);
}
}
· The node does not exist in the tree - In this case you have nothing to delete.
· The node to be deleted has no children - The memory occupied by this node must be freed
and either the left link or the right link of the parent of this node must be set to NULL.
· The node to be deleted has exactly one child - We have to adjust the pointer of the parent of
the node to be deleted such that after deletion it points to the child of the node being deleted.
· The node to be deleted has two children - We need to find the inorder successor of the node to
be deleted. The data of the inorder successor must be copied into the node to be deleted and a
pointer should be setup to the inorder successor. This inorder successor would have one or zero
children. This node should be deleted using the same procedure as for deleting a one child or a
zero child node. Thus the whole logic of deleting a node with two children is to locate the
inorder successor, copy its data and reduce the problem to a simple deletion of a node with one
or zero children.
Situation 1
100 (parent)
50 (cur == psuc)
20 80 (suc)
90
85 95
Situation 2
100 (parent)
50 (cur)
20 90
80
70 (suc)
75
72 76
if(head->left==NULL){printf("\nEmpty tree!\n");return(head);}
parent = head;
cur = head->left;
if(cur == NULL)
{
printf("\nItem to be deleted not found!\n");
return(head);
}
if(cur->left == NULL)
q = cur->right;
else if(cur->right == NULL)
q = cur->left;
else
{
// Obtain the inorder successor and its parent
psuc = cur;
cur = cur->left;
while(suc->left!=NULL)
{
psuc = suc;
suc = suc->left;
}
if(cur==psuc)
{
// Situation 1
suc->left = cur->right;
}
else
{
// Situation 2
suc->left = cur->left;
psuc->left = suc->right;
suc->right = cur->right;
}
q = suc;
if(parent->left == cur)
parent->left=q;
else
parent->rlink=q;
freeNode(cur);
return(head);
}
return(root);
}
Here is another way to do the same
count_leaf(root->right);
}
}
93)Write C code for iterative preorder, inorder and postorder tree traversals
No
Consider 2 trees below
Tree1
a
b
Tree 2
a
b
preorder = ab
postorder = ba
Preorder and postorder do not uniquely define a binary tree. Nor do preorder and level order (same
example). Nor do postorder and level order.
95)Construct a tree given its inorder and preorder traversal strings. Similarly construct a tree given its
inorder and post order traversal strings.
inorder = g d h b e i a f j c
preorder = a b d g h e i c f j
Scan the preorder left to right using the inorder sequence to separate left and right subtrees. For
example, "a" is the root of the tree; "gdhbei" are in the left subtree; "fjc" are in the right subtree. "b" is
the next root; "gdh" are in the left subtree; "ei" are in the right subtree. "d" is the next root; "g" is in the
left subtree; "h" is in the right subtree.
Scan postorder from right to left using inorder to separate left and right subtrees.
inorder = g d h b e i a f j c
postorder = g h d i e b j f c a
Tree root is "a"; "gdhbei" are in left subtree; "fjc" are in right subtree.
Scan level order from left to right using inorder to separate left and right subtrees.
inorder = g d h b e i a f j c
level order = a b c d e f g h i j
Tree root is "a"; "gdhbei" are in left subtree; "fjc" are in right subtree.
Here is some working code which creates a tree out of the Inorder and Postorder
traversals. Note that here the tree has been represented as an array. This really simplifies the whole
implementation.
A
B C
D E F G
That is, for every node at position j in the array, its left child will be stored at position (2*j) and right
child at (2*j + 1). The root starts at position 1.
#include<stdio.h>
#include<string.h>
#include<ctype.h>
/*-------------------------------------------------------------
* Algorithm
*
* Inorder And Preorder
* inorder = g d h b e i a f j c
* preorder = a b d g h e i c f j
* Scan the preorder left to right using the inorder to separate left
* and right subtrees. a is the root of the tree; gdhbei are in the
* left subtree; fjc are in the right subtree.
*------------------------------------------------------------*/
void copy_str(char dest[], char src[], int pos, int start, int end);
void print_t();
for(i=0;i<strlen(io);i++)
{
if(io[i]==po[0])
{
copy_str(t[1],io,1,i,i); // We have the root here
copy_str(t[2],io,2,0,i-1); // Its left subtree
copy_str(t[3],io,3,i+1,strlen(io)); // Its right subtree
print_t();
}
}
copy_str(t[2*j],t[j],2*j,0,posn-1);
copy_str(t[2*j+1],t[j],2*j+1,posn+1,strlen(t[j]));
copy_str(t[j],t[j],j,posn,posn);
print_t();
}
}
}
}
void copy_str(char dest[], char src[], int pos, int start, int end)
{
char mysrc[100];
strcpy(mysrc,src);
dest[0]='\0';
strncat(dest,mysrc+start,end-start+1);
if(pos>hpos)hpos=pos;
}
void print_t()
{
int i;
for(i=1;i<=hpos;i++)
{
printf("\nt[%d] = [%s]", i, t[i]);
}
printf("\n");
}
97)Given an expression tree, evaluate the expression and obtain a paranthesized form of the
expression.
infix_exp(p)
{
if(p)
{
printf("(");
infix_exp(p->left);
printf(p->data);
infix_exp(p->right);
printf(")");
}
}
if(isalnum(symbol))
st[k++] = temp;
else
{
temp->right = st[--k];
temp->left = st[--k];
st[k++] = temp;
}
}
return(st[--k]);
}
Evaluate a tree
switch(root->value)
{
case '+' : return(eval(root->left) + eval(root->right)); break;
case '-' : return(eval(root->left) - eval(root->right)); break;
case '/' : return(eval(root->left) / eval(root->right)); break;
case '*' : return(eval(root->left) * eval(root->right)); break;
case '$' : return(eval(root->left) $ eval(root->right)); break;
default : if(isalpha(root->value))
{
printf("%c = ", root->value);
scanf("%f", &num);
return(num);
}
else
{
return(root->value - '0');
}
}
}
A
B C
D E F G
That is, for every node at position i in the array, its left child will be stored at position (2*i) and right
child at (2*i + 1). The root starts at position 1.
Its
2^n - n
So, if there are 10 nodes, you will have (1024 - 10) = 1014 different trees!! Confirm it yourself with a
small number if you dont believe the formula.
101)A full N-ary tree has M non-leaf nodes, how many leaf nodes does it have?
M + (N ^ (n-1)) = (1 - (N ^ n)) / (1 - N)
Leaf nodes = M * (N - 1) + 1
A
B C D
E F G H I J K L M
Leaf nodes = M * (N - 1) + 1 = 4 * (3 - 1) + 1 = 9
102)Implement Breadth First Search (BFS) and Depth First Search (DFS)
BFS
{
Initialize Q to be a queue with v in it.
While (Q is not empty)
{
Delete a vertex w from the queue;
Let u be a vertex (if any) adjacent from w;
While (u)
{
if(u has not been labeled)
Add u to the queue;
Label u has reached;
U=next vertex that is adjacent from w;
}
}
}
DFS
{
int u = Begin(v);
while(u)
{
if(!reache[u])DFS(u);
u=nextVertex(v);
}
}
prev=NULL;
cur=root;
while(cur!=NULL)
{
prev=cur;
cur=(value<cur->value)?cur->left:cur->right;
}
Since traversing the three is the most frequent operation, a method must be devised to improve the
speed. This is where Threaded tree comes into picture. If the right link of a node in a tree is NULL, it
can be replaced by the address of its inorder successor. An extra field called the rthread is used. If
rthread is equal to 1, then it means that the right link of the node points to the inorder success. If its
equal to 0, then the right link represents an ordinary link connecting the right subtree.
struct node
{
int value;
struct node *left;
struct node *right;
int rthread;
}
temp = x->right;
if(x->rthread==1)return(temp);
while(temp->left!=NULL)temp = temp->left;
return(temp);
}
if(head->left==head)
{
printf("\nTree is empty!\n");
return;
}
temp = head;
for(;;)
{
temp = inorder_successor(temp);
if(temp==head)return;
printf("%d ", temp->value);
}
temp=getnode();
temp->info=item;
r=x->right;
x->right=temp;
x->rthread=0;
temp->left=NULL;
temp->right=r;
temp->rthread=1;
}
Function to find the inorder predecessor (for a left threaded binary three)
temp = x->left;
if(x->lthread==1)return(temp);
while(temp->right!=NULL)
temp=temp->right;
return(temp);
}
This is one of the most frequently asked interview questions of all times...
There are a number of ways to count the number of bits set in an integer. Here are some C programs to
do the same.
Method1
#include<stdio.h>
int main()
{
int num=10;
int ctr=0;
for(;num!=0;num>>=1)
{
if(num&1)
{
ctr++;
}
}
Method2
This is a slightly faster way of doing the same thing. Here the control goes into the while loop only as
many times as the number of bits set to 1 in the integer!.
#include<stdio.h>
int main()
{
int num=10;
int ctr=0;
while(num)
{
ctr++;
num = num & (num - 1); // This clears the least significant bit set.
}
Method3
This method is very popular because it uses a lookup table. This speeds up the computation. What it
does is it keeps a table which hardcodes the number of bits set in each integer from 0 to 256.
For example
0 - 0 Bit(s) set.
1 - 1 Bit(s) set.
2 - 1 Bit(s) set.
3 - 2 Bit(s) set.
...
106)What purpose do the bitwise and, or, xor and the shift operators serve?
Truth Table
-----------
0 AND 0 = 0
0 AND 1 = 0
1 AND 0 = 0
1 AND 1 = 1
x AND 0 = 0
x AND 1 = x
We use bitwise "and" to test if certain bit(s) are one or not. And'ing a value against a pattern with ones
only in the bit positions you are interested in will give zero if none of them are on, nonzero if one or
more is on. We can also use bitwise "and" to turn off (set to zero) any desired bit(s). If you "and" a
pattern against a variable, bit positions in the pattern that are ones will leave the target bit unchanged,
and bit positions in the pattern that are zeros will set the target bit to zero.
The OR operator
Truth Table
-----------
0 OR 0 = 0
0 OR 1 = 1
1 OR 0 = 1
1 OR 1 = 1
x OR 0 = x
x OR 1 = 1
Use bitwise "or" to turn on (set to one) desired bit(s).
0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
x XOR 0 = x
x XOR 1 = ~x
Use bitwise "exclusive or" to flip or reverse the setting of desired bit(s) (make it a one if it was zero or
make it zero if it was one).
Operators >> and << can be used to shift the bits of an operand to the right or left a desired number of
positions. The number of positions to be shifted can be specified as a constant, in a variable or as an
expression. Bits shifted out are lost. For left shifts, bit positions vacated by shifting always filled with
zeros. For right shifts, bit positions vacated by shifting filled with zeros for unsigned data type and
with copy of the highest (sign) bit for signed data type. The right shift operator can be used to achieve
quick multiplication by a power of 2. Similarly the right shift operator can be used to do a quick
division by power of 2 (unsigned types only). The operators >> and <<, dont change the operand at all.
However, the operators >>= and <=< also change the operand after doing the shift operations.
x << y - Gives value x shifted left y bits (Bits positions vacated by shift are
filled with zeros).
x <<= y - Shifts variable x left y bits (Bits positions vacated by shift are filled
with zeros).
For the right shift, All bits of operand participate in the shift. For unsigned
data type,
bits positions vacated by shift are filled with zeros. For signed data type, bits
positions
vacated by shift are filled with the original highest bit (sign bit). Right
shifting n bits
divides by 2 raise to n. Shifting signed values may fail because for negative
values the result never
gets past -1:
-5 >> 3 is -1 and not 0 like -5/8.
A simple C command line utility takes a series of command line options. The options are given to the
utility like this : <utility_name> options=[no]option1,[no]options2,[no]option3?... Write C code using
bitwise operators to use these flags in the code.
//Each option will have a bit reserved in the global_options_bits integer. The
global_options_bits
// integer will have a bit set or not set depending on how the option was specified
by the user.
// For example, if the user said nooption1, the bit for OPTION1 in
global_options_bits
// will be 0. Likewise, if the user specified option3, the bit for OPTION3 in
global_options_bits
// will be set to 1.
// Assume you have already parsed the command line option and that
// parsed_argument_without_no has option1 or option2 or option3 (depending on what
has
// been provided at the command line) and the variable negate_argument says if the
// option was negated or not (i.e, if it was option1 or nooption1)
if (negate_argument)
{
// Setting the bit for this particular option to 0 as the option has
// been negated.
action_mask= ~(OPTION1_BITPOS) & ALL_BITPOS;
tmp_action= tmp_action & action_mask;
}
else
{
//Setting the bit for this particular option to 1.
action_mask= (OPTION1_BITPOS);
tmp_action= tmp_action | action_mask;
}
//Now someone who wishes to check if a particular option was set or not can use the
// following type of code anywhere else in the code.
if(((global_options_bits & OPTION1_BITPOS) == OPTION1_BITPOS)
{
//Do processing for the case where OPTION1 was active.
}
else
{
//Do processing for the case where OPTION1 was NOT active.
}
Method1
int i;
Method2
In this method, we use a lookup table.
A Heap is an almost complete binary tree.In this tree, if the maximum level is i, then, upto the (i-1)th
level should be complete. At level i, the number of nodes can be less than or equal to 2^i. If the
number of nodes is less than 2^i, then the nodes in that level should be completely filled, only from left
to right.
The property of an ascending heap is that, the root is the lowest and given any other node i, that node
should be less than its left child and its right child. In a descending heap, the root should be the highest
and given any other node i, that node should be greater than its left child and right child.
To sort the elements, one should create the heap first. Once the heap is created, the root has the highest
value. Now we need to sort the elements in ascending order. The root can not be exchanged with the
nth element so that the item in the nth position is sorted. Now, sort the remaining (n-1) elements. This
can be achieved by reconstructing the heap for (n-1) elements.
heapsort()
{
n = array(); // Convert the tree into an array.
makeheap(n); // Construct the initial heap.
makeheap(n)
{
heapsize=n;
for(i=n/2; i>=1; i--)
keepheap(i);
}
keepheap(i)
{
l = 2*i;
r = 2*i + 1;
p = s[l];
q = s[r];
t = s[i];
m = s[largest];
if(largest != i)
{
swap(s[i], s[largest]);
keepheap(largest);
}
}
Both Merge-sort and Quick-sort have same time complexity i.e. O(nlogn). In merge sort the file a[1:n]
was divided at its midpoint into sub-arrays which are independently sorted and later merged. Whereas,
in quick sort the division into two sub-arrays is made so that the sorted sub-arrays do not need to be
merged latter.
while(i<=m)
c[k++]=a[i++];
while(j<=n)
c[k++]=a[j++];
}
113)Implement the bubble sort algorithm. How can it be improved? Write the code for selection sort,
quick sort, insertion sort.
To improvise this basic algorithm, keep track of whether a particular pass results in any swap or not. If
not, you can break out without wasting more cycles.
if(flag==0)break;
}
}
temp = a[pos];
a[pos] = a[i];
a[i] = temp;
}
}
key = a[low];
i = low + 1;
j = high;
while(1)
{
while(i < high && key >= a[i])i++;
if(i < j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
else
{
temp = a[low];
a[low] = a[j];
a[j] = temp;
return(j);
}
}
}
int main()
{
// Populate the array a
quicksort(a, 0, n - 1);
}
a[j + 1] = item;
}
}
The postfix "++" operator has higher precedence than prefix "*" operator. Thus, *p++ is same as *(p+
+); it increments the pointer p, and returns the value which p pointed to before p was incremented. If
you want to increment the value pointed to by p, try (*p)++.
115)What is a NULL pointer? How is it different from an unitialized pointer? How is a NULL pointer
defined?
A null pointer simply means "I am not allocated yet!" and "I am not pointing to anything yet!".
The C language definition states that for every available pointer type, there is a special value which is
called the null pointer. It is guaranteed to compare unequal to a pointer to any object or function.
A null pointer is very different from an uninitialized pointer. A null pointer does not point to any
object or function; but an uninitialized pointer can point anywhere.
There is usually a null pointer for each type of a pointer, and the internal values of these null pointers
for different pointer types may be different, its up to the compiler. The & operator will never yield a
null pointer, nor will a successful call to malloc() (malloc() does return a null pointer when it fails).
In this call to execl(), the last argument has been explicitly casted to force the 0 to be treated as a
pointer.
if(ptr){}
and
if(!ptr){}
Make sure you are able to distinguish between the following : the null pointer, the internal
representation of a null pointer, the null pointer constant (i.e, 0), the NULL macro, the ASCII null
character (NUL), the null string ("").
This error means that the program has written, through a null (probably because its an uninitialized)
pointer, to a location thats invalid.
More to come....
117)Does an array always get converted to a pointer? What is the difference between arr and &arr?
How does one declare a pointer to an entire array?
In C, the array and pointer arithmetic is such that a pointer can be used to access an array or to simulate
an array. What this means is whenever an array appears in an expression, the compiler automatically
generates a pointer to the array's first element (i.e, &a[0]).
Also, on a side note, the rule by which arrays decay into pointers is not applied recursively!. An array
of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer.
int myarray[NO_OF_ROWS][NO_OF_COLUMNS];
myfunc(myarray);
or
Since the called function does not allocate space for the array, it does not need to know the overall
size, so the number of rows, NO_OF_ROWS, can be omitted. The width of the array is still important,
so the column dimension
NO_OF_COLUMNS must be present.
An array is never passed to a function, but a pointer to the first element of the array is passed to the
function. Arrays are automatically allocated memory. They can't be relocated or resized later. Pointers
must be assigned to allocated memory (by using (say) malloc), but pointers can be reassigned and
made to point to other memory chunks.
In C, &arr yields a pointer to the entire array. On the other hand, a simple reference to arr returns a
pointer to the first element of the array arr. Pointers to arrays (as in &arr) when subscripted or
incremented, step over entire arrays, and are useful only when operating on arrays of arrays. Declaring
a pointer to an entire array can be done like int (*arr)[N];, where N is the size of the array.
Also, note that sizeof() will not report the size of an array when the array is a parameter to a function,
simply because the compiler pretends that the array parameter was declared as a
pointer and sizeof reports the size of the pointer.
Before ANSI C introduced the void * generic pointer, these casts were required because older
compilers used to return a char pointer.
int *myarray;
myarray = (int *)malloc(no_of_elements * sizeof(int));
But, under ANSI Standard C, these casts are no longer necessary as a void pointer can be assigned to
any pointer. These casts are still required with C++, however.
119)What does malloc() , calloc(), realloc(), free() do? What are the common problems with malloc()?
Is there a way to find out how much memory a pointer was allocated?
calloc(m, n) is also used to allocate memory, just like malloc(). But in addition, it also zero fills the
allocated memory area. The zero fill is all-bits-zero. calloc(m.n) is essentially equivalent to
p = malloc(m * n);
memset(p, 0, m * n);
The malloc() function allocates raw memory given a size in bytes. On the other hand, calloc() clears
the requested memory to zeros before return a pointer to it. (It can also compute the request size given
the size of the base data structure and the number of them desired.)
Any memory allocated using malloc() realloc() must be freed using free(). In general, for every call to
malloc(), there should be a corresponding call to free(). When you call free(), the memory pointed to
by the passed pointer is freed. However, the value of the pointer in the caller remains unchanged. Its a
good practice to set the pointer to NULL after freeing it to prevent accidental usage. The
malloc()/free() implementation keeps track of the size of each block as it is allocated, so it is not
required to remind it of the size when freeing it using free(). You can't use dynamically-allocated
memory after you free it.
Unfortunately there is no standard or portable way to know how big an allocated block is using the
pointer to the block!. God knows why this was left out in C.
Yes, it is!
120)What's the difference between const char *p, char * const p and char * const * p?
const char *p - Cannot change the value pointed to by p, but can change the pointer
p itself.
*p = 'A' is illegal.
p = "Hello" is legal.
const * char p - Cannot change the pointer p, but can change the value pointed to
by p.
*p = 'A' is legal.
p = "Hello" is illegal.
const char * const p - Cannot change the value pointed to by p nor the pointer.
Errata The question wrongly mentions char * const *p, which is not legal. Instead it should be const
char * const p. This will be corrected the next time the FAQ is updated.
The void data type is used when no other data type is appropriate. A void pointer is a pointer that may
point to any kind of object at all. It is used when a pointer must be specified but its type is unknown.
The compiler doesn't know the size of the pointed-to objects incase of a void * pointer. Before
performing arithmetic, convert the pointer either to char * or to the pointer type you're trying to
manipulate
122)What do Segmentation fault, access violation, core dump and Bus error mean?
The segmentation fault, core dump, bus error kind of errors usually mean that the program tried to
access memory it shouldn't have.
Probable causes are overflow of local arrays; improper use of null pointers; corruption of the malloc()
data structures; mismatched function arguments (specially variable argument functions like sprintf(),
fprintf(), scanf(), printf()).
For example, the following code is a sure shot way of inviting a segmentation fault in your program:
sprintf(buffer,
"%s %d",
"Hello");
So whats the difference between a bus error and a segmentation fault?
A bus error is a fatal failure in the execution of a machine language instruction resulting from the
processor
detecting an anomalous condition on its bus.
A bus error triggers a processor-level exception, which Unix translates into a "SIGBUS" signal,which
if not caught, will terminate the current process. It looks like a SIGSEGV, but the difference between
the two is that SIGSEGV indicates an invalid access to valid memory, while SIGBUS indicates an
access to an invalid address.
Bus errors mean different thing on different machines. On systems such as Sparcs a bus error occurs
when you access memory that is not positioned correctly.
int main(void)
{
char *c;
long int *i;
c = (char *) malloc(sizeof(char));
c++;
i = (long int *)c;
printf("%ld", *i);
return 0;
}
On Sparc machines long ints have to be at addresses that are multiples of four (because they are four
bytes long), while chars do not (they are only one byte long so they can be put anywhere). The
example code uses the char to create an invalid address, and assigns the long int to the invalid address.
This causes a bus error when the long int is dereferenced.
A segfault occurs when a process tries to access memory that it is not allowed to, such as the memory
at address 0 (where NULL usually points). It is easy to get a segfault, such as the following example,
which dereferences NULL.
#include < stdio.h>
int main(void)
{
char *p;
p = NULL;
putchar(*p);
return 0;
}
int *p[10];
int (*p)[10];
Its an scenario where the program has lost a reference to an area in the memory. Its a programming
term describing the loss of memory. This happens when the program allocates some memory but fails
to return it to the system
125)What are brk() and sbrk() used for? How are they different from malloc()?
brk() and sbrk() are the only calls of memory management in UNIX. For one value of the address,
beyond the last logical data page of the process, the MMU generates a segmentation violation interrupt
and UNIX kills the process. This address is known as the break address of a process. Addition of a
logical page to the data space implies raising of the break address (by a multiple of a page size).
Removal of an entry from the page translation table automatically lowers the break address.
Both calls return the old break address to the process. In brk(), the new break address desired needs to
be specified as the parameter. In sbrk(), the displacement (+ve or -ve) is the difference between the
new and the old break address. sbrk() is very similar to malloc() when it allocates memory (+ve
displacement).
malloc() is really a memory manager and not a memory allocator since, brk/sbrk only can do memory
allocations under UNIX. malloc() keeps track of occupied and free peices of memory. Each malloc
request is expected to give consecutive bytes and hence malloc selects the smallest free pieces that
satisfy a request. When free is called, any consecutive free pieces are coalesced into a large free piece.
These is done to avoid fragmentation.
realloc() can be used only with a preallocated/malloced/realloced memory. realloc() will automatically
allocate new memory and transfer maximum possible contents if the new space is not available. Hence
the returned value of realloc must always be stored back into the old pointer itself.
126)What is a dangling pointer? What are reference counters with respect to pointers?
A pointer which points to an object that no longer exists. Its a pointer referring to an area of memory
that has been deallocated. Dereferencing such a pointer usually produces garbage.
Using reference counters which keep track of how many pointers are pointing to this memory location
can prevent such issues. The reference counts are incremented when a new pointer starts to point to the
memory location and decremented when they no longer need to point to that memory. When the
reference count reaches zero, the memory can be safely freed. Also, once freed, the corresponding
pointer must be set to NULL.
Since addresses are always whole numbers, pointers always contain whole numbers.
Yes
*(*(p+i)+j) == p[i][j].
So is
129)What operations are valid on pointers? When does one get the Illegal use of pointer in function
error?
px<py
px>=py
px==py
px!=py
px==NULL
px=px+n
px=px-n
px-py
Something like
j = j * 2;
k = k / 2;
The extern in a function's declaration is sometimes used to indicate that the function's definition is in
some other source file, but there is no difference between
and
int function_name();
You can pass pointers to locations which the function being called can populate, or have the function
return a structure containing the desired values, or use global variables.
Function overload is not present in C. In C, either use different names or pass a union of supported
types (with additional identifier that give hints of the type to be used).
Most people think its supported because they might unknowingly be using a C++ compiler to compile
their C code and C+= does have function overloading.
The inline comment is a request to the compiler to copy the code into the object at every place the
function is called. That is, the function is expanded at each point of call. Most of the advantage of
inline functions comes from avoiding the overhead of calling an actual function. Such overhead
includes saving registers, setting up stack frames, and so on. But with large functions the overhead
becomes less important. Inlining tends to blow up the size of code, because the function is expanded at
each point of call.
int myfunc(int a)
{
...
}
Inlined functions are not the fastest, but they are the kind of better than macros (which people use
normally to write small functions).
#define myfunc(a) \
{ \
... \
}
The problem with macros is that the code is literally copied into the location it was called from. So if
the user passes a "double" instead of an "int" then problems could occur. However, if this senerio
happens with an inline function the compiler will complain about incompatible types. This will save
you debugging time stage.
char *(*(*a[N])())();
138)Can we declare a function that can return a pointer to a function of the same type?
We cannot do it directly. Either have the function return a generic function pointer, with casts to adjust
the types as the pointers are passed around; or have it return a structure containing only a pointer to a
function returning that structure.
139)How can I write a function that takes a variable number of arguments? What are the limitations
with this? What is vprintf()?
The header stdarg.h provides this functionality. All functions like printf(), scanf() etc use this
functionality.
The program below uses a var_arg type of function to count the overall length of strings passed to the
function.
#include <stdarg.h>
length = strlen(first_argument);
while((p = va_arg(argp, char *)) != NULL)
{
length = length + strlen(p);
}
va_end(argp);
return(length);
}
int main()
{
int length;
length = myfunction("Hello","Hi","Hey!",(char *)NULL);
return(0);
}
Any function which takes a variable number of arguments must be able to determine from the
arguments themselves, how many of them there have been passed. printf() and some similar functions
achieve this by looking for the format string. This is also why these functions fail badly if the format
string does not match the argument list. Another common technique, applicable when the arguments
are all of the same type, is to use a sentinel value (often 0, -1, or an appropriately-cast null pointer) at
the end of the list. Also, one can pass an explicit count of the number of variable arguments. Some
older compilers did provided a nargs() function, but it was never portable.
Is this allowed?
int f(...)
{
...
}
No! Standard C requires at least one fixed argument, in part so that you can hand it to va_start().
va_arg(argp, float);
va_arg(argp, double)
Similarly, use
va_arg(argp, int)
How can I create a function which takes a variable number of arguments and passes them to some
other function (which takes a variable number of arguments)?
You should provide a version of that other function which accepts a va_list type of pointer.
So how can I call a function with an argument list built up at run time?
There is no portable way to do this. Instead of an actual argument list, you might want to pass an array
of generic (void *) pointers. The called function can then step through the array, much like main()
steps through char *argv[].
Below, the myerror() function prints an error message, preceded by the string "error: " and terminated
with a newline:
#include <stdio.h>
#include <stdarg.h>
void myerror(char *fmt, ...)
{
va_list argp;
fprintf(stderr, "error: ");
va_start(argp, fmt);
vfprintf(stderr, fmt, argp);
va_end(argp);
fprintf(stderr, "\n");
}
140)With respect to function parameter passing, what is the difference between call-by-value and call-
by-reference? Which method does C use?
In the case of call-by-reference, a pointer reference to a variable is passed into a function instead of the
actual value. The function's operations will effect the variable in a global as well as local sense. Call-
by-value (C's method of parameter passing), by contrast, passes a copy of the variable's value into the
function. Any changes to the variable made by function have only a local effect and do not alter the
state of the variable passed into the function.
No.
C uses pass by value, but it can pretend doing pass by reference, by having functions that have pointer
arguments and by using the & operator when calling the function. This way, the compiler will simulate
this feature (like when you pass an array to a function, it actually passes a pointer instead). C does not
have something like the formal pass by reference or C++ reference parameters.
141)If I have the name of a function in the form of a string, how can I invoke that function?
struct
{
char *name;
int (*func_ptr)();
} func_table[] = {"myfunc1", myfunc1,
"myfunc2", myfunc2,};
Search the table for the name, and call via the associated function pointer.
If there is no declaration in scope then it is assumed to be declared as returning an int and without any
argument type information. This can lead to discrepancies if the function is later declared or defined.
Such functions must be declared before they are called. Also check if there is another function in some
header file with the same name.
143)How can I pass the variable argument list passed to one function to another function.
Good question
#include <stdarg.h>
main()
{
display("Hello", 4, 12, 13, 14, 44);
}
display(char *s,...)
{
show(s,...);
}
show(char *t,...)
{
va_list ptr;
int a;
va_start(ptr,t);
a = va_arg(ptr, int);
printf("%f", a);
}
#include <stdarg.h>
main()
{
display("Hello", 4, 12, 13, 14, 44);
}
display(char *s,...)
{
va_list ptr;
va_start(ptr, s);
show(s,ptr);
}
144)How do I pass a variable number of function pointers to a variable argument (va_arg) function?
#include <stdarg.h>
main()
{
int (*p1)();
int (*p2)();
int fun1(), fun2();
p1 = fun1;
p2 = fun2;
display("Bye", p1, p2);
}
display(char *s,...)
{
int (*pp1)(), (*pp2)();
va_list ptr;
typedef int (*f)(); //This typedef is very important.
va_start(ptr,s);
pp1 = va_arg(ptr, f); // va_arg(ptr, int (*)()); would NOT have worked!
pp2 = va_arg(ptr, f);
(*pp1)();
(*pp2)();
}
fun1()
{
printf("\nHello!\n");
}
fun2()
{
printf("\nHi!\n");
}
It wont if the prototpe is around. It will ideally scream out with an error like
or
#include <stdio.h>
/*
int foo(int a);
int foo2(int a, int b);
*/
int main(int a)
{
int (*fp)(int a);
a = foo();
a = foo2(1);
exit(0);
}
int foo(int a)
{
return(a);
}
What this means is that the right hand side of the expression is not evaluated if the left hand side
determines the outcome. That is if the left hand side is true for || or false for &&, the right hand side is
not evaluated.
Although its surprising that an expression like i=i+1; is completely valid, something like a[i]=i+1; is
not. This is because all accesses to an element must be to change the value of that variable. In the
statement a[i]=i+1; , the access to i is not for itself, but for a[i] and so its invalid. On similar lines, i=i+
+; or i=++i; are invalid. If you want to increment the value of i, use i=i+1; or i+=1; or i++; or ++i; and
not some combination.
A sequence point is a state in time (just after the evaluation of a full expression, or at the ||, &&, ?:, or
comma operators, or just before a call to a function) at which there are no side effects.
Between the previous and next sequence point an object shall have its stored
value modified at most once by the evaluation of an expression. Furthermore,
the prior value shall be accessed only to determine the value to be stored.
148)Does the ?: (ternary operator) return a lvalue? How can I assign a value to the output of the
ternary operator?
Try doing something like this if you want to assign a value to the output of this operator
*((mycondition) ? &var1 : &var2) = myexpression;
Yes!
But frankly, this feature is of no use to anyone. Anyone asking this question is more or less a fool
trying to be cool.
The directive provides a single, well-defined "escape hatch" which can be used for all sorts of
(nonportable) implementation-specific controls and extensions: source listing control, structure
packing, warning suppression (like lint's old /* NOTREACHED */ comments), etc.
For example
#pragma once
inside a header file is an extension implemented by some preprocessors to help make header files
idempotent (to prevent a header file from included twice).
Nothing!. But, it's a good trick to prevent the common error of writing
if(x = 0)
The error above is the source of a lot of serious bugs and is very difficult to catch. If you cultivate the
habit of writing the constant before the ==, the compiler will complain if you accidentally type
if(0 = x)
You should use gotos wherever it suits your needs really well. There is nothing wrong in using them.
Really.
There are cases where each function must have a single exit point. In these cases, it makes much sense
to use gotos.
myfunction()
{
if(error_condition1)
{
// Do some processing.
goto failure;
}
if(error_condition2)
{
// Do some processing.
goto failure;
}
success:
return(TRUE);
failure:
// Do some cleanup.
return(FALSE);
}
Also, a lot of coding problems lend very well to the use of gotos. The only argument against gotos is
that it can make the code a little un-readable. But if its commented properly, it works quite fine.
Any good compiler will and should generate identical code for ++i, i += 1, and i = i + 1. Compilers are
meant to optimize code. The programmer should not be bother about such things. Also, it depends on
the processor and compiler you are using. One needs to check the compiler's assembly language
output, to see which one of the different approcahes are better, if at all.
Note that speed comes Good, well written algorithms and not from such silly tricks.
An lvalue is an expression that could appear on the left-hand sign of an assignment (An object that has
a location). An rvalue is any expression that has a value (and that can appear on the right-hand sign of
an assignment).
The lvalue refers to the left-hand side of an assignment expression. It must always evaluate to a
memory location. The rvalue represents the right-hand side of an assignment expression; it may have
any meaningful combination of variables and constants.
Casting is a mechanism built into C that allows the programmer to force the conversion of data types.
This may be needed because most C functions are very particular about the data types they process. A
programmer may wish to override the default way the C compiler promotes data types.
A statement is a single C expression terminated with a semicolon. A block is a series of statements, the
group of which is enclosed in curly-braces.
The process by which the C compiler ensures that functions and operators use data of the appropriate
type(s). This form of check helps ensure the semantic correctness of the program.
struct salary
{
char empname[20];
struct
{
int dearness;
}
allowance;
}employee;
It is a reference to a variable or function before it is defined to the compiler. The cardinal rule of
structured languages is that everything must be defined before it can be used. There are rare occasions
where this is not possible. It is possible (and sometimes necessary) to define two functions in terms of
each other. One will obey the cardinal rule while the other will need a forward declaration of the
former in order to know of the former's existence.
161)What is the difference between the & and && operators and the | and || operators?
& and | are bitwise AND and OR operators respectively. They are usually used to manipulate the
contents of a variable on the bit level. && and || are logical AND and OR operators respectively. They
are usually used in conditionals
162)Is C case sensitive (ie: does C differentiate between upper and lower case letters)?
Yes, ofcourse!
No!
main()
{
int i=1;
while (i<=5)
{
printf("%d",i);
if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf("PP");
}
The following preprocessor directives are used for conditional compilation. Conditional compilation
allows statements to be included or omitted based on conditions at compile time.
#if
#else
#elif
#endif
#ifdef
#ifndef
In the following example, the printf statements are compiled when the symbol DEBUG is defined, but
not compiled otherwise
#ifdef DEBUG
printf( "x=%d\n" );
#endif...
y = ....;
#ifdef DEBUG
printf( "y=%d\n" );
#endif...
#if directive
Expression examples
#if 1
#if 0
#if ABE == 3
#if ZOO < 12
#if ZIP == 'g'
#if (ABE + 2 - 3 * ZIP) > (ZIP - 2)
#else directive
· #else marks the beginning of statement(s) to be compiled if the preceding #if or #elif
expression is zero (false)
· Statements following #else are bounded by matching #endif
Examples
#if OS = 'A'
system( "clear" );
#else
system( "cls" );
#endif
#elif directive
Examples
#if TST == 1
z = fn1( y );
#elif TST == 2
z = fn2( y, x );
#elif TST == 3
z = fn3( y, z, w );
#endif
...
#if ZIP == 'g'
rc = gzip( fn );
#elif ZIP == 'q'
rc = qzip( fn );
#else
rc = zip( fn );
#endif
· #ifdef is used to include or omit statements from compilation depending of whether a macro
name is defined or not.
· Often used to allow the same source module to be compiled in different environments (UNIX/
DOS/MVS), or with different options (development/production).
· #ifndef similar, but includes code when macro name is not defined.
Examples
#ifdef TESTENV
printf( "%d ", i );
#endif
#ifndef DOS
#define LOGFL "/tmp/loga.b";
#else
#define LOGFL "c:\\tmp\\log.b";
#endif
defined() operator
· defined(mac), operator is used with #if and #elif and gives 1 (true) if macro name mac is
defined, 0 (false) otherwise.
· Equivalent to using #ifdef and #ifndef, but many shops prefer #if with defined(mac) or !
defined(mac)
Examples
#if defined(TESTENV)
printf( "%d ", i );
#endif
#if !defined(DOS)
#define LOGFL "/tmp/loga.b";
#else
#define LOGFL "c:\\tmp\\log.b";
#endif
166)Can we use variables inside a switch statement? Can we use floating point numbers? Can we use
expressions?
No
The only things that case be used inside a switch statement are constants or enums. Anything else will
give you a
switch(i)
{
case "string1" : // Something;
break;
case "string2" : // Something;
break;
}
switch(i)
{
case 1: // Something;
break;
case 1*2+4: // Something;
break;
}
switch(i)
{
case 1: // Something;
break;
case t: // Something;
break;
}
Also note that the default case does not require a break; if and only if its at the end of the switch()
statement. Otherwise, even the default case requires a break;
167)What is more efficient? A switch() or an if() else()?
168)How to write functions which accept two-dimensional arrays when the width is not known before
hand?
It declares an array of size three, initialized with the three characters 'a', 'b', and 'c', without the usual
terminating '\0' character. The array is therefore not a true C string and cannot be used with strcpy,
printf %s, etc. But its legal.
No
Doing a++ is asking the compiler to change the base address of the array. This the only thing that the
compiler remembers about an array once its declared and it wont allow you to change the base address.
If it allows, it would be unable to remember the beginning of the array.
171)What is the difference between the declaration and the definition of a variable?
The definition is the one that actually allocates space, and provides an initialization value, if any.
There can be many declarations, but there must be exactly one definition. A definition tells the
compiler to set aside storage for the variable. A declaration makes the variable known to parts of the
program that may wish to use it. A variable might be defined and declared in the same statement.
Uninitialized variables declared with the "static" keyword are initialized to zero. Such variables are
implicitly initialized to the null pointer if they are pointers, and to 0.0F if they are floating point
numbers.
Local variables start out containing garbage, unless they are explicitly initialized.
Memory obtained with malloc() and realloc() is likely to contain junk, and must be initialized. Memory
obtained with calloc() is all-bits-0, but this is not necessarily useful for pointer or floating-point values
(This is in contrast to Global pointers and Global floating point numbers, which start as zeroes of the
right type).
No, C does not have a boolean variable type. One can use ints, chars, #defines or enums to achieve the
same in C.
#define TRUE 1
#define FALSE 0
An enum may be good if the debugger shows the names of enum constants when examining variables.
174)Where may variables be defined in C?
Outside a function definition (global scope, from the point of definition downward in the source code).
Inside a block before any statements other than variable declarations (local scope with respect to the
block).
175)To what does the term storage class refer? What are auto, static, extern, volatile, const classes?
This is a part of a variable declaration that tells the compiler how to interpret the variable's symbol. It
does not in itself allocate storage, but it usually tells the compiler how the variable should be stored.
This keyword provides a short-hand way to write variable declarations. It is not a true data typing
mechanism, rather, it is syntactic "sugar coating".
For example
mynode *ptr1;
· It makes the writing of complicated declarations a lot easier. This helps in eliminating a lot of
clutter in the code.
· It helps in achieving portability in programs. That is, if we use typedefs for data types that are
machine dependent, only the typedefs need to change when the program is ported to a new
platform.
· It helps in providing better documentation for a program. For example, a node of a doubly
linked list is better understood as ptrToList than just a pointer to a complicated structure.
177)What is the difference between constants defined through #define and the constant keyword?
A constant is similar to a variable in the sense that it represents a memory location (or simply, a value).
It is different from a normal variable, in that it cannot change it's value in the proram - it must stay for
ever stay constant. In general, constants are a useful because they can prevent program bugs and
logical errors(errors are explained later). Unintended modifications are prevented from occurring. The
compiler will catch attempts to reassign new values to constants.
Constants may be defined using the preprocessor directive #define. They may also be defined using the
const keyword.
#define ABC 5
and
There is also one good use of the important use of the const keyword. Suppose you want to make use
of some structure data in some function. You will pass a pointer to that structure as argument to that
function. But to make sure that your structure is readonly inside the function you can declare the
structure argument as const in function prototype. This will prevent any accidental modification of the
structure values inside the function.
These are used when you keyboard does not support some special characters
??= #
??( [
??) ]
??< {
??> }
??! |
??/ \
??' ^
??- ~
179)How are floating point numbers stored? Whats the IEEE format?
But note that when structures are passed, returned or assigned, the copying is done only at one level
(The data pointed to by any pointer fields is not copied!.
The only way to compare two structures is to write your own function that compares the structures
field by field. Also, the comparison should be only on fields that contain data (You would not want to
compare the next fields of each structure!).
A byte by byte comparison (say using memcmp()) will also fail. This is because the comparison might
fonder on random bits present in unused "holes" in the structure (padding used to keep the alignment of
the later fields correct). So a memcmp() of the two structure will almost never work. Also, any strings
inside the strucutres must be compared using strcmp() for similar reasons.
myfunction((struct mystruct){10,20});
183)How does one use fread() and fwrite()? Can we read/write structures to/from files?
A similat fread() invocation can read it back in. But, data files so written will not be portable (specially
if they contain floating point numbers). Also that if the structure has any pointers, only the pointer
values will be written, and they are most unlikely to be valid when read back in. One must use the
"rb/wb" flag when opening the files.
A more portable solution is to write code to write and read a structure, field-by-field, in a portable
(perhaps ASCII) way!. This is simpler to port and maintain.
184)Why do structures get padded? Why does sizeof() return a larger size?
Its common for structures to have external padding as well as internal padding. This is required to
ensure that alignment properties are preserved when an array of contiguous structures is allocated.
Even if the structure is not part of an array, the end padding remains, so that sizeof() can always return
a consistent size.
185)Can we determine the offset of a field within a structure and directly access that element?
If structpointer is a pointer to an instance of this structure, and field a is an int, its value can be set
indirectly with
To avoid wastage of memory in structures, a group of bits can be packed together into an integer and
its called a bit field.
struct tag-name
{
data-type name1:bit-length;
data-type name2:bit-length;
...
...
data-type nameN:bit-length;
}
A real example
struct student;
{
char name[30];
unsigned sex:1;
unsigned age:5;
unsigned rollno:7;
unsigned branch:2;
};
scanf("%d", &sex);
a[i].sex=sex;
There are some limitations with respect to these bit fields, however:
One can define the macro with a single, parenthesized "argument" which in the macro expansion
becomes the entire argument list, parentheses and all, for a function such as printf():
The caller must always remember to use the extra parentheses. Other possible solutions are to use
different macros depending on the number of arguments. C9X will introduce formal support for
function-like macros with variable-length argument lists. The notation ... will appear at the end of the
macro "prototype" (just as it does for varargs functions).
ANSI has introduced a well-defined token-pasting operator, ##, which can be used like this:
main()
{
int var12=100;
printf("%d",f(var,12));
}
O/P
100
Stringizing operator
main()
{
sum(a+b); // As good as printf("a+b = %f\n", a+b);
}
So what does the message "warning: macro replacement within a string literal" mean?
#define TRACE(var, fmt) printf("TRACE: var = fmt\n", var)
TRACE(i, %d);
gets expanded as
In other words, macro parameters were expanded even inside string literals and character constants.
Macro expansion is *not* defined in this way by K&R or by Standard C. When you do want to turn
macro arguments into
strings, you can use the new # preprocessing operator, along with string literal concatenation:
#define TRACE(var, fmt) printf("TRACE: " #var " = " #fmt "\n", var)
See and try to understand this special application of the strigizing operator!
#define Str(x) #x
#define Xstr(x) Str(x)
#define OP plus
char *opname = Xstr(OP); //This code sets opname to "plus" rather than "OP".
Example1
int main()
{
int x=4;
float a = 3.14;
char ch = 'A';
DEBUG(x, %d);
DEBUG(a, %f);
DEBUG(ch, %c);
}
outputs
DEBUG: x=4
DEBUG: y=3.140000
DEBUG: ch=A
Example2
int main()
{
int x=4, y=4, z=5;
int a=1, b=2, c=3;
PRINT(x,y,z);
PRINT(a,b,c);
}
#define PRINT(v1,v2,v3) printf("\n" #v1 "=%d" #v2 "=%d" #v3 "=%d", v1, v2, v3);
#define SQR(x) (x * x)
191)What should go in header files? How to prevent a header file being included twice? Whats wrong
with including more headers?
Generally, a header (.h) file should have (A header file need not have a .h extension, its just a
convention):
Put declarations / definitions in header files if they will be shared between several other files. If some
of the definitions / declarations should be kept private to some .c file, don;t add it to the header files.
How does one prevent a header file from included twice?. Including header files twice can lead to
multiple-definition errors.
There are two methods to prevent a header file from included twice
Method1
#ifndef HEADER_FILE
#define HEADER_FILE
...header file contents...
#endif
Method2
A line like
#pragma once
inside a header file is an extension implemented by some preprocessors to help make header files
idempotent (to prevent a header file from included twice).
So, what's the difference between #include <> and #include "" ?
The <> syntax is typically used with Standard or system-supplied headers, while "" is typically used
for a program's own header files. Headers named with <> syntax are searched for in one or more
standard places. Header files named with font class=announcelink>"" syntax are first searched for in
the "current directory," then (if not found) in the same standard places.
The limitation is only that identifiers be significant in the first six characters, not that they be restricted
to six characters in length.
193)How do stat(), fstat(), vstat() work? How to check whether a file exists?
The functions stat(), fstat(), lstat() are used to get the file status.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
These functions return information about the specified file. You do not need any access rights to the
file to get this information but you need search rights to all directories named in the path leading to the
file.
They all return a stat structure, which contains the following fields:
struct stat {
dev_t st_dev; /* device */
ino_t st_ino; /* inode */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device type (if inode device) */
off_t st_size; /* total size, in bytes */
unsigned long st_blksize; /* blocksize for filesystem I/O */
unsigned long st_blocks; /* number of blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last change */
};
Here is a small piece of code which returns the size of a file by accessing the st_size member of the stat
structure.
*file_size = stat_buffer.st_size;
return(TRUE);
}
Use functions like stat() as used above to find out if a file exits or not. Also, one can use fopen(). When
using fopen(), just open for reading and close immediately. If the file does not exists, fopen() will
given an error.
194)How can I insert or delete a line (or record) in the middle of a file?
195)How can I recover the file name using its file descriptor?
Have a wrapper around fopen() to remember the names of files as you open them.
196)How can I delete a file? How do I copy files? How can I read a directory in a C program?
Deleting a file
The Standard C Library function is remove(). If thats not there, use unlink().
Copying a file
Directly use system() to invoke the operating system's copy() utility, or open the source and destination
files, read characters or blocks of characters from the source file, and write them to the destination file.
Use the opendir() and readdir() functions, which are part of the POSIX standard and are available on
most Unix variants.
197)Whats the use of fopen(), fclose(), fprintf(), getc(), putc(), getw(), putw(), fscanf(), feof(), ftell(),
fseek(), rewind(), fread(), fwrite(), fgets(), fputs(), freopen(), fflush(), ungetc()?
fopen()
FILE *fp;
fp = fopen("filename","mode");
fp = fopen("data","r");
fp = fopen("results","w");
Modes
fclose(fp);
These functions are used to read/write different types of data to the stream.
putc(ch,fp);
c=getc(fp);
putw(integer, fp);
integer=getw(fp);
fprintf(), fscanf()
fprintf(fp,"control string",list);
fscanf(fp,"control string", list);
foef()
Position can be
0->start of file
1->current position
2->end of file
fread(), fwrite()
fwrite(&customer, sizeof(record),1,fp);
fread(&customer,sizeof(record),1,fp);
#include <stdio.h>
#include <conio.h>
int main()
{
FILE *f;
char buffer[1000];
f=fopen("E:\\Misc\\__Temp\\FileDrag\\Main.cpp","r");
if(f)
{
printf("\nOpenened the file!\n");
while(fgets(buffer,1000,f))
{
printf("(%d)-> %s\n",strlen(buffer),buffer);
}
}
fclose(f);
getch();
return(0);
}
The declaration char a[] asks for space for 7 characters and see that its known by the name "a". In
contrast, the declaration char *a, asks for a place that holds a pointer, to be known by the name "a".
This pointer "a" can point anywhere. In this case its pointing to an anonymous array of 7 characters,
which does have any name in particular. Its just present in memory with a pointer keeping track of its
location.
char *a = "string";
+-----+ +---+---+---+---+---+---+------+
| a: | *======> | s | t | r | i | n | g | '\0' |
+-----+ +---+---+---+---+---+---+------+
Pointer Anonymous array
It is curcial to know that a[3] generates different code depending on whether a is an array or a pointer.
When the compiler sees the expression a[3] and if a is an array, it starts at the location "a", goes three
elements past it, and returns the character there. When it sees the expression a[3] and if a is a pointer, it
starts at the location "a", gets the pointer value there, adds 3 to the pointer value, and gets the character
pointed to by that value.
If a is an array, a[3] is three places past a. If a is a pointer, then a[3] is three places past the memory
location pointed to by a. In the example above, both a[3] and a[3] return the same character, but the
way they do it is different!
200)How can I declare an array with only one element and still access elements beyond the first
element (in a valid fashion)?
struct mystruct {
int value;
int length;
char string[1];
};
Now, when allocating memory to the structure using malloc(), allocate more memory than what the
structure would normally require!. This way, you can access beyond string[0] (till the extra amount of
memory you have allocated, ofcourse).
But remember, compilers which check for array bounds carefully might throw warnings. Also, you
need to have a length field in the structure to keep a count of how big your one element array really
is :).
A cleaner way of doing this is to have a pointer instead of the one element array and allocate memory
for it seperately after allocating memory for the structure.
struct mystruct {
int value;
char *string; // Need to allocate memory using malloc() after allocating memory for
the strucure.
};
201)What is the difference between enumeration variables and the preprocessor #defines?
202)Whats the difference between gets() and fgets()? Whats the correct way to use fgets() when
reading a file?
Unlike fgets(), gets() cannot be told the size of the buffer it's to read into, so it cannot be prevented
from overflowing that buffer. As a general rule, always use fgets(). fgets() also takes in the size of the
buffer, so that the end of the array cannot be overwritten.
while(!feof(inp_file_ptr))
{
fgets(buffer, MAX_LINE_SIZE, inp_file_ptr);
fputs(buffer, out_file_ptr);
}
The code above will copy the last line twice! This is because, in C, end-of-file is only indicated after
an input routine has tried to read, and failed. We should just check the return value of the input routine
(in this case, fgets() will return NULL on end-of-file); often, you don't need to use feof() at all.
You cant!.
An asterisk in a scanf() format string means to suppress assignment. You may be able to use ANSI
stringizing and string concatenation to accomplish about the same thing, or you can construct the scanf
format string at run time.
Use sprintf()
Note!, since sprintf() is also a variable argument function, it fails badly if passed with wrong
arguments or if some of the arguments are missed causing segmentation faults. So be very careful
when using sprintf() and pass the right number and type of arguments to it!
206)Why should one use strncpy() and not strcpy()? What are the problems with strncpy()?
strcpy() is the cause of many bugs. Thats because programmers almost always end up copying more
data into a buffer than it can hold. To prevent this problem, strncpy() comes in handy as you can
specify the exact number of bytes to be copied.
But there are problems with strncpy() also. strncpy() does not always place a '\0' terminator in the
destination string. (Funnily, it pads short strings with multiple \0's, out to the specified length). We
must often append a '\0' to the destination string by hand. You can get around the problem by using
strncat() instead of strncpy(): if the destination string starts out empty, strncat() does what you
probably wanted strncpy() to do. Another possibility is sprintf(dest, "%.*s", n, source). When arbitrary
bytes (as opposed to strings) are being copied, memcpy() is usually a more appropriate function to use
than strncpy().
The strtok() function can be used to parse a string into tokens. The first call to strtok() should have the
string as its first argument. Subsequent calls should have the first argument set to NULL. Each call
returns a pointer to the next token, or NULL when no more tokens are found. If a token ends with a
delimiter, this delimiting character is overwritten with a "\0" and a pointer to the next character is
saved for the next call to strtok(). The delimiter string delim may be different for each call.
The strtok_r() function works the same as the strtok() function, but instead of using a static buffer it
uses a pointer to a user allocated char* pointer. This pointer must be the same while parsing the same
string.
An example
main()
{
char str[]="This is a test";
char *ptr[10];
char *p;
int i=1;
int j;
p=strtok(str," ");
if(p!=NULL)
{
ptr[0]=p;
while(1)
{
p=strtok(NULL, " ");
if(p==NULL)break;
else
{
ptr[i]=p;i++;
}
}
}
for(j=0;j<i;j++)
{
printf("\n%s\n", ptr[i]);
}
}
Some compilers leave out certain floating point support if it looks like it will not be needed. In
particular, the non-floating-point versions of printf() and scanf() save space by not including code to
handle %e, %f, and %g. It happens that Borland's heuristics for determining whether the program uses
floating point are insufficient, and the programmer must sometimes insert a dummy call to a floating-
point library function (such as sqrt(); any will do) to force loading of floating-point support.
209)Why do some people put void cast before each call to printf()?
printf() returns a value. Some compilers (and specially lint) will warn about return values not used by
the program. An explicit cast to (void) is a way of telling lint that you have decided to ignore the return
value from this specific function call. It's also common to use void casts on calls to strcpy() and
strcat(), since the return value is never used for anything useful.
For example
int i,j;
for(i=0;i<=10;i++)
{
j+=5;
assert(i<5);
}
If anytime during the execution, i gets a value of 0, then the program would break into the assertion
since the assumption that the programmer made was wrong.
alloca() allocates memory which is automatically freed when the function which called alloca() returns.
However, note that alloca() is not portable and its usage is not recommended.
213)Can you compare two strings like string1==string2? Why do we need strcmp()?
if(string1 == string2)
{
}
The == operator will end up comparing two pointers (that is, if they have the same address). It wont
compare the contents of those locations. In C, strings are represented as arrays of characters, and the
language never manipulates (assigns, compares, etc.) arrays as a whole.
if(strcmp(string1, string2) == 0)
{
int main()
or
int main(void)
or
or
struct mystruct {
int value;
struct mystruct *next;
}
main(argc, argv)
{ ... }
Here the missing semicolon after the structure declaration causes main to be misdeclared.
No.
Yes
main()
{
main();
}
218)What do the system calls fork(), vfork(), exec(), wait(), waitpid() do? Whats a Zombie process?
Whats the difference between fork() and vfork()?
The system call fork() is used to create new processes. It does not take any arguments and returns a
process ID. The purpose of fork() is to create a new process, which becomes the child process of the
caller (which is called the parent). After a new child process is created, both processes will execute the
next instruction following the fork() system call. We can distinguish the parent from the child by
testing the returned value of fork():
If fork() returns a negative value, the creation of a child process was unsuccessful. A call to fork()
returns a zero to the newly created child process and the same call to fork() returns a positive value
(the process ID of the child process) to the parent. The returned process ID is of type pid_t defined in
sys/types.h. Normally, the process ID is an integer. Moreover, a process can use function getpid() to
retrieve the process ID assigned to this process. Unix will make an exact copy of the parent's address
space and give it to the child. Therefore, the parent and child processes will have separate address
spaces. Both processes start their execution right after the system call fork(). Since both processes have
identical but separate address spaces, those variables initialized before the fork() call have the same
values in both address spaces. Since every process has its own address space, any modifications will be
independent of the others. In other words, if the parent changes the value of its variable, the
modification will only affect the variable in the parent process's address space. Other address spaces
created by fork() calls will not be affected even though they have identical variable names.
Trick question!
main()
{
fork();
fork();
}
· Stack Space: which is where local variables, function calls, etc. are stored.
· Environment Space: which is used for storage of specific environment variables.
· Program Pointer (counter) : PC.
· File Descriptors
· Variables
Undex unix, each sub directory under /proc corresponds to a running process (PID #). A ps provide
detailed information about processes running
R - Runnable.
S - Sleeping.
D - Un-interuptable sleep.
T - Stopped or Traced.
Z - Zombie Process.
There are two command to set a process's priority nice and renice.
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Running ls.....\n");
system("ls -lrt");
printf("Done.\n");
exit(0);
}
The exec() functions replace a current process with another created according to the arguments given.
#include <unistd.h>
char *env[];
int execl(const char *path, const char *arg0, ..., (char *)0);
int execv(const char *path, const char *argv[]);
int execlp(const char *path, const char *arg0, ..., (char *)0);
int execvp(const char *path, const char *argv[]);
int execle(const char *path, const char *arg0, ... , (char *)0, const char *env[]);
int execve(const char *path, const char *argv[], const char *env[]);
The program given by the path argument is used as the program to execute in place of what is currently
running. In the case of the execl() the new program is passed arguments arg0, arg1, arg2,... up to a null
pointer. By convention, the first argument supplied (i.e. arg0) should point to the file name of the file
being executed. In the case of the execv() programs the arguments can be given in the form of a
pointer to an array of strings, i.e. the argv array. The new program starts with the given arguments
appearing in the argv array passed to main. Again, by convention, the first argument listed should point
to the file name of the file being executed. The function name suffixed with a p (execlp() and
execvp())differ in that they will search the PATH environment variable to find the new program
executable file. If the executable is not on the path, and absolute file name, including directories, will
need to be passed to the function as a parameter. The global variable environ is available to pass a
value for the new program environment. In addition, an additional argument to the exec() functions
execle() and execve() is available for passing an array of strings to be used as the new program
environment.
execvp("ls", argv);
execve("/bin/ls", argv, env);
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
pid=fork();
switch(pid)
{
case -1: exit(1); // fork() error.
case 0: // Child process, can call exec here.
break;
default: // Parent.
break;
}
exit(0);
}
The call wait() can be used to determine when a child process has completed it's job and finished. We
can arrange for the parent process to wait untill the child finishes before continuing by calling wait().
wait() causes a parent process to pause untill one of the child processes dies or is stopped. The call
returns the PID of the child process for which status information is available. This will usually be a
child process which has terminated. The status information allows the parent process to determine the
exit status of the child process, the value returned from main or passed to exit. If it is not a null pointer
the status information will be written to the location pointed to by stat_loc. We can interrogate the
status information using macros defined in sys/wait.h.
Macro Definition
-----------------------------------------------------------------------------------
WIFEXITED(stat_val); Nonzero if the child is terminated normally
WEXITSTATUS(stat_val); If WIFEXITED is nonzero, this returns child exit code.
WIFSIGNALLED(stat_val); Nonzero if the child is terminated on an uncaught signal.
WTERMSIG(stat_val); If WIFSIGNALLED is nonzero, this returns a signal number.
WIFSTOPPED(stat_val); Nonzero if the child stopped on a signal.
WSTOPSIG(stat_val); If WIFSTOPPED is nonzero, this returns a signal number.
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void){
pid_t child_pid;
int *status=NULL;
if(fork()){
/* wait for child, getting PID */
child_pid=wait(status);
printf("I'm the parent.\n");
printf("My child's PID was: %d\n",child_pid);
} else {
printf("I'm the child.\n");
}
return 0;
}
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
int exit_code;
pid = fork();
switch(pid)
{
case -1: exit(1);
case 0: exit_code = 11; //Set the child exit process
break;
default: exit_code = 0;
break;
}
if (pid)
{
// This is the parent process
int status;
pid_t child_pid;
child_pid = wait(&status);
exit(exit_code);
}
When using fork() to create child processes it is important to keep track of these processes. For
instance, when a child process terminates, an association with the parent survives untill the parent
either terminates normally or calls wait(). The child process entry in the process table is not freed up
immediately. Although it is no longer active, the child process is still in the system because it's exit
code needs to be stored in the even the parent process calls wait(). The child process is at that point
referred to as a zombie process. Note, if the parent terminates abnormally then the child process gets
the process with PID 1, (init) as parent. (such a child process is often referred to as an orphan). The
child process is now a zombie. It is no longer running, it's origional parent process is gone, and it has
been inherited by init. It will remain in the process table as a zombie untill the next time the table is
processed. If the process table is long this may take a while. till init cleans them up. As a general rule,
program wisely and try to avoid zombie processes. When zobbies accumulate they eat up valuable
resources.
The waitpid() system call is another call that can be used to wait for child processes. This system call
however can be used to wait for a specific process to terminate.
#include <sys/types.h>
#include <sys/wait.h>
pit_t waitpid(pid_t pid, int *status, int options);
The pid argument specifies the PID of the particular child process to wait for. If it is a -1 then waitpid()
will return information to the child process. Status information will be written to the location pointed
to by status. The options argument enables us to change the behavior of waitpid(). A very usefull
oprion is WNOHANG which prevents the call to waitpid() from suspending the execution of the caller.
We can it to find out whether any child process has terminated and, if not, to continue.
In some cases, for example if the child process is a server or "daemon" ( a process expected to run all
the time in the background to deliver services such as mail forwarding) the parent process would not
wait for the child to finish. In other cases, e.g. running an interactive command where it is not good
design for the parent's and child's output to be mixed up into the same output stream, the parent
process, e.g. a shell program, would normally wait for the child to exit before continuing. If you run a
shell command with an ampersand as it's last argument, e.g. sleep 60 & the parent shell doesn't wait for
this child process to finish.
The system call vfork(), is a low overhead version of fork(), as fork() involves copying the entire
address space of the process and is therefore quite expensive. The basic difference between the two is
that when a new process is created with vfork(), the parent process is temporarily suspended, and the
child process might borrow the parent's address space. This strange state of affairs continues until the
child process either exits, or calls execve(), at which point the parent process continues. This means
that the child process of a vfork() must be careful to avoid unexpectedly modifying variables of the
parent process. In particular, the child process must not return from the function containing the vfork()
call, and it must not call exit() (if it needs to exit, it should use _exit(); actually, this is also true for the
child of a normal fork()).
However, since vfork() was created, the implementation of fork() has improved , most notably with the
introduction of `copy-on-write', where the copying of the process address space is transparently faked
by allowing both processes to refer to the same physical memory until either of them modify it. This
largely removes the justification for vfork(); indeed, a large proportion of systems now lack the
original functionality of vfork() completely. For compatibility, though, there may still be a vfork() call
present, that simply calls fork() without attempting to emulate all of the vfork() semantics.
222)What is a deadlock?
224)What is the difference between statically linked libraries and dynamically linked libraries (dll)?
Murphy's law states that "If something can go wrong, it will. So is the case with programming. Here
are a few things than can go wrong when coding in C.
Ofcourse, there is the mother of all things that can go wrong - Your logic!.
226)What is hashing?
A hash function maps a string (or some other data structure) to a bounded number (called the hash
bucket) which can more easily be used as an index in an array, or for performing repeated
comparisons.
A mapping from a potentially huge set of strings to a small set of integers will not be unique. Any
algorithm using hashing therefore has to deal with the possibility of collisions.
#include <stdio.h>
#define HASHSIZE 197
HT myHashTable[HASHSIZE];
int main()
{
initialize();
add(2);
add(2500);
add(199);
display_hash();
getch();
return(0);
}
int initialize()
{
int i;
for(i=0;i<HASHSIZE;i++)
myHashTable[i].llist=NULL;
return(1);
}
if(myHashTable[hashkey].llist==NULL)
{
//This hash bucket is empty, add the first element!
tempnode1 = malloc(sizeof(mynode));
tempnode1->value=value;
tempnode1->next=NULL;
myHashTable[hashkey].llist=tempnode1;
}
else
{
//This hash bucket already has some items. Add to it at the end.
//Check if this element is already there?
for(tempnode1=myHashTable[hashkey].llist;
tempnode1!=NULL;
tempnode3=tmpnode1,tempnode1=tempnode1->next)
{
if(tempnode1->value==value)
{
printf("\nThis value [%d] already exists in the Hash!\n", value);
return(1);
}
}
tempnode2 = malloc(sizeof(mynode));
tempnode2->value = value;
tempnode2->next=NULL;
tempnode3->next=tempnode2;
}
return(1);
}
int display_hash()
{
int i;
mynode *tempnode;
for(i=0;i<HASHSIZE;i++)
{
if(myHashTable[i].llist==NULL)
{
printf("\nmyHashTable[%d].llist -> (empty)\n",i);
}
else
{
printf("\nmyHashTable[%d].llist -> ",i);
for(tempnode=myHashTable[i].llist;tempnode!=NULL;tempnode=tempnode->next)
{
printf("[%d] -> ",tempnode->value);
}
printf("(end)\n");
}
if(i%20==0)getch();
}
return(0);
}
Hashkey : [2]
Hashkey : [136]
Hashkey : [2]
Hashkey : [2]
...
...
It means already written, compiled and linked together with our program at the time of linking.
A data structure is a way of organizing data that considers not only the items stored, but also their
relationship to each other. Advance knowledge about the relationship between data items allows
designing of efficient algorithms for the manipulation of data.
a b c d
e f g h
i j k l
Convert into 1D array by collecting elements by rows. Within a row elements are collected from left to
right.
Rows are collected from top to bottom. So, x[i][j] is mapped to position i*no_of_columns + j.
On similar lines, in column major representation, we store elements column wise. Here, x[i][j] is
mapped to position i + j * no_of_rows.
They are:
· Divide and conquer : For a function to compute on n inputs the divide and conquer strategy
suggests the inputs into a k distinct subsets, 1<k<=n, yielding k sub-problems. These sub-
problems must be solved and then a method must be found to combine the sub-solutions into a
solution of the whole. An example for this approach is "binary search" algorithm. The time
complexity of binary search algorithm is O(log n).
· The greedy method : The greedy method suggests that one can devise an algorithm that works
in stages, considering one input at a time. At each stage, a decision is made regarding whether a
particular input is an optimal solution. An example for solution using greedy method is
"knapsack problem". Greedy algorithms attempt not only to find a solution, but to find the ideal
solution to any given problem.
· Dynamic programming : Dynamic Programming is an algorithm design method that can be
used when the solution to a problem can be viewed as the result of a sequence of decisions. An
example for algorithm using dynamic programming is "multistage graphs". This class
remembers older results and attempts to use this to speed the process of finding new results.
· Back-tracking : Here if we reach a dead-end, we use the stack to pop-off the dead end and try
something else we had not tried before. The famous 8-queens problem uses back tracking.
Backtracking algorithms test for a solution, if one is found the algorithm has solved, if not it
recurs once and tests again, continuing until a solution is found.
· Branch and bound : Branch and bound algorithms form a tree of subproblems to the primary
problem, following each branch until it is either solved or lumped in with another branch.
234)What is the difference between the stack and the heap? Where are the different types of variables
of a program stored in memory?
This is a quite popular question. But I have never understood what exactly is the purpose of asking this
question. The memory map of a C program depends heavily on the compiler used.
During the execution of a C program, the program is loaded into main memory. This area is called
permanent storage area. The memory for Global variables and static variables is also allocated in the
permanent storage area. All the automatic variables are stored in another area called the stack. The free
memory area available between these two is called the heap. This is the memory region available for
dynamic memory allocation during the execution of a program.
+-----------------------+
| |
| Automatic Variables | --> Stack
| |
+-----------------------+
| |
| |
| Free Memory | --> Heap
| |
| |
+-----------------------+
| |
| Global Variables | --+--> Permanent storage area
| | |
+-----------------------+ |
| | |
| Program (Text) | --+
| |
+-----------------------+
236)What is infix, prefix, postfix? How can you convert from one representation to another? How do
you evaluate these expressions?
There are three different ways in which an expression like a+b can be represented.
Prefix (Polish)
+ab
Infix
a+b
Note than an infix expression can have parathesis, but postfix and prefix expressions are paranthesis
free expressions.
Conversion from infix to postfix
((A + (B - C) * D) ^ E + F)
To convert it to postfix, we add an extra special value ] at the end of the infix string and push [ onto
the stack.
((A + (B - C) * D) ^ E + F)]
--------->
We move from left to right in the infix expression. We keep on pushing elements onto the stack till we
reach a operand. Once we reach an operand, we add it to the output. If we reach a ) symbol, we pop
elements off the stack till we reach a corresponding { symbol. If we reach an operator, we pop off any
operators on the stack which are of higher precedence than this one and push this operator onto the
stack.
As an example
Is there a way to find out if the converted postfix expression is valid or not
Yes. We need to associate a rank for each symbol of the expression. The rank of an operator is -1 and
the rank of an operand is +1. The total rank of an expression can be determined as follows:
At any point of time, while converting an infix expression to a postfix expression, the rank of the
expression can be greater than or equal to one. If the rank is anytime less than one, the expression is
invalid. Once the entire expression is converted, the rank must be equal to 1. Else the expression is
invalid.
This is very similar to the method mentioned above, except the fact that we add the special value [ at
the start of the expression and ] to the stack and we move through the infix expression from right to
left. Also at the end, reverse the output expression got to get the prefix expression.
This is the same as postfix evaluation, the only difference being that we wont evaluate the expression,
but just present the answer. The scanning is done from left to right.
ABC-D*+
A(B-C)D*+
A((B-C)*D)+
A+((B-C)*D)
Convert from postfix expression to infix
The scanning is done from right to left and is similar to what we did above.
+A*-BCD
Reverse it
DCB-*A+
D(B-C)*A+
((B-C)*D)A+
A+((B-C)*D)
Most compilers recognized the file type by looking at the file extension.
You might also be able to force the compiler to ignore the file type by supplying compiler switch. In
MS VC++ 6, for example, the MSCRT defines a macro, __cplusplus. If you undefine that macro, then
the compiler will treat your code as C code. You don't define the __cplusplus macro. It is defined by
the compiler when compiling a C++ source. In MSVC6 there's a switch for the compiler, /Tc, that
forces a C compilation instead of C++.
1. Lexical analysis.
2. Syntactic analysis.
3. Sematic analysis.
4. Pre-optimization of internal representation.
5. Code generation.
6. Post optimization.
240)What are the different types of linkages?
241)What are the basics of http? What is the difference be http and https?