Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Search Your Question

Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Thursday, July 24, 2008

Algorithms And Programming #4

31. A walk-through through the symbol table functions, lookup () implementation etc - The interview was on the Microsoft C team.

32. A version of the "There are three persons X Y Z, one of which always lies".. etc..

33. There are 3 ants at 3 corners of a triangle; they randomly start moving towards another corner. What is the probability that they don't collide?

34. Write an efficient algorithm and C code to shuffle a pack of cards. This one was a feedback process until we came up with one with no extra storage.

35. The if (x == 0) y = 0 etc.

36. Some more bit wise optimization at assembly level

37. Some general questions on Lex, Yacc etc.

38. Given an array t[100] which contains numbers between 1..99. Return the duplicated value. Try both O (n) and O(n-square).

39. Given an array of characters. How would you reverse it? How would you reverse it without using indexing in the array?

40. Given a sequence of characters. How will you convert the lower case characters to upper case characters? (Try using bit vector - sol given in the C lib -typec.h)

NEXT
BACk

Algorithms And Programming #5


41. Fundas of RPC.

42. Given a linked list, which is sorted. How will u insert in sorted way.

43. Given a linked list how will you reverse it?

44. Give a good data structure for having n queues (n not fixed) in a finite memory segment. You can have some data-structure separate for each queue. Try to use at least 90% of the memory space.

45. Do a breadth first traversal of a tree.

46. Write code for reversing a linked list.

47. Write, efficient code for extracting unique elements from a sorted list of array. e.g. (1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9) -> (1, 3, 5, 9).

48. Given an array of integers, find the contiguous sub array with the largest sum.

ANS. Can be done in O (n) time and O (1) extra space. Scan array from 1 to n. Remember the best sub array seen so far and the best sub array ending in i.

49. Given an array of length N containing integers between 1 and N, determine if it contains any duplicates.

ANS. [Is there an O (n) time solution that uses only O (1) extra space and does not destroy the original array?]

50. Sort an array of size n containing integers between 1 and s. The sum of the array is known not to overflow an integer. Compute the sum. What if we know that integers are in 2's complement form?


NEXT
BACk

Algorithms And Programming #6

51. An array of characters. Reverse the order of words in it.
ANS. Write a routine to reverse a character array. Now call it for the given array and for each word in it.

* 52. An array of integers of size n. Generate a random permutation of the array, given a function rand_n () that returns an integer between 1 and n, both inclusive, with equal probability. What is the expected time of your algorithm?

ANS. "Expected time" should ring a bell. To compute a random permutation, use the standard algo of scanning array from n downto 1, swapping i-th element with a uniformly random element <= i-th. To compute a uniformly random integer between 1 and k (k < n), call rand_n () repeatedly until it returns a value in the desired range.

53. An array of pointers to (very long) strings. Find pointers to the (lexicographically) smallest and largest strings.

ANS. Scan array in pairs. Remember largest-so-far and smallest so far. Compare the larger of the two strings in the current pair with largest-so-far to update it. And the smaller of the current pair with the smallest so far to update it. For a total of <= 3n/2 strcmp () calls. That's also the lower bound.

54. Write a program to remove duplicates from a sorted array.

ANS. int remove_duplicates (int * p, int size)
{
int current, insert = 1;
for (current=1; current < size; current++)
if (p [current] != p [insert-1])
{
p [insert] = p[current];
current++;
insert++;
} else
current++;
return insert;
}

55. C++ (what is virtual function? what happens if an error occurs in constructor or destructor. Discussion on error handling, templates, unique features of C++. What is different in C++, (compare with Unix).

56. Given a list of numbers (fixed list) Now given any other list, how can you efficiently find out if there is any element in the second list that is an element of the first list (fixed list).

57. Given 3 lines of assembly code: find it is doing. IT was to find absolute value.

58. If you are on a boat and you throw out a suitcase, Will the level of water increase?

59. Print an integer using only putchar. Try doing it without using extra storage.

60. Write C code for (a) deleting an element from a linked list (b) traversing a linked list

NEXT
BACk

Algorithms And Programming #7

61. What are various problems unique to distributed databases?

62. Declare a void pointer

ANS. void *ptr;

63. Make the pointer aligned to a 4 byte boundary in a efficient manner ANS. Assign the pointer to a long number and the number with 11...1100 add 4 to the number

64. What is a far pointer (in DOS)

65. What is a balanced tree?

66. Given a linked list with the following property node2 is left child of node1,
if node2 < nod1 else, it is the right child.

O P
|
|
O A
|
|
O B
|
|
O C

How do you convert the above linked list to the form without disturbing the property. Write C code for that.


O P
|
|
O B
/ / / O ? O ?

Determine where do A and C go

67. Describe the file system layout in the UNIX OS

ANS. describe boot block, super block, inodes and data layout

68. In UNIX, are the files allocated contiguous blocks of data

ANS. no, they might be fragmented

69.How is the fragmented data kept track of?

ANS. Describe the direct blocks and indirect blocks in UNIX file system

70. Write an efficient C code for 'tr' program. 'tr' has two command line arguments. They both are strings of same length. tr reads an input file, replaces each character in the first string with the corresponding character in the second string. e.g. 'tr abc xyz' replaces all 'a's by 'x's, 'b's by 'y's and so on.

ANS.
a) have an array of length 26.
put 'x' in array element corr to 'a'
put 'y' in array element corr to 'b'
put 'z' in array element corr to 'c'
put 'd' in array element corr to 'd'
put 'e' in array element corr to 'e'
and so on.

The code
while (!eof)
{
c = getc ();
putc (array [c - 'a']);
}



NEXT
BACk

Algorithms And Programming #8

71. What is disk interleaving

72. Why is disk interleaving adopted?

73. Given a new disk, how do you determine which interleaving is the best a) give 1000 read operations with each kind of interleaving determine the best interleaving from the statistics

74. Draw the graph with performance on one axis and 'n' on another, where 'n' in the 'n' in n-way disk interleaving. (A tricky question, should be answered carefully)

75. I was a c++ code and was asked to find out the bug in that. The bug was that he declared an object locally in a function and tried to return the pointer to that object. Since the object is local to the function, it no more exists after returning from the function. The pointer, therefore, is invalid outside.

76. A real life problem - A square picture is cut into 16 squares and they are shuffled. Write a program to rearrange the 16 squares to get the original big square.

77.int *a;
char *c;
*(a) = 20;
*c = *a;
printf (“%c”, *c);

What is the output?

78. Write a program to find whether a given m/c is big-endian or little-endian!

79. What is a volatile variable?

80. What is the scope of a static function in C?

NEXT
BACk

Algorithms And Programming #9

81. What is the difference between "malloc" and "calloc"?

82. struct n {int data; struct n* next} node;
node *c, *t;
c->data = 10;
t->next = null;
*c = *t;
What is the effect of the last statement?

BACk

Prime Numbers!

Prime Numbers:

Prime Numbers are those natural numbers divisible only by 1 and themselves.These are building blocks of natural number arithmetic.

Some interesting things about prime numbers.

1)Any Natural number can be expressed uniquely as product of powers of distinct primes.This procedure of finding the powers of primes contained in a number is called Prime Factorization.

2)There are infinitely many prime numbers.

3)If a number N is not prime, then it should have a factor less than sqrt(N).Hence the procedure to test whether a number is prime or not is of complexity O(sqrt(N)).

Prime Twin Pairs


One of the first things noticeable about tables of primes is that there are many instances of pairs of prime numbers with the form n and n + 2.

Examples are 11 and 13, 17 and 19, 29 and 31, 101 and 103, 881 and 883, and so on.

These are sometimes called prime twin pairs. No one has ever determined if this is an interesting property of numbers or just a curious coincidence.
The instances of pairs of prime numbers decrease for ever larger numbers.

Palindromic Primes

One of the more curious prime number puzzles that mathematicians have examined is the occurrence of palindromic primes.

