Hello Everyone,

This is my first day here. I've not browsed the site yet. But I wanted to know the answer of these questions. I'd be glad if anyone of you can help me.

1.Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;
2.Exchange two numbers without using a temporary variable.
3.Find if the given number is a power of 2.
4.Multiply x by 7 without using multiplication (*) operator.

1. could be a trick question ...

std::cout << "numbers from 1 to 100 and 100 to 1";

2. assuming we are talking integers, use a macro like ...

// macro to swap two arguments of any type
#define SWAP(x, y)   ((x) ^= (y) ^= (x) ^= (y))

Edit: Eating crow again. Sorry, change the "of any type" to "integers only"!

3. assuming we are talking integers, whittle the number down with a series of odd integers (1,3,5,7,...) until a zero match is reached ...

#include <iostream>

using namespace std;

void isPowerOf2(int x)
{
    int y;
    
    y = 1;   // start of odd number sequence 1, 3, 5, 7 ...
    while(x > -1)
    {
        cout << x << endl;   // test
        x = x - y;   // subtracting a sequence of odd numbers
        y = y + 2;   // next odd number
        if (x == 0)
        {
            cout << "Bingo, we have a power of 2 number" << endl;
            break;
        }
        else if (x < 0)
            cout << "Gee, this number fails the power of 2 test" << endl;
    }
}     

int main()
{
    isPowerOf2(98);
    isPowerOf2(81);
    isPowerOf2(1);
    isPowerOf2(-8);  // test
           
    cin.get();  // wait
    return EXIT_SUCCESS;
}

Edit: put that in here because the tone went splenetic later in this thread.

4. Multiple addition will do ...

y = x+x+x+x+x+x+x;

... as long as you don't multiply by a float!

Ouch, I have forgotten how meticulous C is. Sorry, change the "of any type" to "integers only".

May I kindly suggest you start learning Python, then a simple ...

a, b = b, a

... will do. Where a and b is any objet.

the answer to number 3 (assuming the number is an integer) is to use the modulous operator, %.

if(!(numbername%2))
   cout<<numbername<<" is a power of 2."<<endl;

Thanks a lot everyone. It was quite quick. This forum seems to be good. That helped a lot. Thanks !!

Now you got me started, for swapping either integers or floats this will work too ...

#include <iostream>

using namespace std;

int main()
{
    int a = 1;
    int b = 7;
    
    cout << "a = " << a << "   b = " << b << endl; 
    // swap a with b
    a = a + b;
    b = a - b;
    a = a - b;
    
    cout << "a = " << a << "   b = " << b << endl; 
    
    cin.get();   // wait
    return EXIT_SUCCESS;
}

Edit: Just an interrogative alternate, this swap is actually about five times slower then the usual temp variable swap.

Now you got me started, for swapping either integers or floats this will work too ...

Starting with your example, you could use a c++ template.

#include <iostream>
#include <limits.h>
using namespace std;

template<class T>
swapm(T &a,T &b)
{
	a = a + b;
	b = a - b;
	a = a - b;
};

int main()
{
    int a = 1;
    int b = 7;
    
    cout << "a = " << a << "   b = " << b << endl; 
	swapm(a,b);    
    cout << "a = " << a << "   b = " << b << endl; 

    
	float c = 1.23F;
	float d = 2.34F;
	
    cout << "c = " << c << "   d = " << d << endl; 
	swapm(c,d);    
    cout << "c = " << c << "   d = " << d << endl; 

    cin.get();   // wait
    return 0;
}

the answer to number 3 (assuming the number is an integer) is to use the modulous operator, %.

if(!(numbername%2))
   cout<<numbername<<" is a power of 2."<<endl;

Um, no. This only tells if the number is a multiple of 2. For power of 2, that'd be (!(x & (x - 1))).

As for #1:

First of all, "if" is not a loop. I don't know what got this idea into your head. But let's not use 'if' anyway.

#include <iostream>

