P: n/a

I found these questions on a web site and wish to share with all of u
out there,Can SomeOne Solve these Porgramming puzzles.
Programming Puzzles
Some companies certainly ask for these things. Specially Microsoft.
Here are my favorite puzzles. Don't send me emails asking for the
solutions.
Q1 Write a "Hello World" program in 'C' without using a semicolon.
Q2 Write a C++ program without using any loop (if, for, while etc) to
print numbers from 1 to 100 and 100 to 1;
Q3 C/C++ : Exchange two numbers without using a temporary variable.
Q4 C/C++ : Find if the given number is a power of 2.
Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.
Q6 C/C++ : Write a function in different ways that will return f(7) =
4 and f(4) = 7
Q7 Remove duplicates in array
Q8 Finding if there is any loop inside linked list.
Q9 Remove duplicates in an no key access database without using an
array
Q10 Write a program whose printed output is an exact copy of the
source. Needless to say, merely echoing the actual source file is not
allowed.
Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's),
each player selects a number and adds it to the total. Once a number
is used, it must be removed from the pool. The winner is the person
whose number makes the total equal 31 exactly.
Q12 Swap two numbers without using a third variable.
Given an array (group) of numbers write all the possible sub groups of
this group.
Q14 Convert (integer) number in binary without loops.
Q3,12 are similar , Q7 is simple & I know there answer For the Rest
please Help
Wiating for reply.  
Share this Question
P: n/a

Jatinder <js*******@sancharnet.in> scribbled the following
on comp.lang.c: I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles.
Programming Puzzles
Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.
Q1 Write a "Hello World" program in 'C' without using a semicolon. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Q3 C/C++ : Exchange two numbers without using a temporary variable.
Done to death here on comp.lang.c.
Q4 C/C++ : Find if the given number is a power of 2.
Easy with some bitwise arithmetic.
Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.
Easy peasy. Repeated addition will do the trick.
Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7
int f(int x) {
return x==4 ? 7 : x==7 ? 4 : 0;
}
Q7 Remove duplicates in array
You can't remove anything from an array. You can only modify the
values of its elements.
Q8 Finding if there is any loop inside linked list.
Should be covered in any basic data structures course.
Q9 Remove duplicates in an no key access database without using an array
Impossible without access into a no key access database.
Q10 Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed.
Google for "quine".
Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly.
This one is actually a fullblown game.
Q12 Swap two numbers without using a third variable.
And how is this any different from Q3?
Given an array (group) of numbers write all the possible sub groups of this group.
Search for the definition of a "power set". The algorithm shoudln't be
too hard to figure out.
Q14 Convert (integer) number in binary without loops.
Already done here on comp.lang.c.

/ Joona Palaste (pa*****@cc.helsinki.fi)  Finland \
\ http://www.helsinki.fi/~palaste  rules! /
"This isn't right. This isn't even wrong."
 Wolfgang Pauli  
P: n/a

In article <22**************************@posting.google.com >, js*******@sancharnet.in (Jatinder) wrote: I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles.
Programming Puzzles
Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.
Q1 Write a "Hello World" program in 'C' without using a semicolon. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Q3 C/C++ : Exchange two numbers without using a temporary variable. Q4 C/C++ : Find if the given number is a power of 2. Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator. Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7 Q7 Remove duplicates in array Q8 Finding if there is any loop inside linked list. Q9 Remove duplicates in an no key access database without using an array Q10 Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed. Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly. Q12 Swap two numbers without using a third variable. Given an array (group) of numbers write all the possible sub groups of this group. Q14 Convert (integer) number in binary without loops.
Q3,12 are similar , Q7 is simple & I know there answer For the Rest please Help
Assuming that these questions are from an interview for a programming
job, I must say that most of them are incredibly useless at finding a
good programmer. Take Q3: The correct answer is: Why would anyone want
to do that? Take Q10: You know the answer or you don't. If your name is
Gödel or Turing, you might find a solution on your own, but otherwise
this just tests some very obscure knowledge. I guess these questions are
only used to check your reaction to a stressful situation (which is also
an incredibly useless way at finding a good programmer).
If I was given this list of questions, I would tell them that most of
them are pointless and then examine Q11, because it is the only
interesting one. Maybe a different response if you are desperate for a
job.  
P: n/a

"Joona I Palaste" <pa*****@cc.helsinki.fi> wrote in message news:cbkf50$a76 Jatinder <js*******@sancharnet.in> scribbled the following Q1 Write a "Hello World" program in 'C' without using a semicolon. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Q3 C/C++ : Exchange two numbers without using a temporary variable.
Done to death here on comp.lang.c.
Not familiar with the first two. Q1, how? Is #define SEMICOLON ; valid?
Q2, is recursion a valid answer? Or even just writing the numbers
explicitly printf("1\n2"), etc? For Q3 one can use ^= 3 times, though I
wonder if this is faster than the usual one with a temp variable and 3
assignments on various platforms. Q4 C/C++ : Find if the given number is a power of 2.
Easy with some bitwise arithmetic.
x & (x1) evaluates to zero if the number is an exact power of 2. Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.
Easy peasy. Repeated addition will do the trick.
Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7
int f(int x) { return x==4 ? 7 : x==7 ? 4 : 0; }
Another is realize 4 = %100 and 7 = %111 in binary, so leave the leftmost
bit on, and flip the other 2. Thus: return x ^ %11, or return x ^ 3. Q7 Remove duplicates in array
You can't remove anything from an array. You can only modify the values of its elements.
Fine, then how to replace the duplicates with NULL or the like, or move the
elements one down so that { 1, 2, 1, 1, 4, 3 } becomes { 1, 2, 4, 3,
anything, anything }? Q8 Finding if there is any loop inside linked list.
Should be covered in any basic data structures course.
Q9 Remove duplicates in an no key access database without using an array
Impossible without access into a no key access database.
What is Q9 about? Q10 Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed.
Google for "quine".
Bizarre stuff! Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly.
This one is actually a fullblown game.
Q12 Swap two numbers without using a third variable.
And how is this any different from Q3?
Given an array (group) of numbers write all the possible sub groups of this group.
Search for the definition of a "power set". The algorithm shoudln't be too hard to figure out.
Someone posted something like this in the C++ newsgroup. If you have 3
numbers 1, 2, 3 then make a number of 3 bits %000. Then just add 1 until
you max out. So you get %000, %001, %010, %011, %100, %101, %110, %111. If
the bit is 0 it means that number is not in the group and if the bit it 1 it
means the number is in the group, so %001 is the group "1", and %011 is the
group "1,2", and %101 is the group "1,3". In C++ you could maybe use
std::bitset.
But I think you could do it using recursion too. So f(3,1) prints the
combinations "3,..." and f(3,0) prints combinations without the 3. The part
in ... is the combinations with 2 numbers, so f(2,1) prints "2,..." and
f(2,0) prints "...". The second ... is the combinations with 1 numbers,
just "1" and "". Q14 Convert (integer) number in binary without loops.
Already done here on comp.lang.c.
How, if not recursion? Maybe even lookup tables, which I used to implement
a fast lgdown(x) function which gives log to base 2 of x.  
P: n/a