A palindrome is a word or phrase that reads the same forward or backward. Some examples of palindromic primes are 101, 131, 151, 181, 313, 353, 727, 757, 787, 79997, 91019, 1818181, 7878787, 7272727, and 3535353. There is an infinite number of palindromic primes.


Sieve of Eratosthenes

The Sieve of Eratosthenes is an algorithm for generating a list of all prime numbers up to a given integer N. It does this using O(N) space .

We begin by making a table of integers 2 to N.We find the smallest integer i, that is not crossed out,print i and cross out i, 2i , 3i, .........When i >sqrt(N) the algorithm terminates and further numbers which aren't crossed out printed.

Q1)Suggest ways to improve it further.

Solution:The improvement in terms of space requirements that can be done is accomodating only odd numbers as 2 is the only even prime.
considering time complexity, we can limit the strike off to multiples of prime P greater than P*P ,hence reducing the number of numbers traversed.



What is the complexity of this algorithm?

Solution:Nlog(N)

Q2)In the above mentioned facts about primes ,the second one claims that there are infinite number of primes.Prove it

Solution:Let there be finite number of primes say K.let the primes be P1,P2,....,Pk.
now consider the number N=P1*P2*P3*P4....*Pk + 1.
clearly none of the above k primes divide N.Hence N is also a prime contradicting our initial assumption.

Q3)Show that (N^4 + 4N) is a prime number if and only if N=1. (really simple)

Solution:let f(N)=N^4 + 4N.
f(1)=5 which is prime.
for N greater than 2 we can write f(N)=N(N^3+4) as product of 2 numbers both of which are greater than 1.Hence it is composite.
Hence proved.


Relative Primes

When gcd(m, n) = 1, the integers m and n have no prime factors in
common and we say that they’re relatively prime.

Euler's Phi Function

Euler's Phi function, also known as the totient function, is a function that, for a given positive integer N, calculates the number of positive integers smaller than or equal to N that are relative prime to N. (Note that except when N = 1, only integers strictly smaller than N are counted.

Mathematical Definition

\phi(N) = \Big|\, \{ i ~~|~~ 1\leq i\leq N ~\land~ \gcd(i,N)=1 \} \Big|
where | | indicates the cardinality of the set.

Features of Euler's Phi Function

1) φ(p) = p - 1 for p prime, because all numbers smaller than p are relatively prime to p.

2) φ(N) is even for all N > 2, because if k is relatively prime to N, so is N - k, and they are distinct.

3) It is a multiplicative function in the number-theoretic sense: φ(MN) = φ(M)φ(N) whenever gcd(M,N) = 1.

4)\phi(p^k) = p^k-p^{k-1} = p^{k-1}(p-1) = p^k\left(1-\frac{1}{p}\right), because among the integers from 1 to pk, the integers not relatively prime to pk are precisely those divisible by p, and there are pk - 1 of them.

5)Let N = p_1^{\alpha_1} p_2^{\alpha_2} \cdots p_r^{\alpha_r} be the prime factorisation of N. That is, the pis are distinct primes and each αi is a positive integer. Then \phi(N) = (p_1^{\alpha_1}-p_1^{\alpha_1-1})\cdots(p_r^{\alpha_r}-p_r^{\alpha_r-1}) = N \left( 1 - \frac{1}{p_1} \right)\left( 1 - \frac{1}{p_2} \right) \cdots\left( 1 - \frac{1}{p_r} \right)

If you have perhaps gone through the above facts,you can try solving the below mentioned
programming problems which test the basics

http://acm.uva.es/p/v101/10168.html

http://acm.uva.es/p/v106/10699.html

http://acm.uva.es/p/v107/10789.html

http://acm.uva.es/p/v108/10852.html

http://acm.uva.es/p/v108/10871.html

http://acm.uva.es/p/v109/10924.html

http://acm.uva.es/p/v1/160.html

http://acm.uva.es/p/v2/294.html

http://acm.uva.es/p/v4/406.html

http://acm.uva.es/p/v5/516.html

http://acm.uva.es/p/v5/543.html

http://acm.uva.es/p/v5/583.html

Remember that the solutions to these problems should be efficient in terms of time and space complexities.


post your valuable comments so that we can learn better through discussion.

Solutions to all the above problems shall be posted soon!!

C Programming Puzzles

C programming is very important topic for freshers, interviewers usually asks questions from C,C++,Data structures when it comes to programming. So i am starting this Topic , i will gather some good puzzles and keep on continuing this topic. I will also post the answers to the puzzles listed here soon.

The puzzles mostly covers on typo mistakes, basic understanding of some C concepts , i will explain the answers tho these puzzles covering those concepts also, And please use comment section.

A small poll here, should i post the answers just below each puzzle or should i post the answer in some other post and link it from here. I will post the answers in 3 days.Poll through comments.


1)
#include

main()
{
auto int i = 0;
printf("%d\n",i);

{
int i = 2;
printf("%d\n",i);
{
i+=1;
printf("%d\n",i);
}
printf("%d\n",i);
}
printf("%d\n",i);
printf("%d\n",reset());
printf("%d\n",ret10());
printf("%d\n",reset());
printf("%d\n",ret10());
}


int reset()
{
int j = 0;
return(j);
}

int ret10()
{
static int i = 10;
i+=1;
return(i);
}


2)
#include
#include
main()
{
struct emp1
{
char *name;
int age;
};
struct emp2
{
char *cp;
struct emp1 e1;
}e2 = {"ghi",{"jkl",123}};

struct emp1 e3 = {"rwer",2341};
printf("\n%s %d\n",e3.name,e3.age);
printf("\n%s %s %d\n",e2.cp,e2.e1.name,e2.e1.age);
}

3)
#include
struct xyz
{
int xyz ;
}
;

main()
{
union xyz
{
int xyz;
}
;
}

4)
#include
main()
{
char s[] = "Bouquets and Brickbats";
printf("\n%c, ",*(&s[2]));
printf("%s, ",s+5);
printf("\n%s",s);
printf("\n%c",*(s+2));
}

5)
#include
#include
struct s
{
char *st;
struct s *sptr;
};
main()
{
int i;
struct s *p[3];
static struct s a[]={
{"abcd",a+1},
{"pqrs",a+2},
{"stuv",a}
};
for( i=0;i<3;i++ )
p[i] = a[i].sptr;
swap(*p,a);
printf("%s %s %s \n",p[0]->st,(*p)->st, (*p)->sptr->st);
}

swap(p1,p2)
struct s *p1,*p2;
{
char *temp;
temp = p1->st;
p1->st = p2->st;
p2->st = temp;
}

6)
#include
Swap( int *x , int *y)
{
int tmp = *x ;
*x = *y ;
*y = tmp;
}
main()
{
int a = 1, b = 2;
Swap(&a, &b);
printf("%d %d\n", a, b);
}

7)
#include
main()
{
int i;
scanf("%d",&i);
switch(i) {
printf("\nHello");
case 1: printf("\none");
break;
case 2: printf("\ntwo");
break;
}
}

8)
#include
main()
{
int x;
x = 3;
f(x);
printf("MAIN");

}

f(int n)
{
printf("F");
if (n != 0)
f(n-1);
}


9)
#include
main()
{
int ptr[] = {1,2,23,6,5,6};
char str[] = {'a','b','c','d','e','f','g','h'};

printf("pointer differences are %ld, %d",&ptr[3], &str[3]-&str[0]);
}

10)
#include
main()
{
char a,b,c;
scanf("%c %c %c",&a,&b,&c);
printf("%c %c %c ", a, b, c);
}

11)
#include
#define PRINT(int) printf( "int = %d ", int)
main()
{
int x=03,y=02,z=01;
PRINT (x | y & ~z);
PRINT (x & y && z);
PRINT (x ^ (y & ~z));
}

12)
#include
main()
{
int a = 10000;
char b='c';
int i,j;

printf("%d,%d",printf("%d\n",a),printf("%c\n",b));
}