void cout_nums_and_back(int low, int high) {
    (high < low)  ||  (
        std::cout << low << std::endl,
        cout_nums_and_back(low + 1, high),
        std::cout << low << std::endl
    );
    return;
}

int main() {
	cout_nums_and_back(1, 100);
	return 0;
}

And as for #4:

y = x + (x << 1) + (x << 2);

also works.

Um, no. This only tells if the number is a multiple of 2. For power of 2, that'd be (!(x & (x - 1))).

... right. Well, if you were only TESTED on powers of two, I'm right, but my code isn't gonna cut it past 4.

And as for #4:

y = x + (x << 1) + (x << 2);

also works.

That is most likely the reason 7 was picked as the multiplier.

>Sorry, change the "of any type" to "integers only".
How about changing "macro to swap two arguments of any type" to "silly macro to break everything". It's still broken because you're modifying a variable more than once between sequence points. This isn't a difficult rule to figure out, I can't see why so many people have so much trouble with it.

I would word those questions differently in an interview:

>1.Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;
Translation: Expain recursion.

>2.Exchange two numbers without using a temporary variable.
Translation: Explain why exchanging two numbers without a temporary variable is the height of stupidity.

>3.Find if the given number is a power of 2.
Translation: Find if the given number is a power of 2. ;) This is actually a useful exercise in bit twiddling and the result can be used in real code.

>4.Multiply x by 7 without using multiplication (*) operator.
Translation: How would you multiply without using the (*) operator, and why would I fire you if you did it in our source base?

Hey, that was really nice of you all!! Thanks a lot.

>
>2.Exchange two numbers without using a temporary variable.
Translation: Explain why exchanging two numbers without a temporary variable is the height of stupidity.

And why do you think it is sooo stupid (unrelated to you comments about use of macros, which I agree with)? Did you read the template I posted (not my original code)? works with integers, floats and doubles. Won't work with c++ classes or C-style strings. I think the only way they can be swapped is via temp variable.

>>>2.Exchange two numbers without using a temporary variable.
>And why do you think it is sooo stupid
My answer might be that it attempts to teach how to avoid problems of the 70's while ignoring realities of present day -- and in the process teach bad coding practice.

[edit]Much the same goes for the question about multiplication without a * operator. I did my time with a Z80, but it too was long ago.

Thank you Junior Poster sara.rythm! Thank you for bringing up these question for the fun of it. As you can see, there are two kinds of people, the creative kind that get inspired by your puzzles, and the "go by the book apparatchiks" that find most of their pleasure in cutting you and others down. Unfortunately, this is Reality 101.

Yes, true! But i must say, this forum is quite helpful. And thanks for all the reply. Thank You. :cheesy:

>And why do you think it is sooo stupid
Because it's useless trivia. Questions like this are basically like tricky riddles: unless you already know it, you probably won't figure it out on your own. You also won't use it in the real world. Even the smallest embedded system will have enough spare memory for a temporary variable, and if it doesn't then there are far better ways to optimize space than to restrict the flexibility of your swap. It's also dreadfully easy to "improve" the trick and break everything, as vegaseat proved. Yes, it's good to know the trick, but it's even better to know why it shouldn't be used.

>the creative kind that get inspired by your puzzles, and the "go by the book apparatchiks"
There's a time and a place for creativity. Code should be written with clarity in mind, and ancient tricks that only serve to create bugs and obfuscate things have no place there. Be creative in your algorithms and you'll be a much better programmer for it. Be creative in "cool" micro-optimization code tricks and you'll just be shrugged off as an idiot who has never worked in the real world.

I've already been inspired by these puzzles, I've already solved them, and now I'm inspired by a higher quality of puzzle. You obviously take no pride in your work, or you would try harder to learn the "book" as well as think outside the box, and when to use the best one for the job. The two are not mutually exclusive as you seem to think.

>that find most of their pleasure in cutting you and others down
You still don't get it, do you? I take no pleasure in berating you, because when you do something stupid, it means I failed to properly teach you. Now, that could be because you're too arrogant to think I could teach you something, but that still doesn't change the fact that I have to correct the people that you incorrectly "inspire".