"Siemel Naran" <Si*********@REMOVE.att.net> wrote in message
news:bg*******************@bgtnsc05news.ops.worldnet.att.net... "Joona I Palaste" <pa*****@cc.helsinki.fi> wrote in message
news:cbkf50$a76 Jatinder <js*******@sancharnet.in> scribbled the following
Q1 Write a "Hello World" program in 'C' without using a semicolon. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Q3 C/C++ : Exchange two numbers without using a temporary variable.
Done to death here on comp.lang.c.
Not familiar with the first two. Q1, how? Is #define SEMICOLON ; valid?
no, but consider this
int main (void)
{
if (printf("Hello World"))
{}
if (exit(EXIT_SUCCESS))
{}
}
Allan  
P: n/a

>>>>> "Jatinder" == Jatinder <js*******@sancharnet.in> writes:
Jatinder> I found these questions on a web site and wish to share
Jatinder> with all of u out there,Can SomeOne Solve these
Jatinder> Porgramming puzzles.
Jatinder> Programming Puzzles
Jatinder> Some companies certainly ask for these things. Specially
Jatinder> Microsoft. Here are my favorite puzzles. Don't send me
Jatinder> emails asking for the solutions.
Jatinder> Q1 Write a "Hello World" program in 'C' without using a
Jatinder> semicolon.
Jatinder> Q2 Write a C++ program without using any loop (if, for,
Jatinder> while etc) to print numbers from 1 to 100 and 100 to 1;
void countup(int i){
printf("%d\n",i);
(void) ((i<100)?countup(i+1):i);
}
countup(1);
countdown is left as an excercise ;)
This is C. I'm reading this in comp.lang.c. C++ is offtopic
Jatinder> Q3 C/C++ : Exchange two numbers without using a
Jatinder> temporary variable.
This is a FAQ. There is no good way. (20.15c)
Jatinder> Q4 C/C++ : Find if the given number is a power of 2.
I'd like to know the answer to this one myself.
Jatinder> Q5 C/C++ : Multiply x by 7 without using multiplication
Jatinder> (*) operator.
x<<3x;
this only works if x is unsigned.
Jatinder> Q6 C/C++ : Write a function in different ways that will
Jatinder> return f(7) = 4 and f(4) = 7
int f(int i){
return i^3;
}
Jatinder> Q7 Remove duplicates in array
Jatinder> Q8 Finding if there is any loop inside linked list.
This is similar to Q7. Your looking for duplicate pointer values.
Jatinder> Q9 Remove duplicates in an no key access database
Jatinder> without using an array
Jatinder> Q10 Write a program whose printed output is an exact
Jatinder> copy of the source. Needless to say, merely echoing the
Jatinder> actual source file is not allowed.
This is a FAQ. 20.34
Jatinder> Q11 From a 'pool' of numbers (four '1's, four '2's
Jatinder> .... four '6's), each player selects a number and adds
Jatinder> it to the total. Once a number is used, it must be
Jatinder> removed from the pool. The winner is the person whose
Jatinder> number makes the total equal 31 exactly.
Jatinder> Q12 Swap two numbers without using a third variable.
See Q3
Jatinder> Given an array (group) of numbers write all the possible
Jatinder> sub groups of this group.
Jatinder> Q14 Convert (integer) number in binary without loops.
Jatinder> Q3,12 are similar , Q7 is simple & I know there answer
Jatinder> For the Rest please Help
I'd say Q3 and Q12 are identical.
Jatinder> Wiating for reply.

Dale Henderson
"Imaginary universes are so much more beautiful than this stupidly
constructed 'real' one..."  G. H. Hardy  
P: n/a

Allan Bruce wrote:
.... snip ... no, but consider this
int main (void) { if (printf("Hello World")) {} if (exit(EXIT_SUCCESS)) {} }
Illegal. No #include for prototype of variadic function, nor
EXIT_SUCCESS value, and exit is a void function. The compiler
should barf.
I am trying to construct something that revolves around:
if (printf("Hello ")  printf("World\n")) {...}
which statement could cause either "Hello World" or "WorldHello".

Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!  
P: n/a

"Christian Bau" <ch***********@cbau.freeserve.co.uk> wrote in message
news:ch*********************************@slbnewsm1.svr.pol.co.uk... In article <22**************************@posting.google.com >, js*******@sancharnet.in (Jatinder) wrote:
Programming Puzzles
Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.
Q1 Write a "Hello World" program in 'C' without using a semicolon. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Q3 C/C++ : Exchange two numbers without using a temporary variable.
[snip] If I was given this list of questions, I would tell them that most of them are pointless and then examine Q11, because it is the only interesting one. Maybe a different response if you are desperate for a job.
Maybe you would get the job for walking out...  
P: n/a

"Mabden" <mabden@sbc_global.net> wrote in message news:B5uDc.6258 Maybe you would get the job for walking out...
That might be too out of the box :).  
P: n/a
 js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>...