13)
#include
#define PR(a) printf("%d\t",(int) (a));
#define PRINT(a,b,c) PR(a);PR(b);PR(c);
#define MAX(a,b) (amain(){
int x = 1,y = 2;
PRINT(MAX(x++,y),x,y);
PRINT(MAX(x++,y),x,y);
}

14)
#include
main()
{
unsigned int i=1;
for(;i>=0;i--) printf("hello: %u\n",i);
}

15)
#include
main()
{
struct ist{
int x;
int y;
};

struct list{
int x;
struct ist next;
}head;
head.x = 100;
head.next.x=10;
printf("%d %d", head.x,head.next.x);
}

16)
#include
main()
{
typedef union
{
struct
{
char c1,c2;
} s;
long j;
float x;
} U;

U example;
example.s.c1 = 'a';
example.s.c2 = 'b';
example.j = 5;
printf("%c %c %d", example.s.c1, example.s.c2, example.j);
}

17)
#include
main()
{
struct s1
{ char *str;
struct s1 *ptr;
};
static struct s1 arr[] = { {"Hyderabad",arr+1},{"Bangalore",arr+2},
{"Delhi",arr}};
struct s1 *p[3];
int i;

for(i=0;i<=2;i++)
p[i] = arr[i].ptr;

printf("%s\n",(*p)->str);
printf("%s\n",(++*p)->str);
printf("%s\n",((*p)++)->str);
}

18)
#include
main()
{
struct s1
{ char *str;
struct s1 *ptr;
};
static struct s1 arr[] = {{"Hyderabad",arr+1},
{"Bangalore",arr+2},
{"Delhi",arr}
};
struct s1 *p[3];
int i;

for(i=0;i<=2;i++) p[i] = arr[i].ptr;

printf("%s ",(*p)->str);
printf("%s ",(++*p)->str);
printf("%s ",((*p)++)->str);
}

19)
#include
main()
{
char input[] = "SSSWILTECH1\1\1";
int i, c;
for ( i=2; (c=input[i])!='\0'; i++){
switch(c){
case 'a': putchar ('i'); continue;
case '1': break;
case 1: while (( c = input[++i]) != '\1' && c!= '\0');
case 9: putchar('S');
case 'E': case 'L': continue;
default: putchar(c);continue;
}
putchar(' ');
}
putchar('\n');
}

20)
#include
main()
{
int i, n, m, b, x[25];
int f1(int, int, int j[25]);
for(i=0;i<25;i++) x[i] = i;
i=0; m = 24;
b=f1(i, m, x);
printf("res %d\n",b);
}

int f1( int p, int q, int a[25])
{
int m1,m2;
if (q==0)
return(a[p]);
else
{
m1 = f1 (p, q/2, a);
m2 = f1(p+q/2+1,q/2,a);
if(m1 return (m2);
else
return(m1);
}
}

21)
#include
main()
{
int a[3][4] ={1,2,3,4,5,6,7,8,9,10,11,12} ;
int i,j,k=99 ;
for(i=0;i<3;i++)
for(j=0;j<4;j++)
if(a[i][j] < k) k = a[i][j];
printf("%d", k);
}

22)
#include
main()
{
int a,b,c;
for (b=c=10;a= "Love Your INDIA \
TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq TNn*
RPn/QPbEWS_JSWQAIJO^NBELP\
eHBFHT}TnALVlBLOFAKFCFQHFOQIAIREETMSQGCSQOU
HATFAJKSbEALGSkMCSlOASn^r\
^r\\tZvYxXyT|S~Pn SPm SOn TNn
ULo0ULo#ULo-WHq!WFs XDt!"[b+++6];)
while(a-->64) putchar (++c=='Z'?c=c/9:33^b&1);
}

23)
#include
main()
{
char *p = "hello world!";
*(p+0) = 'H';
printf("%s",p);
}

24)
#include
main()
{
unsigned int m[] = { 0x01,0x02, 0x04, 0x08,0x10, 0x20, 0x40, 0x80};
unsigned int n,i;
printf("%d",m[7]);
scanf("%d",&n);
for(i=0;i<=7;i++)
{ if (n& m[i])
printf("\nyes");
else
printf("\nno");
}
}

25)
#include
main()
{
int a,b=2,c;
int *pointer;
c = 3;
pointer = &c;
a = c/*pointer*/;
b = c /* assigning 3 to b*/;
printf("a = %d; b = %d", a,b);
}

solve them and comment the solutions.

C Programming Puzzles 2

26)
#include
main()
{
int i ;
i = 1;
i= i+2*i++;
printf("i is now %d",i);
}

27)
#include
#define MAX(x,y) (x) >(y)?(x):(y)
main()

{
int i=10,j=5,k=0;
k= MAX(i++,++j);
printf("%d..%d..%d",i,j,k);
}

28)
#include
main()
{
const int i = 100;
int *p = &i;
*p = 200;
printf("%d\n",i);

}

29)
#include
static int count;
void f(int n)
{
int i;
for(i =1;i<=n;i++)
f(n-i);
count++;
}
main()
{
extern int count;
f(5);
printf("%d",count);
}

30)
#include
void test(int , int *);
main()
{
int * iptr, j, k = 2;
iptr = &j;
j = k;
printf( "%d %d ", k, j);
test(j, iptr);
printf("%d %d\n", k, j);
}
void test(int l, int *p)
{
l++;
(*p)++;
}

31)
#include
main()
{
char a= 'A';
if( (a=='Z')||( (a='L')&&( a=='A')))
a=a;
printf("%c",a);
printf(" Nothing ");
}

32)
#include
int myfunc(char *str)
{
char *ptr =str;
while(*ptr++);
return ptr-str-1;
}
main()
{
printf("%d", myfunc("DESIS"));
}

33)
#include
main(int sizeofargv, char *argv[])
{
while(sizeofargv)
printf("%s ",argv[--sizeofargv]);
}

34)
#include
main()
{
int x,y=1,z;
if(x=z=y); x = 3;
printf("%d %d %d\n",x,y,z);
while (y<4) x+=++y;
printf("%d %d\n",x,y);
}

35)
#include
main()
{
union {
long l_e;
float f_e;
} u;

long l_v;
float f_v;
l_v = u.l_e = 10;
printf("%f ", (float)l_v);
printf("%f ", u.f_e);
f_v = u.f_e = 3.555;
printf("%d ", (long)f_v);
printf("%d ", u.l_e);
}

36)
#include
main()
{
char a[5] = "abcd";
int b = 3;

printf("%c\n",a[b]);
printf("%c\n",((char *) b)[(int) a]);
}

37)
#include
#define PRINTIFLESS(x,y) if((x) < (y)) printf("First is smaller");else
main()
{
int i = 2, k =1;
if(i>0 && k>0) PRINTIFLESS(i,k);
else printf("Numbers not greater than 0\n");

}

38)
#include
#include
main()
{
int *iptr,*dptr, i;
dptr = malloc(sizeof(i));
iptr =&i ;
*iptr = 10;
free(iptr);
*dptr = 20;
/*dptr = iptr;*/
free(dptr);
printf("%d,%d,%d",*dptr,*iptr,i);
}

39)
#include
main()
{
char line[80];
gets(line);
puts(line);

}

40)
#include
main()
{
char c1;
int i=0;
c1='a';
while(c1>='a' && c1 <='z')
{
c1++;
i++;
}
printf("%d",i);
}

41)
#include
main()
{
char ch = 'A';
while(ch <='F'){
switch(ch){
case 'A':case 'B':case 'C': case 'D': ch++; continue;
case 'E': case 'F': ch++;
}
putchar(ch);
}
}

42)
#include

f(int x,int *y)
{
x=*(y)+=2;
}

main()
{
static int a[5] = {2,4,6,8,10};
int i,b=5;
for(i=0; i< 5;i++){
f(a[i],&b);
printf("%d %d\n",a[i],b);
}
}

