Posts

Showing posts from March, 2013

The Prisoners Black and White Hat Riddle

Problem : Suppose there are 4 prisoners named A, B, C, and Z. Prisoner Z is standing on one side of a wall, and prisoners A B and C are standing on the other side of the wall. Prisoners A, B, and C are all standing in a straight line facing right – so A can see prisoner B and C, and B can see prisoner C. This is what their arrangement looks like: Z | A B C Where the “|” represents a wall. The wall has no mirrors. So, prisoner Z can see the wall and nothing else. There are 2 white hats and 2 black hats and each prisoner has a hat on his head. Each prisoner can not see the color of his own hat, and can not remove the hat from his own head. But the prisoners do know that there are 2 white hats and 2 black hats among themselves. The prison guard says that if one of the prisoners can correctly guess the color of his hat then the prisoners will be set free and released. The puzzle for you is to figure out which prisoner would know the color of his own hat?And also discuss the vari

Program to find all the permutations of the string

#include<iostream> #include<conio.h> #include<string.h> using namespace std; void permutation(char *a, int i, int n) {    int j;    if (i == n)      printf("%s\n", a);    else    {         for (j = i; j <= n; j++)        {           swap((a[i]), (a[j]));           permute(a, i+1, n);           swap((a[i]), (a[j]));        }    } } void swap (char *x, char *y) {     char temp;     temp = *x;     *x = *y;     *y = temp; } int main() { char a[] = "ABCD";    permutation(a, 0, 3);    // start index-0 and last index-3 of an array    getch(); }

Program to separate positive and negative numbers in an array

#include<iostream> #include<conio.h> using namespace std; void separateposneg(int arr[10],int a) {     int j=0,b[10],count=0;  for(int i=0;i<a;i++)  {   if(arr[i]>0)   {   count++;   b[j]=arr[i];   j++;   } }  for(int i=0;i<a;i++)  {   if(arr[i]<0)   {     b[count]=arr[i];   count++;   }      } cout<<"The separated numbers are\n";  for(int j=0;j<a;j++)  {  cout<<b[j]<<"\n";        }  } int main() {     int ar[10],n;     cout<<"enter no of values\n";     cin>>n; cout<<"Enter array\n"; for(int i=0;i<n;i++) { cin>>ar[i]; } separateposneg(ar,n); getch(); } Input : 6 3 90 -2 6 -90 5 Output : 3 90 6 5 -2 -90

Program to print the numbers with Odd Occurences

#include<iostream> #include<conio.h> using namespace std; int main() { int a[10],b[10]; int n,c; cout<<"Enter the total numbers to be checked\n"; cin>>n; cout<<"Enter the numbers\n"; for(int i=0;i<n;i++) { cin>>a[i]; } for(int j=0;j<n;j++) { int count=0; if(a[j]==0) { c++; continue; } for(int k=j+1;k<n;k++) { if(a[j]==a[k]) { count++; a[k]=0; } } b[j-c]=count+1; if(b[j-c]%2!=0) cout<<"The numbers with odd occurence are\n"<<a[j]<<"\t"; } getch(); } Input : 8 3 3 3 4 4 6 7 7 Output : 3 6

Program to search the element in Sorted Rotated Pivoted array

Sorted Rotated Pivoted array means the sorted array is rotated through the pivot element.The element in a sorted array can be find using binary search in O(logn) time.But if the sorted array is rotated through some pivot element then how to search for an element in that array.Suppose take sorted array 1 2 3 4 5 it might become 3 4 5 1 2 after rotating at Pivot element 5.Pivot element can be found by the idea that the only element whose next element is smaller then pivot element in an array.So here is the program to find the element in a sorted rotated pivoted array. Our first task is to find a pivot element in an array.The above idea of  pivot element is used to find the pivot element in an array. int findpivot(int a[],int low,int high) { int mid=(low+high)/2; if(a[mid]>a[mid+1])        // if middle element is greater then its next element then it is pivot element as it is the                                                    only element whose next element is smaller the

Tricky Questions or Puzzles in C

This post is about the Tricky Questions   or code snippet in C or C++ asked in most of the Interviews   (See Interview Experience ) by some of the good companies. You may know probably the right concept but it will not strike you at the interview and to crack all those Interview Questions  you should know some of them beforehand. If you are applying for Job related to JAVA then checkout the blog post  Tricky Questions in JAVA . 1) what will be the output of the following Printf function.   printf("%d",printf("%d",printf("%d",printf("%s","ILOVECPROGRAM")))); Ans-ILOVECPROGRAM1321 The above printf line gives output like this because printf returns the number of character successfully written in the output. So the inner printf("%s","ILOVECPROGRAM") writes 13 characters to the output so the outer printf function will print 13 and as 13 is of 2 characters so the next outer printf function will print 2 and then