[ ... ] Q1 Write a "Hello World" program in 'C' without using a semicolon.
One obvious method (open to a number of variations) is:
#include <stdio.h>
int main() {
if ( printf("Hello world"))
{}
}
Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;
Almost anything you'd normally do with iteration can also be done with
tail recursion.
Q3 C/C++ : Exchange two numbers without using a temporary variable.
This has come up about 4 weeks into every new semester for years, with
a slightly lighter treatment on a quarterly basis.
Q4 C/C++ : Find if the given number is a power of 2.
There are many ways. Pick N as a power of 2, and compare it to N1
and see if something doesn't occur to you.
Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.
One is to just add x together 7 times. Those of us who remember
writing multiplication routines for old processors that didn't have
multiply instructions can easily reduce that to (x<<2)(x<<1)x.
Those who've studied Booth's algorithm might try (x<<3)x, though
without extra bits for the intermediate value, this can overflow.
Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7
Obvious:
int f(int x) {
if ( x == 7)
return 4;
if ( x == 4)
return 7;
}
Roughly as obvious is to use switch/case intsead.
Using arrays, you can do things like:
int f(int x) {
int rets[] = { 4, 7};
return rets[x>>2];
}
Or if you want to ensure defined results for inputs other than 4 or 7:
int f(int x) {
int rets[] = {4,7};
return rets[(x>>2)&1];
}
If you want to get clever with boolean values, you could try:
int f(int x) {
return (x==7*4)+(x==4*7);
}
or:
int f(int x) {
rturn (x==7*4)(x==4*7);
}
If you prefer strictly bitwise manipulation, you might prefer:
int f(int x) {
return x ^ 3;
}
I'm sure there are more variations as well.
Q7 Remove duplicates in array
You can't really "remove" an element from an array, so this is poorly
defined. If it was a C++ vector (for example) std::sort and
std::unique would render it trivial, as would inserting the elements
into an std::set, and then copying them back out. Doing it quickly
while retaining the original order is a little more challenging.
Q8 Finding if there is any loop inside linked list.
One obvious way would be to create a set of pointers to nodes. Walk
the list, inserting each node's address into the set. Quit when you
reach a node with next == NULL (there's no loop) or a node whose
address is already in the set (there's a loop).
There's an alternative that saves memory, but basically destroys the
list if it does contain a loop: as you walk the list, modify each
'next' pointer to point at the previous node. Eventually, you'll
reach either a node with next==NULL, in which case there's no loop, or
else you'll get back to the original head of the list (in which case
there's a loop, and you've wreaked havoc on your list). If the list
doesn't contain a loop, you can rewalk it, again reversing each
pointer, to restore the original list.
Better yet, just ensure the list is constructed sanely, and you'll
know the answer upfront.
Q10 Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed.
Much like Q3, but comes up a little further into the semster/quarter.
Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly.
If I'm figuring this correctly, it's a pretty boring game. If I go
first, I pick '1' on my first two moves, and you can't win. If I go
second, I pick '2' on my first three moves, and you can't win.
Tictactoe quickly gets boring because neither player can win unless
his opponent makes a mistake. This is even worse, because the same is
true, BUT a player doesn't even have to look at what his opponent has
done to avoid a mistake. The only challenge is ensuring that you take
advantage when he does make a mistake, and (again, assuming I'm
figuring things correctly) that should be quite trivial.
Given an array (group) of numbers write all the possible sub groups of this group.
Recursion is probably your friend on this one as well.
Q14 Convert (integer) number in binary without loops.
As mentioned wrt Q2, almost any iteration is trivially expressed as
tail recursion. The wording doesn't make it clear whether this is
supposed to be a conversion FROM binary or TO binary, but either is
pretty easy to do recursively.

Later,
Jerry.
The universe is a figment of its own imagination.  
P: n/a

"Jerry Coffin" <jc*****@taeus.com> wrote in message
news:b2*************************@posting.google.co m... Almost anything you'd normally do with iteration can also be done with tail recursion.
What is "tail" recursion? Are there other types of recursion?
Any the question says not to use loops. But to me, recursion is a loop,
just expressed differently. Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.
One is to just add x together 7 times. Those of us who remember writing multiplication routines for old processors that didn't have multiply instructions can easily reduce that to (x<<2)(x<<1)x. Those who've studied Booth's algorithm might try (x<<3)x, though without extra bits for the intermediate value, this can overflow.
Are these methods faster than x*7 on modern processors? Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7
If you want to get clever with boolean values, you could try:
int f(int x) { return (x==7*4)+(x==4*7); }
Huh?
I'm sure there are more variations as well.
Probably something with mod or %.
Q7 Remove duplicates in array
You can't really "remove" an element from an array, so this is poorly defined. If it was a C++ vector (for example) std::sort and std::unique would render it trivial, as would inserting the elements into an std::set, and then copying them back out. Doing it quickly while retaining the original order is a little more challenging.
The sort method is O(N*lg(N)) + O(N) if we use comparison sort. But doing
it in place without changing the order seems to be an O(N^2) algorithm, with
the outer loop i running from [0, N) and the inner loop j running from [0,
i). (Seems most people run the inner loop from [i+1, N) and then they run
into problems of how to detect if you've not seen the element already.) Q8 Finding if there is any loop inside linked list.
One obvious way would be to create a set of pointers to nodes. Walk the list, inserting each node's address into the set. Quit when you reach a node with next == NULL (there's no loop) or a node whose address is already in the set (there's a loop).
There's an alternative that saves memory, but basically destroys the list if it does contain a loop: as you walk the list, modify each 'next' pointer to point at the previous node. Eventually, you'll reach either a node with next==NULL, in which case there's no loop, or else you'll get back to the original head of the list (in which case there's a loop, and you've wreaked havoc on your list). If the list doesn't contain a loop, you can rewalk it, again reversing each pointer, to restore the original list.
Better yet, just ensure the list is constructed sanely, and you'll know the answer upfront.
There's another. Have two iterators, first one pointing to first element,
the second pointing to the second. The second one is the fast iterator and
you increment it twice in each iteration. The first iterator is the slow
iterator and you increment it once in each iteration. If the list is not
circular the fast iterator will hit NULL at some point. If the list is
circular the fast iterator will equal to the slow iterator at some point.  
P: n/a

Siemel Naran <Si*********@remove.att.net> scribbled the following
on comp.lang.c: "Jerry Coffin" <jc*****@taeus.com> wrote in message news:b2*************************@posting.google.co m... Almost anything you'd normally do with iteration can also be done with tail recursion.
What is "tail" recursion? Are there other types of recursion?
Tail recursion is first doing the computation, then recursing. Head
recursion is the other way around.
Any the question says not to use loops. But to me, recursion is a loop, just expressed differently.
They're clearly different concepts. At least in C, recursion has a
separate local scope for all levels, while looping reuses the same
local scope for all iterations. > Q6 C/C++ : Write a function in different ways that will return f(7) = > 4 and f(4) = 7
If you want to get clever with boolean values, you could try:
int f(int x) { return (x==7*4)+(x==4*7); }
Huh?
In C, the == operator returns 1 if the operands match or 0 if they
don't. Go from there.

/ Joona Palaste (pa*****@cc.helsinki.fi)  Finland \
\ http://www.helsinki.fi/~palaste  rules! /
"The day Microsoft makes something that doesn't suck is probably the day they
start making vacuum cleaners."
 Ernst Jan Plugge  
P: n/a

"Siemel Naran" <Si*********@REMOVE.att.net> wrote: "Jerry Coffin" <jc*****@taeus.com> wrote in message news:b2*************************@posting.google.c om...
<snip> > Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.
<snip> If you want to get clever with boolean values, you could try:
int f(int x) { return (x==7*4)+(x==4*7); }
Huh?
I'm pretty sure Jerry meant to write:
return (x==7)*4 + (x==4)*7;
Regards

Irrwahn Grausewitz (ir*******@freenet.de)
welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt
clc faqlist : http://www.faqs.org/faqs/Cfaq/faq/
clc OT guide : http://benpfaff.org/writings/clc/offtopic.html  
P: n/a

Joona I Palaste <pa*****@cc.helsinki.fi> wrote: Siemel Naran <Si*********@remove.att.net> scribbled the following on comp.lang.c: "Jerry Coffin" <jc*****@taeus.com> wrote in message news:b2*************************@posting.google.co m...
> Q6 C/C++ : Write a function in different ways that will return f(7) = > 4 and f(4) = 7 If you want to get clever with boolean values, you could try:
int f(int x) { return (x==7*4)+(x==4*7); }
Huh?
In C, the == operator returns 1 if the operands match or 0 if they don't. Go from there.
Now f returns 2 if x equals 28, or 0 otherwise. Great solution. ;)
Regards

Irrwahn Grausewitz (ir*******@freenet.de)
welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt
clc faqlist : http://www.faqs.org/faqs/Cfaq/faq/
clc OT guide : http://benpfaff.org/writings/clc/offtopic.html  
P: n/a

Irrwahn Grausewitz <ir*******@freenet.de> scribbled the following
on comp.lang.c: "Siemel Naran" <Si*********@REMOVE.att.net> wrote:"Jerry Coffin" <jc*****@taeus.com> wrote in message news:b2*************************@posting.google. com... <snip> > Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator. <snip> If you want to get clever with boolean values, you could try:
int f(int x) { return (x==7*4)+(x==4*7); }
Huh?
I'm pretty sure Jerry meant to write:
return (x==7)*4 + (x==4)*7;
Dang! I didn't spot that in my original reply. Jerry's original code is
equivalent to return (x==28)+(x==28), which will return 2 if x==28 but
0 if not.

/ Joona Palaste (pa*****@cc.helsinki.fi)  Finland \
\ http://www.helsinki.fi/~palaste  rules! /
"You can pick your friends, you can pick your nose, but you can't pick your
relatives."
 MAD Magazine  
P: n/a

Irrwahn Grausewitz <ir*******@freenet.de> scribbled the following
on comp.lang.c: Joona I Palaste <pa*****@cc.helsinki.fi> wrote:Siemel Naran <Si*********@remove.att.net> scribbled the following on comp.lang.c: "Jerry Coffin" <jc*****@taeus.com> wrote in message news:b2*************************@posting.google.co m... > Q6 C/C++ : Write a function in different ways that will return f(7) = > 4 and f(4) = 7 If you want to get clever with boolean values, you could try:
int f(int x) { return (x==7*4)+(x==4*7); }
Huh?
In C, the == operator returns 1 if the operands match or 0 if they don't. Go from there.
Now f returns 2 if x equals 28, or 0 otherwise. Great solution. ;)
Yes, I noticed it myself later, as you can see. In my defense, it was
Jerry who wrote the incorrect code, I just failed to correct it... =)