43)
#include
main()
{
FILE *fp1,*fp2;
fp1 = fopen("one","w");
fp2 = fopen("one","w");
fputc('A',fp1);
fputc('B',fp2);
fclose(fp1);
fclose(fp2);
}

44)
#include
main()
{
int a = 0xff;
if(a<<4>>12)
printf("Right");
else
printf("Wrong");
}

45)
#include
main()
{
enum _tag{ left=10, right, front=100, back};
printf("left is %d, right is %d, front is %d, back is %d",left,right,front,back);
}

46)
#include
main()
{
char *arr = "This is to test";
printf("\n%c %c ",*(arr), *(arr++));

}

47)
#include
main()
{
int I =-3, j=2, k = 0,m;
m = ++I && ++j && ++k;
printf("\n%d %d %d %d", I, j, k, m);
}

48)
#include
#define MAX 20

main()
{
FILE *fp1, *fp2;
char *this1, *this2;
fp1 = fopen("ip1.dat","r");
if(fp1==NULL)printf("file open error\n");

fp2 = fopen("ip2.dat","r");
if(fp2==NULL)printf("file open error\n");

if((getline(this1,fp1)!=0) && (getline(this2,fp2)!=0)){
if(strcmp(this1,this2))
continue;
else { printf("lines do not match\n"); break;}
}
}
int getline(char *line, FILE *fp)
{
if(fgets(line,MAX, fp) == NULL)
return 0;
else
return strlen(line);
}

49)
#include
main()
{
FILE *fp;
fp = fopen("testbuf.txt", "wt");
fwrite("1. This is fwrite\n",1, 18, fp);
write(fileno(fp), "2.This is write\n", 17);
fclose(fp);
}

50)
#include
#define PR(a) printf("a = %d\t",(int) (a));
#define PRINT(a) PR(a); putchar('\n');
#define FUDGE(k) k + 3.14

main()
{
int x = 2;
PRINT( x * FUDGE(2));
}

C Programming Puzzles 3

51)
#include
main()
{
int i = 3,j;
j = add(++i);
printf("i = %d *p= %d\n", i, j);
}

add(ii)
int ii;
{
ii++;
printf("ii = %d\n", ii);
}

52)
#include
#define DEBUG(args) (printf("DEBUG: "), printf args)

main()
{
int n = 0,i = 0 ;
printf("%d\n", n);
if(n != 0) DEBUG(("n is %d\n", n));
DEBUG(("%d",i));

}

53)
#include
main()
{
printf("hello");
fork();
}

54)
#include
#include
#include
main()
{
char *s2, *s1 ;
// s1 = malloc(sizeof(char) * 1000);
s1 = "Hello, ";
// s2 = malloc(sizeof(char) * 10);
s2 = "world!";
strcat(s1, s2);
printf("%s", s2);
}

55)
#include
char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";
main()
{
printf(s,34,s,34);
}

56)

#include
#include
main()
{
char *s1 = "alpha", *s2 = "alpha";
if(!strcmp(s1,s2)) printf("yes\n");
}

57)
#include
#define DEBUG(args) (printf("DEBUG: "), printf args)

main()
{
int n = 10;
if(n != 0) DEBUG(("n is %d\n", n));

}

58)
#include
main()
{
int i;
struct
{
int left,y;
}a;
printf("%5d\n",a[i].left);
}

59)
#include
main()
{
char c1,c2,c3;
c1 = getc(stdin);
putc(c1,stdout);
// c2 = getche();
// putc(c2,stdout);
c3 = getchar();
putc(c3,stdout);
}

60)
#include
#include
struct test{
int f;
};

struct test* f(struct test * (*fPtr)() )
{
struct test *ptr = (struct test*) malloc(sizeof(struct test));
return ptr;
}
main()
{
f(f)->f;
}

61)
#include
void print_in_reverse( char *str )
{
if( *str == '\0' )
return;

print_in_reverse(str+1);

printf( "%c" , *str );
}
main()
{
print_in_reverse( "char *str" );
}

62)
#include
#include
//#define sqrt(x) (( x < 0) ? sqrt(-x) : sqrt(x))
main()
{
int y;
y = sqrt(-9);
printf("%d",y);
}

63)
#include
#define MAXI 100
main(){
int done,i,x=6;
done=i=0;
for(i = 0; (i< MAXI) && (x/=2)>1; i++)
done++;
printf("%d %d\n",i,done);
}

64)
#include
main()
{

char as[] = "\\0\0";

int i = 0;
do{
switch( as[i++]){
case '\\' : printf("A");
break;
case 0 : printf("B");
break;
default : printf("C");
break;
}
}
while(i<3);
}

65)
#include
#define MAXI 100
main(){
int done,i,x=6;
done=i=0;
while (i < MAXI && !done){
if ((x/=2)>1){ i++; continue;}
done++;
}
printf("%d %d\n",i,done);
}

66)
#include
main()
{
struct emp
{ char name[20];
int age;
float sal;
};
struct emp e = {"Tiger"};
printf("\n%d %f",e.age,e.sal);
}

67)
#include
main()
{
char str[] = "Taj is 2 miles away";
int i;
for(i=0;i<19;++i)
if(isalpha(str[i]))printf("%c",toupper(str[i]));
}

68)
#include
main()
{
int c;

while((c=getchar()) != 0){
printf("%c",c);
}
}

69)
#include
f( )
{
printf("I am f()");
}
extern f1();
main()
{
int i=10;
f1(i);
}

f1(int i )
{
printf("the i value is %d",i);
f();
}

70)
#include
#define abs(x) x>0?x:-x
#define mabs(x) (((x)>=0)?(x):-(x))
int kabs(int);
main()
{
printf("\n%d %d",abs(10)+1,abs(-10)+1);
printf("\n%d %d",mabs(10)+1,mabs(-10)+1);
printf("\n%d %d\n",kabs(10)+1,kabs(-10)+1);
}
int kabs(int n)
{
return(n>0? n: -n);

}

71)

#include
unsigned char
f(unsigned n)
{
static const unsigned char table[64] = {
0, 0, 0, 9, 0, 0, 10, 1, 0, 0, 0, 0, 0, 11, 2, 21, 7,
0,0, 0, 0, 0, 0,15, 0, 0, 12, 0, 17, 3, 22, 27,32, 8,
0, 0,0, 0, 0, 20, 6, 0, 0, 14,0, 0, 16, 26,31, 0, 0,
19, 5, 13,0, 25, 30, 18, 4, 24, 29, 23, 28, 0
};
return table[((n & -n) * 0x1d0d73df) >> 26];
}
main()
{
printf("%c",f(8));
}

72)
#include
int myfunc(char *str)
{
char *ptr =str;
while(*ptr++);
return ptr-str-1;
}
main()
{
printf("length is %d", myfunc("DESIS"));
}

73)
#include
struct _tag
{
int i;
union
{
int a;
int b;
}c;
} a;

main()
{
a.c.a=10;
printf("test %d\n",a.c.b);
}

74)
#include
main()
{
int a=10,b;
b=a>=5?100:200;
printf("%d\n",b);
}

75)
#include
main()
{
int a;

a = (1,45,012);

printf("%d", a);
}

C Programming Puzzles 4


76)
#include
#define MAXI 100
main(){
int x=6,done,i;
done=i=0;
do
{
if((x/=2)>1)
{i++; continue;}
else
done++;
}while ((i < MAXI) && !done);

printf("%d %d\n",i,done);
}

77)
#include
main()
{
extern int i;
i=20;
printf("%d\n",sizeof(i));
}

78)
#include
fun()
{
printf("Yes\n");
}

#define fun() printf("No\n")

main()
{
fun();
(fun)();
}

79)
#include
main()
{
int i = 1;
switch(i) {
printf("\nHello, ");
case 1: printf("One, ");
i++;
break;
case 2: printf("Two");
break;
}
}

80)
#include
#define DESHAWCURRENTDEBUGLEVEL 1
void main(void)
{
int i = 10 ;
int j = 15 ;

#ifdef DESHAWCURRENTDEBUGLEVEL
printf("%d\n",i);
#else
printf("%d\n",j);
#endif
}

