Wednesday 20 April 2011

An Challenging Interview question with a difference

The following program is provided:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

//This class can be designed as you wish
class SR
{

public
:
SR(int i) {}
};


int
main()
{

int
sum = 0;
for
(int i = 1; i < 100; i++)
{

SR ii(i);
while
(i--)
sum += i;
}

cout<<"Expected value of sum = 161700" << endl;
cout<<"Returned value of sum = " << sum << endl;

return
0;
}


As already mentioned above, the expected output of 161700 is provided. The class 'SR' could be written as one wishes. How to do write the class 'SR' to get the desired output?
.
.
.
.
Give it a try before looking at the solution.
.
.
.
.
.
The modified program with the correct 'SR' class as follows:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

//This class can be designed as you wish
class SR
{

public
:
SR(int& i):ref(i)
{

var = i;
}
~
SR()
{

ref = var;
}

private
:
int
var;
int
&ref;
};


int
main()
{

int
sum = 0;
for
(int i = 1; i < 100; i++)
{

SR ii(i);
while
(i--)
sum += i;
}

cout<<"Expected value of sum = 161700" << endl;
cout<<"Returned value of sum = " << sum << endl;

return
0;
}



Source: Modified from here. Another similar question is available here.

3 comments:

  1. Hi

    Isn't there a bug in the main code?

    99 steps should be 166650, not 161700 which is 98.
    There are two steps where 0 is added causing the missed calculation.

    Changing the while to:

    while (i)
    sum += i--;

    Returns 99's value correctly.

    I found the answer to be very keen. :)

    I didn't realize that about the destructor. It makes sense since the next increment terminates the scope. Thanks for the example.

    ReplyDelete
  2. Rich,

    The question is more about designing the class SR rather than a correct while logic. I would be surprised if many people can design the correct destructor.

    ReplyDelete
  3. I wasted a good bit of time trying to solve this problem in a different way than was intended because I didn't know the significance of the number 161700.

    Since the problem is really about retaining the value of i during its mutilation in the 'while' loop, I suggest pointing out to readers in the opening that 161700 is the sum of "the sum of the integers between 1 and n" where n goes from 1 to 100.

    This would have saved me some trouble :)

    ReplyDelete