/ Joona Palaste (pa*****@cc.helsinki.fi)  Finland \
\ http://www.helsinki.fi/~palaste  rules! /
"And according to Occam's Toothbrush, we only need to optimise the most frequent
instructions."
 Teemu Kerola  
P: n/a
 js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>... I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles.
Programming Puzzles
Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.
Q1 Write a "Hello World" program in 'C' without using a semicolon. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Q3 C/C++ : Exchange two numbers without using a temporary variable. Q4 C/C++ : Find if the given number is a power of 2. Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator. Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7 Q7 Remove duplicates in array Q8 Finding if there is any loop inside linked list. Q9 Remove duplicates in an no key access database without using an array Q10 Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed. Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly. Q12 Swap two numbers without using a third variable. Given an array (group) of numbers write all the possible sub groups of this group. Q14 Convert (integer) number in binary without loops.
Q3,12 are similar , Q7 is simple & I know there answer For the Rest please Help
Wiating for reply.
Q3 & Q12
int main()
{
int a = 10;
int b = 20;
/* Swap here */
a ^= b;
b ^= a;
a ^= b;
/* Show value code */
/* .........
* .........
*/
return 0;
}
Please correct me, if I'm wrong. :)  
P: n/a

Jerry Coffin wrote: js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>...
{snip] Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7
[snip]
I'm sure there are more variations as well.
int f(int x)
{
return 11  x;
}
boa
[snip]  
P: n/a

Jatinder wrote: Q3 C/C++ : Exchange two numbers without using a temporary variable.
Isn't the bitwise solution safe only for unsigned integrals?
Regards,
Ioannis Vranos  
P: n/a

Siemel Naran wrote: Q4 C/C++ : Find if the given number is a power of 2.
Easy with some bitwise arithmetic.
x & (x1) evaluates to zero if the number is an exact power of 2.
The OP cross posted both in clc++ and clc, and the set of questions
obviously consider C as a subset of C++, a dangerous thing to do but anyway.
However in both cases bitwise operations are guaranteed to be safe only
on unsigned integrals, so the above had better include the remark:
"where x is of unsigned integral type".
Regards,
Ioannis Vranos  
P: n/a

CBFalconer wrote: int main (void) { if (printf("Hello World")) {} if (exit(EXIT_SUCCESS)) {} }
Illegal. No #include for prototype of variadic function, nor EXIT_SUCCESS value, and exit is a void function. The compiler should barf.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
if (printf("Hello World")) {}
/* Only needed for C90 compliance */
if (exit(EXIT_SUCCESS),1){}
}
Regards,
Ioannis Vranos  
P: n/a

Ioannis Vranos wrote: Jatinder wrote:
Q3 C/C++ : Exchange two numbers without using a temporary variable. Isn't the bitwise solution safe only for unsigned integrals?
I just checked the standard, it is safe for both integral and
enumeration types.
Regards,
Ioannis Vranos  
P: n/a

Ioannis Vranos wrote: However in both cases bitwise operations are guaranteed to be safe only on unsigned integrals, so the above had better include the remark:
"where x is of unsigned integral type".
Just checked the C++98 standard, and they are valid for both integral
types and enumerations so what I said above is not needed.
Regards,
Ioannis Vranos  
P: n/a

On Sat, 26 Jun 2004, Jatinder wrote: I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles.
Programming Puzzles
Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.
[bunch of questions snipped]
Learn to use a search engine. The answer to the questions and many other
questions are readily available on the internet. You just need to learn to
search for them. Hint: http://groups.google.ca.

Send email to: darrell at cs dot toronto dot edu
Don't send email to vi************@whitehouse.gov  
P: n/a

"Siemel Naran" <Si*********@REMOVE.att.net> wrote in message news:<Fw********************@bgtnsc04news.ops.worldnet.att.net>... "Jerry Coffin" <jc*****@taeus.com> wrote in message news:b2*************************@posting.google.co m...
Almost anything you'd normally do with iteration can also be done with tail recursion. What is "tail" recursion? Are there other types of recursion?
Tail recursion is when the recursive call is the final step of an
algorithm. If the recursive call isn't the final step, it's not tail
recursion. In some cases, of course, an algorithm with some other
execution pattern can be converted to a tailrecursive form, but
others can't (especially those that include two or more recursive
calls).
Any the question says not to use loops. But to me, recursion is a loop, just expressed differently.
Both certainly express the concept of repeated execution of some set
of instructions. I'm less certain of characterizing all iteration as a
loop though.
[ ... ]
Are these methods faster than x*7 on modern processors?
Sometimes they are, other times they're not. The correct answer will
often depend as much on surrounding instructions as it does on the
processor. Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7 If you want to get clever with boolean values, you could try:
int f(int x) { return (x==7*4)+(x==4*7); }
Huh?
As has already been noted, I misparenthesized that. It should have
been "return (x==7)*4+(x==4)*7;" It's based on the fact that in C a
'true' result has the value 1, and a 'false' result has the value 0.
C++ has a type specifically for booleans, but for backward
compatibility it still allows them to be implicitly converted to
integer types.
I'm sure there are more variations as well.
Probably something with mod or %.
Maybe  OTOH, that's sort of the basis of the 'x^3' version.
There's another. Have two iterators, first one pointing to first element, the second pointing to the second. The second one is the fast iterator and you increment it twice in each iteration. The first iterator is the slow iterator and you increment it once in each iteration. If the list is not circular the fast iterator will hit NULL at some point. If the list is circular the fast iterator will equal to the slow iterator at some point.
Yes  I'd seen that posted elsewhere so I didn't repost it, but it IS
pretty clever.

Later,
Jerry.
The universe is a figment of its own imagination.  
P: n/a

Siemel Naran wrote: "Mabden" <mabden@sbc_global.net> wrote in message news:B5uDc.6258
Maybe you would get the job for walking out...
That might be too out of the box :).
A job interview is for finding a match. The company is also under the
microscope. Would you really want to work for a company who gives this
as the big programming test?  
P: n/a
 js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>... I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles.
Programming Puzzles
Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.
Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;
I'll try it in C, should be portable to C++:
#include <stdio.h>
int p(int x, int i)
{
(x > 100) && (i = 1);
(x > 0 && x < 101) && printf("%d\n", x);
(x > 0) && p(x + i, i);
return 1;
}
int main(void)
{
p(1, 1);
return 0;
}
Gregory Pietsch  
P: n/a
 js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>... I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles.
Programming Puzzles
Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.
Q3 (the same as the other you mentioned, basically) took me less than
a minute to solve, and I'm only 16:
/* vim:ts=4
*/
#include <stdio.h>
int main(void) {
int foo = 87;
int bar = 56;
foo += bar;
bar = foo  bar;
foo = foo  bar;
fprintf(stdout, "%i, %i\n", foo, bar);
}
Try other values for foo & bar, even negatives and zero.
You mentioned MS often use these sorts of puzzles to test their
programmers. I got an even better one to stump even the best MS
programmers:
/* vim:ts=4
*/
#include <stdio.h>
int main(void) {
int *foo = NULL;
fprintf(stdout, "%i\n", *foo);
}
What will happen if I compile and run this program??  
P: n/a