81)
#include
#define scanf "%s DE Shaw"
main()
{
printf(scanf,scanf);
}

82)
#include
main()
{
char *p="abc";
char *q="abc123";

while(*p==*q)
{
printf("%c %c",*p,*q);
p++;q++;
}
}

83)
#include
#define INTPTR int *
main()
{
INTPTR pi, pj;
int i,j;
i=10;j=20;
pi = &j;
pj = &j;
j++;
i= *pi;
printf("%d,",i);
j++;
// i= *pj;
printf("%d",pj);
}

84)
#include
#include
main()
{
char strp[] = "Never ever say no";
char *chp, c='e';
int i,j;
chp = strrchr(strp, c);
i = chp-strp;
for(j=0;j<=i;j++)printf("%c",strp[j]);
}

85)
#include
main()
{
char str[] ="abcdef";
printf("str is %s",str);
str = "DESIS";
printf("str is %s",str);
}

86)
#include
main()
{
int i = 10;
printf(" %d %d %d \n", ++i, i++, ++i);
}

87)
#include
#include
main()
{
char *str ="India pvt. ltd.";
char *str1 = "DESIS";
printf("str is %s",str);
printf("str is %s",str1);
strcpy(str,str1);
printf("str is %s",str);
}

88)
#include
#include
main()
{
char str[] ="DESIS India pvt. ltd.";
const char *str1= str;
strcpy(str1,"DESHAW");
printf("str is %s",str);
}

89)
#include
main()
{
int i=4,j=2,k=0;
char c1='a',c2='b';
if(k==0)printf("k is zero\n");
else if(j==2)printf("j is 2\n");
else if(i==4)printf("i is 4\n");
if(c1!='a')printf("c1 is not a\n");
else if (c2=='a')printf("c2 is b");
else printf("Hello\n");
}

90)
#include
main()
{
int a[3] = {1,2,3};
int i= 2;
printf("\n %d %d\n", a[i], i[a]);
}

91)
#include
void fun(int, int*);
main()
{
int j,i;
int * intptr;
printf("enter an integer\n");
scanf("%d",&i);
intptr = &j;
j = i;
printf("i and j are %d %d \n",i,j);
fun(j,intptr);
printf("i is:%d",i);
printf("\n j is:%d",j);
}
void fun(int k, int *iptr)
{
k++;
(*iptr)++;
return;
}

92)
#include
main()
{
int x;
x = printf("%d\n",x=printf("%d\n",100));
printf("%d\n",x);
}

93)
#include
main()
{
int i;
char c;
for (i=0;i<5;i++){
scanf("%d",&c);
printf("%d",i);
}
}

94)
#include
main()
{
int x = 10,y=2,z;
z=x/*y+y*/+y;
printf("%d\n",z);
}

95)
#include
main()
{
int a[] = {0,1,2,3,4};
int *p[] = {a,a+1,a+2,a+3,a+4};
int **pp = p;

printf("%d, %d, %d ", *pp-a, pp-p, **pp);
pp++; pp++;;++pp;*++pp;
printf("%d, %d, %d ", pp-p, *pp-a, **pp);
}

96)
#include
#include
#include
main()
{
int *p, *c, i;
i = 5;
p = malloc(sizeof(i));
printf("\n%d",*p);
*p = 10;
printf("\n%d %d",i,*p);
c = calloc(2,i);
printf("\n%d\n",*c);
}

97)
#include
main()
{
char input[] = "SSSWILTECH1\1\1";
int i, c;
for ( i=2; (c=input[i])!='\0'; i++)
{
switch(c)
{
case 'a': putchar ('i'); continue;
case '1': break;
case 1: while (( c = input[++i]) != '\1' && c!= '\0');
case 9: putchar('S');
case 'E': case 'L': continue;
default: putchar(c);continue;
}
putchar(' ');
}
putchar('\n');
}

98)
#include
main()
{
unsigned int k = 987 , i = 0;
char trans[10];

do
{
trans[i++] = (k%16 > 9) ? (k%16 - 10 + 'a') : (k%16 - '0' );

} while(k /= 16);

for(i=0;i<10;i++)
printf("%c", trans[i]);
}

99)
#include

main()
{
unsigned int k = 987 , i = 0;
char trans[10];

do {
trans[i++] = (k%16 > 9 ? k%16 - 10 + 'a' : k%16 - '0' );
printf("%d %d\n",k,k%16);

} while(k /= 16);

printf("%s\n", trans);
}

100)
#include
main()
{
char *pk;
const char* p;
const char c = 'a';
char c1='b';
p=&c1;
pk = &c;
printf("%c %c",*pk,*p);
}

C Programming Puzzles 5

101)
#include
main()
{
int i=4;
if (i>5) printf("Hi");
else f(i);
}

f(int j)
{
if (j>=4) f(j-1);
else if(j==0)return;
printf("Hi");
return;
}

102)
#include
int *NEXT(register int i)
{
int *ipt;
ipt = &i;
ipt++;
return ipt;
}

main ()
{
int j;
printf("%d",(NEXT(j)));
}

103)
#include
#define PRINT(int) printf("int = %d ",int)
main()
{
int x,y,z;
x=03;y=02;z=01;
PRINT(x^x);
z<<=3;PRINT(x);
y>>=3;PRINT(y);
}

104)
#include
#define PRINT(int) printf( "int = %d ", int)
main()
{
int x=03,y=02,z=01;
PRINT (x | y & ~z);
PRINT (x & y && z);
PRINT (x ^ y & ~z);
}

105)
#include
main()
{
int p;
for(p = 1; p<=10,--p; p=p+2)
puts("Hello");
}

106)
#include
int n, R;
main()
{
R = 0;
scanf("%d",&n);
printf("\n %d, %d",fun(n),R);
}

int fun(int n)
{
if (n>3) return R = 5;
R = 6;
return(1);
}

107)
#include
main()
{
int arr[3][3] = {1,2,3,4,5,6,7,8,9};
int i,j;
for (j=2;j>=0;j--){
for(i=2;i>=0;i--){
printf("\n%d",*(*(arr+i)+j));
printf("\n TATATATA");
}
}
}

108)
#include
main()
{
int a = 10, b = 5,c = 3,d = 3;

if ((a printf(" %d %d %d %d ", a, b, c, d);
else
printf(" %d %d %d %d ", a, b, c, d);

}

109)
#include
main()
{
struct test
{
char c;
int i;
char m;
} t1;
printf("%d %d\n",sizeof(t1), sizeof(t1.c));
}

110)
#include
main()
{
int a,b;
scanf("%d %d", &a, &b);
printf("%d\n", a+++b);
printf("%d %d\n",a,b);
}

111)
#include
int i;
main()
{
char a[] = "Shiva";
printf("%c\n",i[a]);
}

112)
#include
myread(a,b)
{
printf("%d %d",a,b);
}

main()
{
myread(2,4);
}

113)
#include
funct(char* str)
{
printf("%s\n",str);
}

main()
{
static int ii = 1;
int jj = 5;
ii+=++jj;
funct(ii+++ "Campus Interview");
}

114)
#include
funct(str)
{
printf("%s\n",str);
}

main()
{
funct('-'-'-'+"DEShaw");
}

115)
#include
main()
{
printf(" %d\n",'-'-'-'+'/'/'/');
}

116)
#include
static int a = 6;
extern int a;

main()
{
printf("%d",a);
}

117)
#include
main()
{
int i=6,j=4;
printf("NO\n");
switch(i)
{
do{
case 1: printf("yes\n");

case 2:

case 3:

case 4:

case 5:

case 6:
j--;
}while (j);
}
}

118)
#include
abc(int *i, int *j)
{
*i = *i + *j;
*j = *i - *j;
*i = *i - *j;
}
main()
{
int i = 5, j=10;
abc(&i,&j);
printf("%d..%d",i,j);
}