AVL Tree

Image
AVL Tree is often asked in interviews or coding rounds by some companies like Oracle and SAP.Though some people leave AVL trees thinking its not important,but you can never know what they might ask you in interview.So Its good to know about it.If not completely then at least some basic concepts. AVL Trees are Height Balanced binary search tree datastructure such that for every internal nodes the heights of the two child node differ by at most one.If the balanced is disturbed at any time re-balancing is to be done to again make it balanced.In AVL Tree searching,Insertion and Deletion takes O(logn) time.Insertion and Deletion may require to re-balance the tree using Tree rotation  . Let the height of last nodes be 1 the node above it be 2 and finally the root node be 4.You can see that the tree is balanced as the height of child nodes of internal nodes differ by the value of 1 or 0.Next we will discuss the Insertion of AVL Tree. Insertion : It is necessary to check the

Find the prime numbers between a range of numbers

Often this question is asked in interviews by companies and most of them apply the same old traditional method of finding prime numbers resulting in large complexity of the program. The proper solution for finding the prime numbers is the Sieve of Eratosthenes. Well, the algorithm is not so difficult, unlike its name. The basic principle here is to iteratively mark the multiples of unmarked numbers starting from 2 till the limit and then the numbers left out unmarked are primes numbers. Let's take a series of numbers starting from 2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25.............. Now lets mark multiples of 2 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25.............. Now mark multiples of 3 (Next unmarked) 2 3  4  5  6  7  8   9   10  11  12  13  14   15   16  17  18  19  20   21   22  23  24  25.............. Now mark the multiples of next unmarked that is 5 2 3  4  5  6  7  8   9   10  11  12  13  14   1

Program to reverse a doubly linked list