Am I the only person here that thinks it's complete bullshit to think you
can swap the values of two variables without a temporary variable?! It
simply cannot be done. Why? Consider this, you have two containers, each of
capacity 3 litres. Each of them is filled with 2 litres of water. Swap the
water from the containers. Okay... let's just poor all of one of them into
the other. Mammy mammy! It was an accident, I didn't realize you can't put 4
litres of water into a 3 litre container.
Fools.
JKop  
P: n/a

JKop <NU**@null.null> scribbled the following
on comp.lang.c: Am I the only person here that thinks it's complete bullshit to think you can swap the values of two variables without a temporary variable?! It simply cannot be done. Why? Consider this, you have two containers, each of capacity 3 litres. Each of them is filled with 2 litres of water. Swap the water from the containers. Okay... let's just poor all of one of them into the other. Mammy mammy! It was an accident, I didn't realize you can't put 4 litres of water into a 3 litre container.
Fools.
It *can* be done! Not with all kinds of variables, but with unsigned
integer types, it's easy. Not one, but *two* ways to do it have been
shown in this thread. Of course it will break down if those variables
happen to share the same memory location, which can be the case if using
pointers and indirecting through them.

/ Joona Palaste (pa*****@cc.helsinki.fi)  Finland \
\ http://www.helsinki.fi/~palaste  rules! /
"I am not very happy acting pleased whenever prominent scientists overmagnify
intellectual enlightenment."
 Anon  
P: n/a

Joona I Palaste wrote: JKop <NU**@null.null> scribbled the following on comp.lang.c:
Am I the only person here that thinks it's complete bullshit to think you can swap the values of two variables without a temporary variable?! It simply cannot be done. Why? Consider this, you have two containers, each of capacity 3 litres. Each of them is filled with 2 litres of water. Swap the water from the containers. Okay... let's just poor all of one of them into the other. Mammy mammy! It was an accident, I didn't realize you can't put 4 litres of water into a 3 litre container.
Fools.
It *can* be done! Not with all kinds of variables, but with unsigned integer types, it's easy. Not one, but *two* ways to do it have been shown in this thread. Of course it will break down if those variables happen to share the same memory location, which can be the case if using pointers and indirecting through them.
The "xor" method works on all unsigned integer types,
and [OT] if you program in assembler, it works on
any two memory locations or registers unless you
cause a trap along the way. [/OT]
However the arithemetic method upthread, i.e.
foo += bar; bar = foo  bar; foo = foo  bar;
may fail if you get unsigned integer overflow, at
least I think *may* fail. This may be the case of
the container not being able to hold 4 litres.
What does the Cstandard say about unsigned integer overflow?
NPL
PS.  [OT] there are, of course, languages which do
not have the "exlusive OR" operator. But they're
not C [/OT]  
P: n/a

Nick Landsberg <hu*****@worldnet.att.net> scribbled the following
on comp.lang.c: Joona I Palaste wrote: JKop <NU**@null.null> scribbled the following on comp.lang.c:Am I the only person here that thinks it's complete bullshit to think you can swap the values of two variables without a temporary variable?! It simply cannot be done. Why? Consider this, you have two containers, each of capacity 3 litres. Each of them is filled with 2 litres of water. Swap the water from the containers. Okay... let's just poor all of one of them into the other. Mammy mammy! It was an accident, I didn't realize you can't put 4 litres of water into a 3 litre container.Fools.
It *can* be done! Not with all kinds of variables, but with unsigned integer types, it's easy. Not one, but *two* ways to do it have been shown in this thread. Of course it will break down if those variables happen to share the same memory location, which can be the case if using pointers and indirecting through them.
The "xor" method works on all unsigned integer types, and [OT] if you program in assembler, it works on any two memory locations or registers unless you cause a trap along the way. [/OT]
The "xor" method will *not* work on two variables with the same memory
location. You'd expect the swap to be a noop, but it ends up setting
both variables to 0, because it "xors" the first variable with itself,
yielding 0, and then keeps "xorring" this 0 with itself.

/ Joona Palaste (pa*****@cc.helsinki.fi)  Finland \
\ http://www.helsinki.fi/~palaste  rules! /  
P: n/a

Joona I Palaste wrote: Nick Landsberg <hu*****@worldnet.att.net> scribbled the following on comp.lang.c:
Joona I Palaste wrote:
JKop <NU**@null.null> scribbled the following on comp.lang.c:
Am I the only person here that thinks it's complete bullshit to think you can swap the values of two variables without a temporary variable?! It simply cannot be done. Why? Consider this, you have two containers, each of capacity 3 litres. Each of them is filled with 2 litres of water. Swap the water from the containers. Okay... let's just poor all of one of them into the other. Mammy mammy! It was an accident, I didn't realize you can't put 4 litres of water into a 3 litre container.
Fools.
It *can* be done! Not with all kinds of variables, but with unsigned integer types, it's easy. Not one, but *two* ways to do it have been shown in this thread. Of course it will break down if those variables happen to share the same memory location, which can be the case if using pointers and indirecting through them.
The "xor" method works on all unsigned integer types, and [OT] if you program in assembler, it works on any two memory locations or registers unless you cause a trap along the way. [/OT]
The "xor" method will *not* work on two variables with the same memory location. You'd expect the swap to be a noop, but it ends up setting both variables to 0, because it "xors" the first variable with itself, yielding 0, and then keeps "xorring" this 0 with itself.
You are correct. I should have said two different/distinct
memory locations.

"It is impossible to make anything foolproof
because fools are so ingenious"
 A. Bloch  
P: n/a

"Wayne Rasmussen" <Xv*****************@gomonarch.com> wrote in message
news:40***************@gomonarch.com... Siemel Naran wrote:
"Mabden" <mabden@sbc_global.net> wrote in message news:B5uDc.6258
Maybe you would get the job for walking out...
That might be too out of the box :).
A job interview is for finding a match. The company is also under the microscope. Would you really want to work for a company who gives this as the big programming test?
I just "interviewed" with a company in Los Angeles (that little country
between Mexico and USA). They didn't even talk to me at all. They handed me
a "personality test", which also included an intelligence test (and I've
been through Mensa testing  it was hard), and sat me in a room for 2 hours.
At the end they took the answer sheet and said they'd get back to me.
I passed the test, I guess, because I get to go back next week for another 2
hour programming test. If I pass that, I get to move to round three which is
to face a panel of their programmers in a room for questioning. I'm guessing
it'll be about 2 hours...
Whee...

Mabden
p.s. Here's one I missed: What is the next letter in this sequence: A F Z U
G L T ? 1. O 2. C 3. X 4. N
p.p.s. I figured it out later. ("You think you're better than me?!!")  
P: n/a

"boa" <ro**@localhost.com> wrote in message
news:21*****************@juliett.dax.net... Jerry Coffin wrote:
js*******@sancharnet.in (Jatinder) wrote in message
news:<22**************************@posting.google. com>... {snip]
Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7
[snip]
I'm sure there are more variations as well.
int f(int x) { return 11  x; }
Very nice!