119)
#include
int main()
{
char c;
c=255;
printf("%d",c);
return(0);
}

120)
#include
main()
{
int x=5,p=10;
printf("%*d",x,p);
}

121)
#include
main()
{
int a[]={2,3,4,5,6};
int i=0;
printf("%d",a[i++]+i[a+1]);
}

122)
#include
#include
main()
{
int *ptr=(int*)malloc(sizeof(int));
*ptr=4;
printf("%d",*ptr++);
}

123)
#include
main()
{
float x=3.14;
printf("%e, %E, %f",x,x,x);
}

124)
#include
int main(int k)
{
if(k<10)
printf("%d ",main(k+1));
return k;
}

125)
#include
main()
{
int i=4;
printf("%d %d %d",++i,i++,i*i);
printf("\n");
printf("%d %d %d",i*i,++i,i++);
}

C programming questions!!

Well, to all the C programmers out there.. here are some of the questions which I
bet you would surely enjoy solving...


1)
Find the bug in this code.
#include
int main()
{
int i=3,j=5;
printf("%d",(i+j)++);
return(0);
}
Ans:



2)
What is the output of the following piece of code?
#include
int main()
{
char c='8';
int d=8;
printf("%d %d %d",d,d+=c>='0'&&c<='9',c++);
return(0);
}
Ans:



3)
x=x*y+1; --------------1
Is this different from x=x*(y+1); --------------2

How to right the assignment operation "2" with out using
parenthesis in one statement.
Ans:




4)
What does this code do?
#include
void func(char s[],int c)
{
int i,j;
for(i=j=0;s[i]!='\0';i++)
if(s[i]!=c)
s[j++]= s[i] + s[i]==c ;
s[j]='\0';
}

int main()
{
char s[]="aelloworld";
func(s,'k');
printf("%s",s);
return(0);
}
Ans:



5)
Can you find any difference between the two scanf calls made in the
code given below ?

#include
int main()
{
int x,y;
scanf("%d",&x);
scanf(" %d",&y);
return 0;
}
Ans:




6)
Predict the output of the following piece of code.
Assume that bit position 0 is at the right end and that i and j are
sensible positive values.
#include
unsigned getbits(unsigned a,int i,int j)
{
return(a>>(i+1-j)) & ~(~0<}
int main()
{
unsigned num=128;
printf("%d\n",getbits(num,7,5));
return(0);
}
Ans:



7)
What does this code do on input 'abcd' from console?
#include
int main()
{
char c;
while(c=getchar()!='\n')
printf("%d",c);
return(0);
}
Ans:


8)
What does this code do?
#include
int main()
{
int i;
int a[20]={1,2,3,4,5,6,7,8,9,10,10,9,8,7,6,1,2,3,4,5};
int n=20;
for(i=0;i<20;i++)
{
printf("%6d%c",a[i],(i%10==9 || i== 19)?'\n':' ');
}
return(0);
}
Ans:



9)
Will this code work properly? If yes why? If not why not?
#include
void swap(int *a,int *b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}
int main()
{
int a=3617283450;
int b=3617283449;
swap(&a,&b);
printf("%d %d\n",a,b);
return(0);
}
Ans:



10)
What is the output of the following piece of code?
#include
int main()
{
int a=3,b=1;
a = b<
>2;
b = b<
>2;
printf("%d %d",a,b);
return 0;
}
Ans:



11)
Can you predict the output of the following code snippet ?
#include
int main()
{
int i=9876;


printf("%d\n",printf("%d",printf("%d",i)));


return 0;
}
Ans:




12)
Give the output of the following code.
#include
typedef struct s
{
int a[10];
}s;
typedef struct t
{
int *a;
}t;

int main()
{
s s1,s2;t t1;
s1.a[0]=0;

t1.a=s1.a;
s1.a[0]++;
s2=s1;
s1.a[0]++;

printf("%d %d %d",s1.a[0],s2.a[0],t1.a[0]);
return 0;
}
Ans:



13)
You just have to write the declaration of an unsigned int p;
Obviously you can't use any spaces or new lines in the declaration !!
Ans:




14)
What is the output of the following code?
#include
int main()
{
int x=2,y=3,z1,z2;
z1=x + + + y;
z2=x+++y;
printf("%d %d %d %d",x,y,z1,z2);
return 0;
}
Ans:



15)
Predict the output of the following code with the following inputs ->
1. 2c3
2. 2 5
#include
#include
int main()
{
int *i=0,*j=4;
i=(int*)malloc(sizeof(int));
scanf("%dc%d",&i,&j);
printf("%d %d",i,j);
return(0);
}
Ans:




16)
What is the output of the following code for the input "dcba"?
#include
#include
int main()
{
char c;
while (c=getchar()!='a') printf("%d",c);
return 0;
}
Ans:



17)
What is the output of the following code?
#include
int array[]={1,2,3,4,5,6,7,8};
#define SIZE (sizeof(array)/sizeof(int))

int main()
{
printf("%d",SIZE);
if(-1<=SIZE) printf("1");
else printf("2");
return 0;
}
Ans:



18)
What is the output of the following code?
#include
#include
int main()
{
char a[]="aaa";
char *b="bbb";
strcpy(a,"cc");
printf("%s",a);
strcpy(b,"dd");
printf("%s",b);
return 0;
}
Ans:




19)
Can you predict the output of the following code snippet ?
#include
#define sq(x) x*x
int main()
{
int a=3;
printf("%d\n",sq(a+3));
}
Ans:



20)
What is the output of this code?
#include
int main()
{
int *i=0;
printf(" %p\n",i);
return(0);
}
Ans:




21)
Does the following C code compile ???? If it does .. can you
explain what happens when you run it with some arbitrary text
as input or what does it do ????
[ The input is redirected from a file called "input.txt" ]
int main()
{
for(;scanf("%*[^a-z]")+1;putchar(getchar()));
}
Ans:




22)
What is the output of the following code?
#include
int main()
{
int a=1,b=3,c,d;
c=(a,b);
d=a,b,c;
printf("%d %d",c,d);
return 0;
}
Ans:




23)
What is the expected output of the code ?????
#include
#define concatinate(a,b) a##b
#define same1(a) #a
#define same2(a) same1(a)
int main()
{
printf("%s\n",same2(concatinate(1,2)));
printf("%s\n",same1(concatinate(1,2)));
return 0;
}
Ans:



24)
The intention of the following program was to print 42 astericks('*')
But it fails to do so.
You have to add/replace/delete exactly one character in the program
to make it work ???
Find as many solutions as possible.

#include
int main()
{
int n = 42;
for(int i = 0; i < n; i-- )
printf("*");
return 0;
}
Ans:























25)
What does this code do?
#include
void insert(char s[],int c)
{
int i,j;
for(i=j=0;s[i]!='\0';i++)
if(s[i]!=c)
s[j++]= s[i];
s[j]='\0';
}

int main()
{
char s[]="helloworld";
insert(s,'l');
printf("%s",s);
return(0);
}
Ans:




26)
What is the output of the following code?
#include
#include
int s(char *A[20],char *B[20])
{
char *a,*b;
a=A;b=B;
while(*a++!=*b++); *a=*b='\0';
return strlen(A);
}
int main()
{
char A[20]="somestring",
B[20]="debugthecbug";
printf("%d %s %s\n",s(&A,&B),A,B);
return 0;
}
Ans:




27)
Can you predict the output ?
#include
#define print(var) printf("%s : %d\n",#var,(var))
int main()
{
int y = 100;
int *p;
p = new int;
*p = 10;
y = y/*p; /*dividing y by *p */;
print(y);
return 0;
}
Ans:



28)
Take the input as 4, and write the output of the following code.
#include
main()
{
int i=0;
printf("%d %d\n",scanf(" %d",&i),i);
printf("%d %d\n",i=4,i);
}
Ans:



29)
Predict the output of the following program.
#include
int main()
{



int a=3, b = 5;
printf(&a["Ya!Hello! how is this? %s\n"], &b["junk/super"]);
printf(&a["WHAT%c%c%c\n%c%c\n%c !\n"], 1["this"],
2["beauty"],0["tool"],0["is"],3["sensitive"],4["CCCCCC"]);


return 0;
}
Ans:





30)
What is the output of the following code?
#include
#include
int main()
{
int *ptr=(int*)malloc(sizeof(int));
*ptr=4;
printf("%d",(*ptr)+++*ptr++);
return(0);
}
Ans:




31)
What is the output of the following piece of code?
#include
int main(int k)
{
if(k<10)
printf("%d ",main(k+1));
return k;
}
Ans:





32)
Predict the output or error if any in the following code.
#include
main()
{
int i = 4;
printf("%d %d %d",++i,i++,i*i);
printf("\n");
printf("%d %d %d",i*i,++i,i++);
system("PAUSE");
}
Ans:



33)
Give the output of the following piece of code.
#include
int main()
{
int a,b,c=2,d=10;


printf("%d\n ",scanf("%d%d%d",&a,&b,&c,&d) ) ;


printf("%d\n%d\n%d\n%d\n",a,b,c);
return(0);
}
Ans:



34)
#include
main()
{
int a[15][10][5]={1};
func(a);
}
Which of these is/are correct function prototypes for func ?

void func( int a[][10][5] );
void func( int a[15][][5] );
void func( int a[15][10][] );
Ans:





35)
Give the output of the following piece of code.
#include
main()
{
float x=3.14;
printf("%e, %E, %f",x,x,x);
}
Ans:



36)
What is the output of the following program?
#include
int fun1()
{
static int c=20;
return --c;
}

int fun2()
{
static int c=1;
return fun1()+c--;
}

int main()
{
int i=0;
while(i printf("%d ",i++);
return 0;
}
Ans:



37)
What is the output of the following program?
#include
#include
void p(char *a)
{
static int y=1;
if(y=1-y) printf("%c",*a);
return;
}

int main()
{
char *a;a=(char*)malloc(20*sizeof(char));
strcpy(a,"DbugtheCbug");
while(*a!='\0') p(a++);
printf("\n");
return 0;
}
Ans:



38)
Give the output of the following piece of code.
#include
main()
{
int a=4,b=10;


printf("%d %d %d %d\n",a,a^=b=b^=a=a^=b,b,printf("%d %d %d\n",b,a,a^=b=b^=a=a^=b));


}
Ans:




39)
Predict the output of the following program.
#include
int main()
{
int x = 5,p = 10;
printf("%*d",x,p);
}
Ans:




40)
What is the output of the following code?
#include
int main()
{
int i=2;
i=i++;
printf("%d ",i++ + i++);
}
Ans:




41)
Predict the output for the below code.
#include
int main()
{
int a[]={2,3,4,5,6};
int i=0;
printf("%d",a[i++]+i[a+1]);
return(0);
}
Ans:



42)
What is the output of the following piece of code?
#include
#include
void weird(int *a)
{
a=(int*)malloc(sizeof(int));
}
int main()
{
int *a;
weird(a);
*a=6;
printf("%d\n",*a);
return(0);
}
Ans:



43)
What is the output of the following piece of code?
#include
#include
int main()
{
int *ptr=(int*)malloc(sizeof(int));
*ptr=4;
printf("%d",*ptr++);
return(0);
}
Ans:




44)
Correct the following code in case of any errors.
#include
#include
#define SIZE 15
int main()
{
int *a, i;
a = (void*)malloc(SIZE*sizeof(int));
for (i=0; i *(a + i) = (int)i * i;
for (i=0; i printf("%d\n", *a++);
free(a);
return 0;
}
Ans:




45)
What is the output of the following program?
#include
int main()
{
char c;
c=255;
printf("%d",c);
return(0);
}

Wednesday, July 23, 2008

C Programming Puzzles 6.


126)
#include
main()
{
char c='6';
int d=6;
printf("%d %d %d",d,d+=c>'0'&&c<='7',c++);
}

127)
#include
main()
{
int a=4,b=2;
a=b<>2;
b=b<
>2;
printf("%d %d",a,b);
}

128)
#include
main()
{
int i=98765;
printf("%d\n",printf("%d",printf("%d",i)));
}

129)
#include
main()
{
char c;
while(c=getchar()!='a')printf("%d",c);
}
//INPUT=dcba

130)
#include
main()
{
int *i=0;
printf(" %p\n",i);
}

131)
#include
#include
main()
{
int *ptr=(int*)malloc(sizeof(int));
*ptr=4;
printf("%d",(*ptr)+++*ptr++);
}

132)
#include
unsigned getbits(unsigned a,int i,int j)
{
return(a>>(i+1-j)) & ~(~0<}
main()
{
unsigned num=128;
printf("%d\n",getbits(num,7,5));
}

133)
#include
#define sq(x) x*x
main()
{
int a=5;
printf("%d\n",sq(a+5));
}

134)
#include
#define concatinate(a,b) a##b
#define same1(a) #a
#define same2(a) same1(a)
main()
{
printf("%s\n",same2(concatinate(1,2)));
printf("%s\n",same1(concatinate(1,2)));
}

135)
#include
main()
{
int a=1,b=3,c,d;
c=(a,b);
d=a,b,c;
printf("%d %d",c,d);
}

136)
#include
#include
main()
{
int*ptr=(int*)malloc(sizeof(int));
*ptr=4;
printf("%d",(*ptr)+++*ptr++);
}

137)
#include
main()
{
int x;
x=20;
printf("x:%d\n",x);
printf("sizeof(x++) is: %d\n",sizeof(x++));
printf("x:%d\n",x);
}

138)
#include
#define f(x,y) x##y
#define g(x) #x
#define h(x) g(y)

int main()
{
printf("%s\n",h(f(2,3)));
printf("%s\n",g(f(2,3)));
return 0;
}

139)
#include
int main()
{
int i;
i = 10,20,30;
printf("i:%d\n",i);
}

140)
#include
#define PrintInt(expr) printf("%s : %d\n",#expr,(expr))
int Shiftfn(int a)
{
int t;
t = a<<2 + a;
return t;
}

int main()
{
int i = 1, j = 2,k = 3;
PrintInt(Shiftfn(i));
PrintInt(Shiftfn(j));
PrintInt(Shiftfn(k));
}

141)
#include
enum {false,true};

int main()
{
int i=1;
do
{
printf("%d\n",i);
i++;
if(i < 15)
continue;
}while(false);
}

142)
#include
int main()
{
float a = 12.5;
printf("%d\n",a);
printf("%d\n", *(int *)&a);
return 0;
}

143)
#include
int main()
{
int a=1;
switch(a)
{ int b=20;
case 1: printf("b is %d\n",b);
break;
default:printf("b is %d\n",b);
break;
}
return 0;
}

144)
#include
#include
int s(char*A[20],char*B[20])
{
char *a,*b;
a=A,b=B;
while(*a++!=*b++);
*a=*b='\0';
return strlen(A);
}

int main()
{
char A[20]="somestring",B[20]="debugthecbug";
printf("%d %s %s\n",s(&A,&B),A,B);
return 0;
}

145)
#include
void insert(char a[],int n)
{
int i,j;
for(i=j=0;a[i]!='\0';i++)
if(a[i]!=n)
a[j++]=a[i];
a[j]='\0';
}
main()
{
char a[]="helloworld";
insert(a,'l');
printf("%s",a);
}

146)
#include
#include
void weird(int*a)
{
a=(int*)malloc(sizeof(int));
}
main()
{
int*a;
weird(a);
*a=6;
printf("%d\n",*a);
}

147)
#include
main()
{
int a=4,b=10;
printf("%d %d %d %d\n",a,a^=b=b^=a=a^=b,b,printf("%d %d %d\n",
b,a,a^=b=b^=a=a^=b));
}