In doubly linked list we are not restricted to move in one direction unlike in singly linked list because in doubly linked list we have two pointers in one node that is next pointer and previous pointer.so that we can move in both directions.Taking the advantage of this property of doubly linked list it is more easier to reverse doubly linked list as compared to singly linked list.The logic of the program is simple.We are going upto middle of doubly linked list and swap the first node and last node and so on until the linked list is reversed. struct node { node *next; node *previous; int data; } void reverse(struct node *head) { node *firstnode; node *secondnode; int l; int length=0; struct node *tail=head; while(tail!=NULL) { tail=tail->next; length++; } firstnode=head; secondnode=tail; l=length/2; node *temp; for(int i=0;i<l;i++) { temp=firstnode->data; firstnode->data=secondnode->data; secondnode->data=temp; firstnode=firstnode->nex

Resistive vs Capacitive touchscreens

We all know that there are two types of touchscreens in mobile phones but we dont know what actually they are and what are the difference between them.Many of us encountered the difference while using mobile phones such as some touchscreen response is faster and its easy to touch while in some response is little longer and have to apply more pressure.The two types of touchscreen are resistive and capacitive. Which one is better then the other.Well today we will see what are the difference between them. Resistive : This is the most common touchscreen type in mobile phones except some smartphones and tablets. Talking about resistive touch,from the name we can get that this touchscreen depends on resistance.The resisitive touchscreen consist of several layers stacked upon each other.But there are two important transparent thin layer seperated by thin gap.The screen we touch has a coating on its other side and beneath it there is other layer also have coating on it one side.Both the s

Program to reverse the words of string

This program is little bit modification to the previous post program.After reversing the letters of each words in a string when we call again the reverse function the words get reversed of the string. #include<stdio.h> #include<conio.h> void reverse(char *start, char *end); void reversethewords(char *s) {   char *wordbegin = s;      //wordbegin and t are two pointer to the first character of string s   char *t = s;               while( *t)   {     t++;     if (*t == '\0')            // if reached at the end of the string reverse(swap) the first character and last and     {                                                                                                                            so on.       reverse(wordbegin, t-1);     }     else if(*t == ' ')        // if encountered with space then reverse and make wordbegin=t+1 for the     {                                                                                                  

Program to reverse the letters of each words of the string

#include<stdio.h> #include<conio.h> void reverse(char *start, char *end); void reversethewords(char *s) {   char *wordbegin = s;      //wordbegin and temp are two pointer to the first character of string s   char *t = s;                 while( *t)   {     t++;     if (*t == '\0')            // if reached at the end of the string reverse(swap) the first character and last and     {                                                                                                                            so on.       reverse(wordbegin, t-1);     }     else if(*t == ' ')        // if encountered with space then reverse and make wordbegin=t+1 for the     {                                                                                                                            next word       reverse(wordbegin, t-1);       wordbegin = t+1;     }   } } void reverse(char *start, char *end) {   char temp;   while (start < end)   {    

extern keyword in C

For extern keyword to understand let us first discuss the difference between declaring a variable and defining a variable.The declaration of variable is simply declaring variable in the program that is it just exist somewhere in the program with no memory allocated to that variable.When the variable is declared program know the datatype of the variable.On the other hand when we say we defined a variable it means that a variable is declared and also section of memory is allocated to that variable in the program.The variable in a program can be declared various times but can only defined once.Now moving onto the "extern" keyword when we declare a variable with extern keyword the variable is only declared and not defined. Let's understand this using some sample programs : int a; int main() { a=10; printf("%d",a); } The above program is compiled successfully without any error because the variable "a" is declared and defined globally.So the varia

Volatile qualifier in C

I am going to talk about volatile keyword in C which is asked in most of the technical interviews by companies.Although we encountered with this keyword often but most of us don't know why it is being used in declaring variables.So it can be a good question for the interview. The volatile keyword is used to prevent compiler from applying optimizations on objects which can get changed that cannot be determined by the compiler.Objects declared as volatile are excluded from optimizations because they can changed by the code outside of the scope of the current code.The system always read the value of volatile object from memory location rather then the temporary register where as if the object is not volatile then compiler will do optimization in such a way that it will uses the value from temporary register to speed up the program. Let's understand it by sample programs.In the below code we are compiling the code without optimization and we are declaring a variable as cons

Answers for frequently asked puzzles in Interview.

Ans 1) As you can only open the door once. So let's take 3 switches as A, B, C, and let's take bulb as X, Y, Z.So first turn on switch A for some time let's say 4-5 minutes then switch it off. Now turn on any other switch from B or C. Now enter the door and see the bulbs. The one which is on corresponds to the switch you just turn on, Now touch the bulbs, the bulb which is hot corresponds to the switch you turn on first that is A and the bulb which is cold corresponds to the switch you didn't turn on. Ans 2) Divide gold bar into 3 parts 1 bar,2 bar, and 4 bar by making 2 cuts day 1- Give away 1 bar day2- Take away 1 bar and give 2 bar day 3- Give again 1 bar (2+1=3) day 4- Take away 1 and 2 bar and give 4 bar day 5- Give 1 bar (4+1=5) day 6- Take away 1 bar and give 2 bars (4+2=6) day 7 -Give 1 bar (4+2+1=7) Ans 3) This question is asked in an interview to check whether you can give more than one answer for one question (basically they wanted to check wheth

Program to find the element in an array with maximum occurrences

This is the program to find the element with maximum occurrences in an array.I extended the previous post program to get the element with maximum occurrences. #include<stdio.h> #include<conio.h> int main() { int k=0,count=0,z=0; int index; int countarr[16],nos[16]; int arr[20]={1,1,23,23,23,34,34,34,45,45,33,33,33,33,33,33,54,54,11,12}; for(int i=0;i<20;i++) { if(i>0) { i=i+count-1; } nos[z]=arr[i]; z=z+1; count=0; for(int j=0;j<20;j++) { if(arr[i]==arr[j]) count++; } countarr[k]=count; k=k+1;     }   int max=countarr[0]; for(int i=1;i<k;i++) { if(countarr[i]>max) { max=countarr[i]; index=i; } } printf("The element which have maximum frequency is :\n"); printf("%d",nos[index]); getch();   }

Count the occurrences of elements in an array

This is the program of counting the occurrences of each of the elements in an array asked in interview.I used a sample array for this program. #include<stdio.h> #include<conio.h> int main() { int k=0,count=0,z=0; int countarr[16],nos[16]; int arr[20]={1,1,23,23,23,34,34,34,45,45,33,33,33,33,33,33,54,54,11,12}; for(int i=0;i<20;i++) { if(i>0) { i=i+count-1; } nos[z]=arr[i]; z=z+1; count=0; for(int j=0;j<20;j++) { if(arr[i]==arr[j]) count++; } countarr[k]=count; k=k+1;     }   printf("The count of each element of the array is :\n"); for(int i=0;i<k;i++) printf("%d-%d\n",nos[i],countarr[i]); getch();   }

The Vignere cipher

Image
The Vignere cipher is a method of encryption which uses caesar cipher on each letter based on the letters of keyword.In caeser cipher each letter of the plaintext is shifted number of tomes depending upon the key value for examlple if the key=2 then the letter A is shifted two times and encrypted as C.Vignere cipher uses this technique on each of the letters but with different keys each time.That is the reason it appears unbreakable at first.But it is quite easy to understand and implement. For encrypting the plaintext vignere cipher uses vignere square or tabula recta which is like 26 X 26 table consisting of alphabets A-Z on ech row and columns.The columns in a table are such that each next column first alphabet is obtained by shifting previous column alphabet by one. Here is the figure of vignere square or tabular recta For the Encryption process the cipher uses different alphabets from the rows each time depending upon the alphabet key is having.So the process of encr

Program to perform Merge Sort using Linked list

Merge Sort is being done using Divide and Conquer Algorithm.We are going to use linked list for performing the merge sort.I will going to write the functions of the program and not the whole program. Program : /* This function takes the head of the linked list and declare two nodes a and b and then split the linked list by calling splitlinkedlist( ) function by passing head and two nodes and then sort recursively each part . */ struct node { int data; struct node*next; }; void mergesort(struct node *head1) { struct node *head=*head1; struct node *a; struct node *b; if (head==NULL||head->next==NULL) return; splitlinkedlist(head,&a,&b); mergesort(&a);                      // Recursively sort the splited nodes mergesort(&b); *head1=sort_merge(a,b); } /* This function is used to split the linked list from middle, for that we are taking a as a front node and b as back node and we are declaring two new node fast and slow,and then increment fas

Different image formats for web browsers

This post is about different image formats for web browsers like jpeg,png,gif and WebP.I assume that all of you are aware of first three image formats but very few know about WebP.So i will be explaining each of them independently. JPEG : JPEG is acronym of "Joint photographic expert group" .It is in Raster format .Basically JPEG is a compression method.JPEG compressed images are usually stored in JFIF file format (JPEG file interchange format).The file extension we used in JPEG is .jpg or .jpeg.JPEG compression is called lossy compression that is the degree of compression can be adjusted allowing a tradeoff between storage size and image quality but JPEG often suffers degradation in image quality when repeatedly edited and saved.JPEG/JFIF is most common image format for storing and transmitting images on World wide web.This format is simply called JPEG.  GIF : GIF (Graphics interchange format) is a bitmap image format.This image format is widely used in World wide

Program to implement Queues using two stacks

Lets learn the concept of Queues and Stacks first. Stack  : Stack uses LIFO principle that is the element which entered stack last will pop first. Queue  : Queue uses FIFO principle that is the element which is added first will get out first. Now the logic for the above program is very simple.You can understand it by thinking about two stacks we are using togather.  We going to try to apply FIFO principle to the elements we are entering in stacks.But we know that the element which entered in first will pop at last in stacks.So how we going to do it ?? Its Simple !!! Just take one stack lets say Stack1 put all the elements in it.And now take other stack which we will be calling as stack2 and pop each element from stack1 and push that element in stack2.Repeat this process untill the stack1 is empty. Now the next step is to just pop each element from stack2.Thus you can see that the element which entered first gets out first which is nothing but FIFO principle used in Queue

Frequently asked puzzles in Interviews

1)There is a room with a door (closed) and three light bulbs. Outside the room, there are three switches, connected to the bulbs. You may manipulate the switches as you wish, but once you open the door you can't change them. Identify each switch with its bulb. 2)You've got someone working for you for seven days and a gold bar to pay them. The gold bar is segmented into seven connected pieces. You must give them a piece of gold at the end of every day. If you are only allowed to make two breaks in the gold bar, how do you pay your worker? Here you put one condition in front of the worker that he cannot spend any of the gold bars until he is fully paid. 3)Why is a manhole cover round? 4)If given a cake, a corner has been broken. How do u cut the rest into two equal parts? 5)What is the color of the bear when dropped from a height of 20 m and takes 2 seconds?                   6)Can you make 120 with 5 Zeroes? 7)Numbers of Zero at the end of 100 !?

C Program to show memory representation of datatypes

#include <stdio.h> #include<conio.h> typedef unsigned char *byte_ptr; void showbytes(byte_ptr start, int len) //show bytes takes byte pointer as an argument and prints memory {                                                           //contents from byte_ptr  to byte_ptr + len      int i;      for (i = 0; i < len; i++)            printf(" %.2x", start[i]);      printf("\n"); } void showint(int x) {      showbytes((byte_ptr) &x, sizeof(int)); } void showfloat(float x) {      showbytes((byte_ptr) &x, sizeof(float)); } int main() {     int i = 1;     float f = 1.0;     showfloat(f);     showint(i);       getch(); }