no it doesnt work you disregard any overflow errors. That to me makes it superflawed!

That was aimed at ancient dragon on his template swop two numbers function.The perils of replying before reading page 2

>The perils of replying before reading page 2
I always set the number of posts per page to the maximum so as to avoid that problem most of the time. :)

>And why do you think it is sooo stupid
Because it's useless trivia. Questions like this are basically like tricky riddles: unless you already know it, you probably won't figure it out on your own. You also won't use it in the real world.

yes, its a trivia question, but one that will separate the real programmers from the dabblers, the chaf from the weat, the men from the boys, thinkers from the robots -- you get the idea :) It teaches creative thinking, and isn't that one of the goals of higher eduational instutions?

no it doesnt work you disregard any overflow errors. That to me makes it superflawed!

That was aimed at ancient dragon on his template swop two numbers function.The perils of replying before reading page 2

[edit]my stupid comments deleted because they were for wrong thread :sad: [/edit]

Page 2 didn't exist when I posted that.

>It teaches creative thinking, and isn't that one of the goals of higher eduational instutions?
Bwahahahaha! No, one of the goals of higher educational institutions is to create conformists to fit nicely as cogs in the machine. If you're looking for creative encouragement, don't look at schools.

>but one that will separate the real programmers from the dabblers
Yes, yes, and the ones that don't answer: "That's silly, I'd never do it that way" are the dabblers. If I'm going to interview a programmer, and this is something I do fairly often, I'll use a more realistic question to separate the real programmers from the dabblers.

The reason for the overflow is because there was not enough memory allocated to hold the string! So yes, adding a few more bytes will fix that type of error. You can't stuff 16 characters into a 15-byte buffer, you can't push a cammel through the eye of a needle.

And don't be decieved into thinking std::string allocates only the number of bytes needed to hold the string. Of course its compiler dependent, but VC++ 6.0 version of that class allocates a minumum of 31 bytes -- even if only 1 byte is needed. Why? For speed and efficiency. It takes up too much time to allocate/reallocate exactly what is needed -- "memory of cheap" approach.

What are you babbling about? Your template function cannot swap strings, so why are you talking about strings? I get the feeling you're in the wrong thread.

>
What are you babbling about? Your template function cannot swap strings, so why are you talking about strings? I get the feeling you're in the wrong thread.

Yup. got my threads confused :D

i'll remind you of the func I was commenting on...

template<class T>
swapm(T &a,T &b)
{
	a = a + b;
	b = a - b;
	a = a - b;
};

Obviously this is flawed. Cant you see that? It has potential for overflow and producing wrong results.

i'll remind you of the func I was commenting on...
Obviously this is flawed. Cant you see that? It has potential for overflow and producing wrong results.

That was my first reaction too -- and yes, it does indeed produce overflow. But when tested with very large numbers -- INT_MAX from limits.h -- the template still produced the correct results with my compiler. I don't think there is a safe way to swap two integers without using a temp variable.

>the template still produced the correct results with my compiler
That doesn't mean it worked, it only means that your compiler happens to interpret undefined behavior as the behavior that you expected.

>I don't think there is a safe way to swap two integers without using a temp variable.
Not with a template, at least, not easily. But if you write a swap function to swap two integers, you can test for overflow without too much difficulty. Of course, if you had used a temporary in the first place, all of this undefined behavior and trickiness could be avoided. Now do you see why I think it's a stupid problem?

How is x ^= y; y ^= x; x ^= y; unsafe when x and y are equally sized integers? Is there a problem with using xor for signed integers? Well, I wouldn't really use it, because I've never swapped integers in my life.

As for swapping strings, there is a member function named 'swap' which tends to achieve the task in constant time.

>How is x ^= y; y ^= x; x ^= y; unsafe when x and y are equally sized integers?
Try it when x == y. Without special case tests, the XOR swap is hopelessly broken.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.