148)
#include
int fun1()
{
static int c=20;
return --c;
}

int fun2()
{
static int c=1;
return fun1()+c--;
}

int main()
{
int i=0;
while(i printf("%d ",i++);
return 0;
}

149)
#include
#include
main()
{
char a[]="aaa";
char *b="bbb";
strcpy(a,"cc");
printf("%s",a);
strcpy(b,"dd");
printf("%s",b);
}

150)
#include
int array[]={1,2,3,4,5,6,7,8};
#define SIZE (sizeof(array)/sizeof(int))

int main()
{
printf("%d",SIZE);
if(-1<=SIZE) printf("1");
else printf("2");
return 0;
}

Basic C Interview Questions


These are few basic Interview questions in C .....

1)How do we check whether a linked list is circular?

2)What is the output of this program?

#include
##include
main()
{
typedef union
{
int a;
char b[10];
float c;
}
Struct;

Struct x,y = {100};
x.a = 50;
strcpy(x.b,"hello");
x.c = 21.50;

printf("Union x : %d %s %f \n",x.a,x.b,x.c );
printf("Union y : %d %s %f \n",y.a,y.b,y.c);
}

3)What is a Null object?

4)Name some pure object oriented languages.

5)What is a container class? What are the different types of container classes?

6)What will be the output of the following program:
#include
main()
{
printf("%x",-1<<4);
}

7)What are the major differences between C and C++?

8)What is an incomplete type?

9)What are printf and scanf, call by reference or call by value?

10)What is a const pointer?

11)When should a type cast be used and when should it not be used?

12)Which is the easiest sorting method?

13)Which is the quickest sorting method?

14)Which are the best sorting algorithms to sort a linked list?

15)What is a preprocessor and what will it do for a program?

16)How can a string be converted into a number?

17)How can a number be converted into a string?

18)What is a heap?

19)Why does n++ execute much faster than n+1?

20)What is modular Programming?

21)Which expression always returns true and which expression always returns false?

22)What is the difference between "malloc" and "calloc"?

23)Is C
a)A low level language
b)A middle level language
c)A high level language ?

24)Why doesn't C support function overloading?

25)What is the difference between global int & static int declaration?

Heaps And Heapsort

A heap is a specialized tree-based data structure that satisfies the heap property.If Y is the child node of X,then key(X) >= key(Y). Such a heap is called a max heap and the opposite one is called a min heap.

The operations commonly performed with a heap are:

1)delete-max or delete-min:removing the root node of a max or min-heap,respectively.
2)increase-key or decrease-key:updating a key within a max or min-heap,respectively.
3)merge:joining two heaps to form a valid new heap containing all the elements of both.

Heaps are used in the sorting algorithm called heapsort.

HEAPSORT:

Heap sort is one of the best methods being in-place and with no quadratic worst case scenarios.It is a comparision based sorting algorithm, ans is part of the selection sort family.The operations performed by heap sort algorithm are:

BUILD-MAX-HEAP:To build a max heap with the given [1,n] elements.
MAX-HEAPIFY:Which modifies a heap with [1,n-1] elements so that it satifies the properties of a heap.

The following are the basic questions on heaps:

1)What are the properties of a heap?
2)What is the height of an n-element heap?
3)Where in a max-heap might the smallest element reside, assuming that all the elements are distinct?
4)Is an array that is in sorted order a min-heap?
5)What are the minimum and maximum numbers of elements in a heap of height h?
6)How many nodes are present in an n-element heap of height h?
7)What is the running time complexity of a heapsort?
8)What is the worst-case running time of a heapsort?
9)What is the running time of heapsort on an array A of length n that is alreay sorted in increasing order? What about the same in decreasing order?
10)What is the best case running time of heapsort when all the elements are distinct?
11)Name some applications of heaps

Trees - Programming Interview Questions

1. Write a C program to find the depth or height of a binary tree.

Click Here For Solution

2. Write a C program to determine the number of elements (or size) in a binary tree.

Click Here For Solution

3. Write a C program to delete a tree (i.e, free up its nodes)
Click Here For Solution


4. Write a C program to find the minimum value in a binary search tree.

Click Here For Solution

5. Write a C program to create a mirror copy of a tree (left nodes become right and right nodes become left)
Click Here For Solution

6. Write C code to implement the preorder(), inorder() and postorder() traversals. Whats their time complexities?
Click Here For Solution
7. Write a C program to create a copy of a tree
Click Here For Solution

8. Write a C program to check if a given binary tree is a binary search tree or not?
Click Here For Solution

9. Write a C program to implement level order traversal of a tree.
Solution:Breadth First Search of the tree gives the level order traversal.

10. Write a C program to delete a node from a Binary Search Tree?
Click Here For Solution

11. Write a C program to search for a value in a binary search tree (BST).
Click Here For Solution
12. Write a C program to count the number of leaves in a tree
Click Here For Solution
13. Write a C program for iterative preorder, inorder and postorder tree traversals
Solution:Use stacks to depict the function calls.Not much different from routine traversals.

Dynamic Programming

Dynamic Programming is a method of solving problems exhibiting the properties of overlapping subproblems and optimal substructure that takes much less time than naive methods.It is typically applied to optimization problems.

Longest Common subsequence and substring:

Longest Common subsequence and substring are two applications of Dynamic Programming.The longest common subsequence problem is finding the longest subsequence common to all sequences in a set of sequences (often just two) while longest common substring is finding the longest substring.

1)Determine an LCS of {1,0,0,1,0,1,0,1} and {0,1,0,1,1,0,1,1,0}.
2)Give an algorithm to find the Longest common subsequence of sequences with lengths m,n respectively and also analyze their time complexities.
3)Give an algorithm to find the Longest common string of strings with lengths m,n respectively and also analyse their time complexities.
4)Give an O(n^2) time algorithm to find the longest monotonically increasing subsequence of a sequence of n numbers.
5)Give an O(n^2) time algorithm to find the longest monotonically increasing subsequence of a sequence of n numbers.
6)What is the difference between longest common subsequence and longest common substring
7)State few applications of Dynamic Programming.

Stacks,Queues and Linked lists

1)Explain how to implement two stacks in one array A[1,...,n] in such a way that neither stack overflows unless the total number of elements in both stacks together is n. The run time of PUSH and POP is O(1).

2)Explain how to implement a queue using two stacks. Analyse the running time of the queue operations.

3)Explain how to implement a stack using two queues. Analyse the running time of the stack operations.

4)Write four O(1)-time procedures to insert elements into and delete elements from both ends of a deque constructed from an array.

5)Implement a stack using a singly linked list L. The run time of PUSH and POP should be O(1).

6)Implement a queue using a singly linked list L. The run time of ENQUEUE and DEQUE should be O(1).

7)Can the dynamic-set operation INSERT be implemented on a singly linked list in O(1) time? What about DELETE?

8)Implement the dictionary operations INSERT,DELETE and SEARCH using singly linked,circular lists.What are the running times of the procedures?

9)Give a THETA(n)-time nonrecursive procedure that reverses a singly linked list of n elements. The procedure should use no more than constant storage beyond that needed for the list itself.

10)Write the operations of INSERT, DELETE and SEARCH in a linked list.Also, how do we reverse a linked list?

Some Questions on Recursion

1)Given a number n, find the nth Fibinocci number.

2)Using recursion,reverse a given string.

3)Find the factorial of a given number.

4)Towers of Hanoi: The towers of hanoi problem consists of a set of three poles arranged in a row. There is a set of n disks of decreasing size stacked on one of the poles. The problem is to transfer these disks from the current pole to another by moving only one disk at a time, subject to the constraint that you cannot place a disk on top of a smaller one. Write a program to compute the sequence of moves that will accomplish the task.

5)Find the gcd of 2 numbers using recursion.

6)Given a string, find all the permutations of that string.

7)Given a string and a number x(<=length of that string).Find all the combinations of that string with x characters.

8)Implement a merge sort and quick sort.

Click here for the solutions