Mabden  
P: n/a

Mabden <mabden@sbc_global.net> scribbled the following
on comp.lang.c: "Wayne Rasmussen" <Xv*****************@gomonarch.com> wrote in message news:40***************@gomonarch.com... Siemel Naran wrote: > "Mabden" <mabden@sbc_global.net> wrote in message news:B5uDc.6258 > > Maybe you would get the job for walking out... > > That might be too out of the box :). A job interview is for finding a match. The company is also under the microscope. Would you really want to work for a company who gives this as the big programming test?
I just "interviewed" with a company in Los Angeles (that little country between Mexico and USA). They didn't even talk to me at all. They handed me a "personality test", which also included an intelligence test (and I've been through Mensa testing  it was hard), and sat me in a room for 2 hours. At the end they took the answer sheet and said they'd get back to me.
I passed the test, I guess, because I get to go back next week for another 2 hour programming test. If I pass that, I get to move to round three which is to face a panel of their programmers in a room for questioning. I'm guessing it'll be about 2 hours...
Whee...
Unbelievable. I rmemember *my* latest job interview. The company's CEO
and I sat in the corridor of a Finnish technology enterprise building,
where the company's offices were located at the time, and talked for a
few hours about what I'm like as an employee. Later, I, the CEO and the
company's chief programmer met in a restaurant and talked about what I
am like as a programmer. The company paid for my dinner. Then I was
going about minding my own business when I got a call that I had got the
job. That's all there was to it. No tests, no panel hearings, just a few
hours of talk.

/ Joona Palaste (pa*****@cc.helsinki.fi)  Finland \
\ http://www.helsinki.fi/~palaste  rules! /
"Hasta la Vista, Abie!"
 Bart Simpson  
P: n/a

"Foobarius Frobinium" <fo******@youremailbox.com> wrote in message
news:a7**************************@posting.google.c om... js*******@sancharnet.in (Jatinder) wrote in message
news:<22**************************@posting.google. com>... You mentioned MS often use these sorts of puzzles to test their programmers. I got an even better one to stump even the best MS programmers: #include <stdio.h>
int main(void) { int *foo = NULL;
fprintf(stdout, "%i\n", *foo); }
What will happen if I compile and run this program??
You'll get a warning saying main() has no return value.  
P: n/a

"Nick Landsberg" <hu*****@worldnet.att.net> wrote in message
news:uC*******************@bgtnsc05news.ops.worldnet.att.net... The "xor" method will *not* work on two variables with the same memory location. You'd expect the swap to be a noop, but it ends up setting both variables to 0, because it "xors" the first variable with itself, yielding 0, and then keeps "xorring" this 0 with itself.
You are correct. I should have said two different/distinct memory locations.
Uuuuhhh... if the two "variables" point to the same location, then the swap
is done!

Mabden  
P: n/a

"Joona I Palaste" <pa*****@cc.helsinki.fi> wrote in message
news:cb**********@oravannahka.helsinki.fi... Mabden <mabden@sbc_global.net> scribbled the following on comp.lang.c: "Wayne Rasmussen" <Xv*****************@gomonarch.com> wrote in message news:40***************@gomonarch.com... Siemel Naran wrote: > "Mabden" <mabden@sbc_global.net> wrote in message news:B5uDc.6258 > > Maybe you would get the job for walking out... > > That might be too out of the box :).
A job interview is for finding a match. The company is also under the microscope. Would you really want to work for a company who gives this as the big programming test?
I just "interviewed" with a company in Los Angeles (that little country between Mexico and USA). They didn't even talk to me at all. They handed me a "personality test", which also included an intelligence test (and I've been through Mensa testing  it was hard), and sat me in a room for 2 hours. At the end they took the answer sheet and said they'd get back to me.
I passed the test, I guess, because I get to go back next week for another 2 hour programming test. If I pass that, I get to move to round three which is to face a panel of their programmers in a room for questioning. I'm guessing it'll be about 2 hours...
Whee...
Unbelievable. I rmemember *my* latest job interview. The company's CEO and I sat in the corridor of a Finnish technology enterprise building, where the company's offices were located at the time, and talked for a few hours about what I'm like as an employee. Later, I, the CEO and the company's chief programmer met in a restaurant and talked about what I am like as a programmer. The company paid for my dinner. Then I was going about minding my own business when I got a call that I had got the job. That's all there was to it. No tests, no panel hearings, just a few hours of talk.
Yup. Those are the best kinds of "interviews", and generally
only happen for highlyqualified candidates. My last 2 jobs
were like that, and both were 6 figure programming jobs. Ah,
those were the days...
Those BS interviews asking about how to twiddle bits are a
waste of time. If I can't recall an exact algorithm, I just
look it up in one of my many reference books, including the
3 volumes of Knuth. The overall approach to solving a problem
and how I think about designing a solution is what's really
important. Don't sweat the small things, that's what junior
programmers are for.  
P: n/a

Joona I Palaste wrote: It *can* be done! Not with all kinds of variables, but with unsigned integer types,
I had somewhere in my mind the unsigned restriction, but then I checked
the standard and saw that xor is safe to be applied on both integral
types and enumerations. Then how does this unsigned restriction come?
"5.12 Bitwise exclusive OR operator
exclusiveorexpression:
andexpression
exclusiveorexpression ^ andexpression
The usual arithmetic conversions are performed; the result is the
bitwise exclusive OR function of the operands. The operator applies only
to integral or enumeration operands."
Regards,
Ioannis Vranos  
P: n/a

Joona I Palaste wrote: It *can* be done! Not with all kinds of variables, but with unsigned integer types,
I had somewhere in my mind the unsigned restriction, but then I checked
the standard and saw that XOR is safe to be applied on both integral
types and enumerations. Then how does this unsigned restriction come?
"5.12 Bitwise exclusive OR operator
exclusiveorexpression:
andexpression
exclusiveorexpression ^ andexpression
The usual arithmetic conversions are performed; the result is the
bitwise exclusive OR function of the operands. The operator applies only
to integral or enumeration operands."
Regards,
Ioannis Vranos  
P: n/a

Christian Bau wrote: In article <22**************************@posting.google.com >, js*******@sancharnet.in (Jatinder) wrote:
I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles.
Programming Puzzles
Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.
Q1 Write a "Hello World" program in 'C' without using a semicolon. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Q3 C/C++ : Exchange two numbers without using a temporary variable. Q4 C/C++ : Find if the given number is a power of 2. Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator. Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7 Q7 Remove duplicates in array Q8 Finding if there is any loop inside linked list. Q9 Remove duplicates in an no key access database without using an array Q10 Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed. Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly. Q12 Swap two numbers without using a third variable. Given an array (group) of numbers write all the possible sub groups of this group. Q14 Convert (integer) number in binary without loops.
Q3,12 are similar , Q7 is simple & I know there answer For the Rest please Help
Assuming that these questions are from an interview for a programming job, I must say that most of them are incredibly useless at finding a good programmer.
To play some devil's advocate here:
If your experience as a programmer is confined entirely to the academic
or professional spheres, you may never see questions like that, and so
wouldn't get the answer. But if you investigate and discuss programming
independently (like on this newsgroup), then you probably will. So they
may be a good way of finding people who are passionate self starters,
which could be particularly important in an industry where 70% of people
have left after 6 years (so I've read).
Take Q3: The correct answer is: Why would anyone want to do that? Take Q10: You know the answer or you don't. If your name is Gödel or Turing, you might find a solution on your own, but otherwise this just tests some very obscure knowledge.
We sometimes give Q4 in our interviews. I'd expect any programmer to be
able to come up with *some* solution, even if it's only testing whether
the value equals any of 32 powers of 2. What usually happens is that
the candidate tries to realize a more sophisticated solution but fails,
and rather than dropping back to a more obvious algorithm gets bogged
down. That's an all too common warning flag.
I guess these questions are only used to check your reaction to a stressful situation (which is also an incredibly useless way at finding a good programmer).
There's useful information to be gained by observing how people approach
a problem even if they don't get the right answer. If, given Q10, the
candidate says immediately "It can't be done" and then struggles to back
up their claim, that's bad news. If they say "I'd guess it
could/couldn't be done, but I'm not sure, and I might go to find out
here..." then that's a plus.
We sometimes give questions that are too specific to our work for a new
candidate to know, the idea being to see whether they'd guess, guess and
verify, give up, etc. The quine isn't a good choice for that because,
as you said, there's no motivation. If I was given this list of questions, I would tell them that most of them are pointless and then examine Q11, because it is the only interesting one. Maybe a different response if you are desperate for a job.
Way to think "outside the box" ;)

Pull out a splinter to reply.  
P: n/a

Jatinder wrote: I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles.
Programming Puzzles
Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.
Ok I couldn't resist so I 'll give my answers to these questions. As a
poster has done previously, where "C" is mentioned I consider C++98 (I
view these from clc++).
Q1 Write a "Hello World" program in 'C' without using a semicolon.
#include <iostream>
int main()
{
if(std::cout<<"Hello World!\n") {}
}
Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;
#include <iostream>
template<class T>
inline void printinc(T i, const T limit)
{
std::cout<<i<<" ";
if(i<limit)
printinc(++i, limit);
}
template<class T>
inline void printdec(T i, const T limit)
{
std::cout<<i<<" ";
if(i>limit)
printdec(i, limit);
}
int main()
{
using namespace std;
printinc(1, 100);
cout<<endl<<endl;
printdec(100, 1);
}
Q3 C/C++ : Exchange two numbers without using a temporary variable.
#include <algorithm>
int main()
{
using std::swap;
int x=1, y=2;
swap(x,y);
}
Q4 C/C++ : Find if the given number is a power of 2.
#include <bitset>
#include <limits>
#include <cstddef>
bool IsPowerOfTwo(unsigned long x)
{
using namespace std;
// It is safe for unusual implementations where bytes
// are more than 8 bits.
bitset<numeric_limits<unsigned char>::digits>bitRep=x;
unsigned nonZeroBits=0;
for(size_t i=0; i<bitRep.size(); ++i)
if(bitRep[i])
nonZeroBits++;
if(nonZeroBits==1)
return true;
else
return false;
}
Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.
Obscure question, addition can be used as others mentioned or
#include <iostream>
int main()
{
using namespace std;
int x=3, temp=x;
x<<=3;
x=temp;
cout<<x<<endl;
}
Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7
inline somefunc(int x)
{
return x==7?4:7;
}
Q7 Remove duplicates in array
std::sort, std::unique.
Q8 Finding if there is any loop inside linked list.
One has already suggested the use of two pointers advancing which is
really a very good solution.
Q9 Remove duplicates in an no key access database without using an array
SQL. :)
Q10 Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed.
I have seen it somewhere in the web sometime in the past.
Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly.
And what is the programming question?
Q12 Swap two numbers without using a third variable.
Already answered:
#include <algorithm>
int main()
{
using std::swap;
int x=1, y=2;
swap(x,y);
}
:P
Given an array (group) of numbers write all the possible sub groups of this group.
std::next_permutation and std::prev_permutation. An example:
#include <algorithm>
#include <string>
#include <iostream>
int main()
{
using namespace std;
string s="abcd";
do
cout<<s<<endl;
while(next_permutation(s.begin(), s.end()));
}
Q14 Convert (integer) number in binary without loops.
I assume it means the binary representation as a string since numbers
are already stored in binary, and such "conversion" has not any meaning.
With std::bitset this is too easy.
Regards,
Ioannis Vranos  
P: n/a

Ioannis Vranos wrote:
Well some errata. :) Q1 Write a "Hello World" program in 'C' without using a semicolon. #include <iostream>
int main() { if(std::cout<<"Hello World!\n") {} }
Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;
Note: There is a restriction for if statements, but if statements do not
constitute a loop.
#include <iostream>
template<class T> inline void printinc(T i, const T limit) { std::cout<<i<<" ";
if(i<limit) printinc(++i, limit); }
template<class T> inline void printdec(T i, const T limit) { std::cout<<i<<" ";
if(i>limit) printdec(i, limit); }
int main() { using namespace std;
printinc(1, 100);
cout<<endl<<endl;
printdec(100, 1); }
Q4 C/C++ : Find if the given number is a power of 2.
#include <bitset> #include <limits> #include <cstddef>
bool IsPowerOfTwo(unsigned long x) { using namespace std;
// It is safe for unusual implementations where bytes // are more than 8 bits.
bitset<numeric_limits<unsigned char>::digits>bitRep=x;
bitset<numeric_limits<unsigned char>::digits*sizeof(x)>bitRep=x; unsigned nonZeroBits=0;
for(size_t i=0; i<bitRep.size(); ++i) if(bitRep[i]) nonZeroBits++;
if(nonZeroBits==1) return true;
else return false; }
Regards,
Ioannis Vranos  
P: n/a

Jatinder wrote: I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles.
Programming Puzzles Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.
Ok I couldn't resist so I 'll give my answers to these questions. As a
poster has done previously, where "C" is mentioned I consider C++98 (I
view these from clc++).
Q1 Write a "Hello World" program in 'C' without using a semicolon.
#include <iostream>
int main()
{
if(std::cout<<"Hello World!\n") {}
}
Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;
Note: There is a restriction for if statements, but if statements do not
constitute a loop.
#include <iostream>
template<class T>
inline void printinc(T i, const T limit)
{
std::cout<<i<<" ";
if(i<limit)
printinc(++i, limit);
}
template<class T>
inline void printdec(T i, const T limit)
{
std::cout<<i<<" ";
if(i>limit)
printdec(i, limit);
}
int main()
{
using namespace std;
printinc(1, 100);
cout<<endl<<endl;
printdec(100, 1);
}
Q3 C/C++ : Exchange two numbers without using a temporary variable.
#include <algorithm>
int main()
{
using std::swap;
int x=1, y=2;
swap(x,y);
}
Q4 C/C++ : Find if the given number is a power of 2.
#include <bitset>
#include <limits>
#include <cstddef>
bool IsPowerOfTwo(unsigned long x)
{
using namespace std;
// It is safe for unusual implementations where bytes
// are more than 8 bits.
bitset<numeric_limits<unsigned char>::digits*sizeof(x)>bitRep=x;
unsigned nonZeroBits=0;
for(size_t i=0; i<bitRep.size(); ++i)
if(bitRep[i])
nonZeroBits++;
if(nonZeroBits==1)
return true;
else
return false;
}
Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.
Obscure question, addition can be used as others mentioned or
#include <iostream>
int main()
{
using namespace std;
int x=3, temp=x;
x<<=3;
x=temp;
cout<<x<<endl;
}
Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7
inline somefunc(int x)
{
return x==7?4:7;
}
Q7 Remove duplicates in array
std::sort, std::unique.
Q8 Finding if there is any loop inside linked list.
One has already suggested the use of two pointers advancing which is
really a very good solution.
Q9 Remove duplicates in an no key access database without using an array
SQL. :)
Q10 Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed.
I have seen it somewhere in the web sometime in the past.
Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly.
And what is the programming question?
Q12 Swap two numbers without using a third variable.
Already answered:
#include <algorithm>
int main()
{
using std::swap;
int x=1, y=2;
swap(x,y);
}
:P
Given an array (group) of numbers write all the possible sub groups of this group.
std::next_permutation and std::prev_permutation. An example:
#include <algorithm>
#include <string>
#include <iostream>
int main()
{
using namespace std;
string s="abcd";
do
cout<<s<<endl;
while(next_permutation(s.begin(), s.end()));
}
Q14 Convert (integer) number in binary without loops.
I assume it means the binary representation as a string since numbers
are already stored in binary, and such "conversion" has not any meaning.
With std::bitset this is too easy.
Regards,
Ioannis Vranos  
P: n/a

Ioannis Vranos wrote: > Given an array (group) of numbers write all the possible sub groups of > this group. std::next_permutation and std::prev_permutation. An example:
#include <algorithm>
#include <vector>
#include <iostream>
int main()
{
using namespace std;
int array[4]={1,2,3,4};
for(int*p=array, *r=&array[4]; p!=r; r)
{
vector<int>temparray(p,r);
do
{
for(vector<int>::size_type i=0; i<temparray.size(); ++i)
cout<<temparray[i]<<" ";
cout<<endl;
}while(next_permutation(temparray.begin(), temparray.end()));
}
}
Regards,
Ioannis Vranos  
P: n/a

xarax wrote: "Joona I Palaste" <pa*****@cc.helsinki.fi> wrote in message news:cb**********@oravannahka.helsinki.fi...
Mabden <mabden@sbc_global.net> scribbled the following on comp.lang.c:
"Wayne Rasmussen" <Xv*****************@gomonarch.com> wrote in message news:40***************@gomonarch.com...
Siemel Naran wrote:
>"Mabden" <mabden@sbc_global.net> wrote in message news:B5uDc.6258 > >>Maybe you would get the job for walking out... > >That might be too out of the box :).
A job interview is for finding a match. The company is also under the microscope. Would you really want to work for a company who gives this as the big programming test?
I just "interviewed" with a company in Los Angeles (that little country between Mexico and USA). They didn't even talk to me at all. They handed me a "personality test", which also included an intelligence test (and I've been through Mensa testing  it was hard), and sat me in a room for 2 hours. At the end they took the answer sheet and said they'd get back to me.
I passed the test, I guess, because I get to go back next week for another 2 hour programming test. If I pass that, I get to move to round three which is to face a panel of their programmers in a room for questioning. I'm guessing it'll be about 2 hours...
Whee...
Unbelievable. I rmemember *my* latest job interview. The company's CEO and I sat in the corridor of a Finnish technology enterprise building, where the company's offices were located at the time, and talked for a few hours about what I'm like as an employee. Later, I, the CEO and the company's chief programmer met in a restaurant and talked about what I am like as a programmer. The company paid for my dinner. Then I was going about minding my own business when I got a call that I had got the job. That's all there was to it. No tests, no panel hearings, just a few hours of talk.
Yup. Those are the best kinds of "interviews", and generally only happen for highlyqualified candidates. My last 2 jobs were like that, and both were 6 figure programming jobs. Ah, those were the days...
Those BS interviews asking about how to twiddle bits are a waste of time. If I can't recall an exact algorithm, I just look it up in one of my many reference books, including the 3 volumes of Knuth. The overall approach to solving a problem and how I think about designing a solution is what's really important. Don't sweat the small things, that's what junior programmers are for.
Amen.
Back in the "good old days" in my company, the interview
process was actually partially scripted in the sense
that there was a "seller," a "buyer" and a social
encounter.
The "seller's" job was to point out all the whizbang things
that we were doing in order to make the candidate want
to come to work for us. At the technical level it was
mostly about the technologies we used and the kinds of
problems we were trying to solve and why it was important
to solve those kinds of problems. The candidate's interest
was noted. ("What aspect of this problem most interests you?")
The "buyer's" job was to discretely ask about the candidate's
technical background. e.g. "Tell me more about this project (on your
resume). What did you do on it? What was the most interesting
aspect of it? What was the most troublesome problem you faced?
How did you solve it?" (We, of course, didn't use the exact
phrasing noted above, but we evaluated the candidate's
responses as to the level of understanding. e.g. if the
candidate focused on design flaws, they got higher mental
marks than if the candidate focused on coding errors.)
Each of the above was about 23 hours. After that, the candidate
would be taken out to dinner where we were supposed to judge
how he/she would interact with coworkers. (I know, totally
subjective, but actually the "dinne" was more important
then the previous sessions, assuming that the candidate had
impressed us in the previous sessions.)
Not very scientific. No "20 questions about trivial/obscure
software techniques". Just gut feelings on the part of
the interviewers. Unfair? Probably. Effective? Mostly
yes.
Some highego hardcases got through, but not too many.
Just my $0.02 American.
NPL

"It is impossible to make anything foolproof
because fools are so ingenious"
 A. Bloch  
P: n/a

Foobarius Frobinium wrote: js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>...
I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles.
Programming Puzzles
Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions.
Q3 (the same as the other you mentioned, basically) took me less than a minute to solve, and I'm only 16:
/* vim:ts=4 */
#include <stdio.h>
int main(void) { int foo = 87; int bar = 56;
foo += bar; bar = foo  bar; foo = foo  bar;
fprintf(stdout, "%i, %i\n", foo, bar); }
Try other values for foo & bar, even negatives and zero.
You mentioned MS often use these sorts of puzzles to test their programmers. I got an even better one to stump even the best MS programmers:
/* vim:ts=4 */
#include <stdio.h>
int main(void) { int *foo = NULL;
fprintf(stdout, "%i\n", *foo); }
What will happen if I compile and run this program??
To stump Microsoft programmers, I prefer to ask them to write a
recursive factorial function.
See
< http://msdn.microsoft.com/library/de...enus/vclang/h
tml/_CLANG_Recursive_Functions.asp> for their answer. Prepare to wince.

Pull out a splinter to reply.  
P: n/a

Christian Bau wrote: Assuming that these questions are from an interview for a programming job, I must say that most of them are incredibly useless at finding a good programmer. Take Q3: The correct answer is: Why would anyone want to do that? Take Q10: You know the answer or you don't. If your name is Gödel or Turing, you might find a solution on your own, but otherwise this just tests some very obscure knowledge. I guess these questions are only used to check your reaction to a stressful situation (which is also an incredibly useless way at finding a good programmer).
If I was given this list of questions, I would tell them that most of them are pointless and then examine Q11, because it is the only interesting one. Maybe a different response if you are desperate for a job.
Presuming that the interviewer is competent: it is not the answer to the
question that is important, but _how_ you solve it.  
P: n/a

Joona I Palaste wrote: Of course it will break down if those variables happen to share the same memory location, which can be the case if using pointers and indirecting through them.
Explain to me how *two* variables can share the same memory address.   This discussion thread is closed Replies have been disabled for this discussion.   Question stats  viewed: 16624
 replies: 271
 date asked: Nov 14 '05
