Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

Solve : A note for all programmers?

Answer»

Everyone who is on a large-scale project can benefit from this simple, yet amazing advice. It's the best way to make sure your code works. It can be summed up as follows:

Work on a portion of your project. Comment thoroughly why each code block exists. Then, check back in a week.

Why? As you are WRITING your code, everything makes sense to you. Your train of thought is fresh and you don't forsee any errors. However, after about a week or so of not touching your code, the patterns you formed in your brain as you wrote begin to diminish. By the time you return to your code, you are looking with the critical eye of someone who never saw this code before.

Novelists have the same problem: Everything makes sense to them, but nobody else understands it. Then, the author re-reads the passage and says: "Wait. I was trying to say [insert point here]". Then, s/he rewrites it more clearly. This is a good strategy to implement when writing code.

The larger the project, the more you can benefit from this. As I TYPE, I am checking about a thousand lines or so of code. I need my comments; otherwise, it's incomprehensible. Even so, I'm finding tons of things I did that were redundant, prone to error, or just plain wrong altogether.

Of course, those who do programming for a career can't just tell their boss they're taking a week off to "de-familarize yourself" with the project. But that's what teams of programmers are for: To help watch for errors. This advice is BETTER suited for the solo programmer.Also be sure to compile your code every now and then to make sure there are no, compile errors, and syntax errors. That way when the project is completely finished all you have to worry about are the run-time errors.

8-)fffreak@fffreak

its a good idea to compile your code now and then but this WOULD eliminate the competitiveness of the coder, but im not suggesting the other way around, its just it would look like a trial and error BASIS, but in the long run, compile the code if you want the results at hand.

@Dilbert

good, a very good idea for new programmers

@spiderlucci

you have to create a new thread for this to make sure you have prompt reply, this would give irrelevance to the topic at hand.

thanks to all

no flames just directions:)Locking topic to prevent new questions from being asked in this thread.

2.

Solve : Intermediate C/C++ - #define?

Answer» The #define Keyword

For those of you who are coding in C or C++ and have to cut-paste a lot of code, this may be a big help. Normally, you shouldn't cut and paste code - it leads to horrible misunderstandings. However, in the event that an action (a block of code) needs to be done a lot, #define is excellent for helping with that.

How it works

#define is a pre-compiler instruction that does a simple text replacement. That's it. For example if you had this:

Code: [Select]#define BIG 512

int arrayObjects[BIG];
By the time the actual compiler began working with your code, it would see this:

Code: [Select]int arrayObjects[512];
The pre-compiler instruction, like comments, are stripped at this point, to save space.

This is particularly handy if you need a block of code to be executed a lot. An example is a command prompt game I wrote the other week. I needed delays in my code so users would READ the text line-by-line, as opposed to the bottom of a paragraph, which was my first inclination.

I used this (#include ) to do that:

Code: [Select]time_t X, y;
time(&x);
do
{
time(&y);
}
while((y - x) < 1.5); //1.5 second delay
I needed this code to repeat after each line of text. I couldn't just do this:

Code: [Select] time_t x, y;
cout << "A line of text here.\n";
time(&x);
do
{
time(&y);
}
while((y - x) < 1.5);
cout << "More text\n";
time(&x);
do
{
time(&y);
}
while((y - x) < 1.5);
Doing this ad infinitum is painstaking, annoying, and hard to read or maintain. There are two ways to do this. One is to put the declarations time_t x,y as a global variable and place the while loop in a function, then I can simply call

Code: [Select]cout << "Line of text\n";
smallDelay();
Assuming smallDelay() has the delay code, this works. But this is even neater, in that you can write as few as three letters each time (less is POSSIBLE, but the point of this is clarity, so...). Here's an example:

Code: [Select]#define PAU time(&x); \
do \
{ \
time(&y); \
} ]
while((y - x) < 1.5)

cout << "Line of text...\n";
PAU;
cout << "Second line of text...\n";
PAU;
And so on.

Possible problems with #define

#define is useful, but it can lead to trouble. #define does not do any type casting, which means it does not make sure you are assigning proper values to an int, string, or other variable. You could do this:

Code: [Select]#define BIG 512
using std::string;
int theInt = BIG;
string THESTRING = BIG; //Oops, meant to have 'char theString = "BIG";'!
The compiler would see

string theString = 512;

An int cannot be assigned to a char[]. In fact, you will probably see an error message almost exactly like the previous sentence. Having quotes around "BIG" makes the intended assignment: The character array 'B', 'I', 'G', '\0'. (Strings end in null 0)
3.

Solve : C++ strings in upper/lower case?

Answer» Question

I've got a program I'm writing in C++ and I need user input to be all lower or uppercase. How can I get this without spitting error messages every time someone capitalizes/doesn't capitalize a single letter?

Answer

This probably isn't a common question, but it's one that led me on a long chase with several answers that would mess up depending on the compiler. This is stupid. There is a method, quick and easy, that works in C++, and it should be kept within easy access, in my opinion, because anyone who is learning C++ will play with the GETLINE(cin) stuff and will want to use conditional statements with that input. It's all part of learning. So, an example:

Code: [Select]//To lowercase
string X = "DilBERt"; //So we get a mix.
for(int i = 0; i < 100; i++) //This makes sure that we get the whole word.
{
if(x[i] + 32 < 122) //122 is the VALUE for "z".
{
x[i] += 32; //32 is the difference between an uppercase and its lower counterpart
}
}
For conversion to uppercase, change the if statement to

if(x - 32 > 65) // 65 is the value for "A".

and x += 32 should be changed to x -= 32
4.

Solve : Operator overload -- Factorials (C++)?

Answer»

This isn't the solution I wanted to this problem, but it's pretty darn close, and it's easy to use.

What I have here is a header (.hpp) written in C++. It overloads the ! operator to allow factorials in your programs. This way, you don't have to write out the algorithm -- it's done for you and can be used almost as easily as the increment (++) operator.

For those who don't know, a factorial is the product of all integers leading up to that number. For example, 4! is 1 * 2 * 3 * 4, and 5! is 1 * 2 * 3 * 4 * 5.

The operator overload doesn't have a postfix in this case. I've created a class A that you can pass integers in. It is used like this:
!A()

where in the () is any legal integer or variable.

For example, to set x to factorial 5:
int x = !A(5);

To set something to the factorial of itself:
x = !A(x);

I apologize; I wasn't able to get something as tidy as "5!" as an expression. If anyone does, I'd appreciate it if they would share.

The actual working code is as follows:

Code: [Select]class A
{
public:
A::A(int x): theVal(x) {}
int operator!();
private:
int theVal;
};

int A::operator!()
{
unsigned long int theFactorial = 1;
for(int i = 1; i <= theVal; i++)
{
theFactorial *= i;
}
return theFactorial;
}

That's it, really. You then #include "factorial.hpp" into any .cpp file, and it's there for your coding purposes. All the syntax info is repeated in the .hpp file as a comment block, for easy access. A couple of notes also mentioned in the .cpp file:

NOTE that I use an unsigned long int for the actual factorial work. Factorials add up very fast. !A(16) is the limit for this header; anything higher causes it to display the bit value equivalent, which isn't what you want (it appears as a very large negative number).

This limit can be extended by changing all ints to doubles. However, then !A(10) and above gives answers similar to 12256+e26, and is therefore not desirable. (If you don't know why !A(17) is too much for a unsigned long, try it: 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 is a BIG number. How Calculator does it, I have no idea.)

Attached is the header file for C++, and a sample program that uses it, which I used to test my header. Enjoy.

[old attachment deleted by admin]Nice work

I hate being all negative, but I actually thing using the ! operating isn't a good idea. People might confuse it with its logical meaning, that is to invert a function. Simply calling the function fract() or something would be just as good.

You could try creating a number class, which contains a variable for the number, and methods for factorials and stuff.

Also try looking into macros. You might be able to use them to gt 4! to your desired meaning... I'll research it later for you. But I'm not sure it'll get it exactly like that.Inverting a function? I am aware that != is used as "not equalt o" but I've never heard of inversing a function with a ! in C++. If you can find something better than this, please post it. I've done the best I can with my knowledge, but I'd love to see a x!. Inverting might not be the correct word. ! makes true into FALSE and false into true. It is called NOT. For example (!a == B) is the same as (a != b).

My functions which do stuff, but would normally be void, I often make boolean and return whether they have been successful or not. For example, in my Noughts and Crosses game (Tic Tac Toe) I have a makemove(int x, int y) function. It returns true if the move was completed, or false if not (illegal move). So I can do this: if (!makemove(x, y)) {...request new move...} for example.

In my AI algorithim, it goes through the following stages: Can I make 3 in a row and win? Can I block a 3 in a row the opponent is about to make? *uses evaluation function to find good square*. If all else fails, move randomly. I have a boolean, foundmove, to track whether it has found a move, and stop the process, or to continue to the next stage. For example, if (!foundmove) nextstage(); . This is the same as (foundmove != true) or (foundmove == false) but provides a shorthand way of doing it.

The point I was trying to make was, using ! in your fractorial function, might be confusing if it is used as a boolean NOT else where in the program. To someone who is unaware of what A does, it might seem like A returns a boolean, and you want to take the inverse of that result into x.I see what you mean. That's why I mentioned that the user will want to make a comment or two to that effect, but it would be easier if one could just to 5! or something like that.

Trouble is, I can't think of an operator to overload that wouldn't cause confusion in some way. So if there's a way to circumvent this problem I'd love to have it; it'll make this that much easier.Code: [Select]#define factorial(val) \
unsigned long limit = val; \
val = 1; \
for (unsigned long i = 1; i <= limit; i++) \
val *= i;

This fufils a similar role, and macros are faster than functions. Well, only because they don't need to copy in or return values. So since most of the processing work is done inside the macro/function it doesn't really matter. Still, it's the principle. I don't think it's possible to use the ! charecter as a macro or function name.Code: [Select]#include <iostream>
using std::cout;
using std::cin;
using std::endl;

unsigned long int factorial = 1; //Global Variable used for the fatorial procedure.
int i;
#define FACTORIAL(x) \
for(i = 1; i <= reply; i++) \
{ \
factorial *= i; \
} \

#define ever ;;

int main()
{
for(ever)
{
::factorial = 1;
cout << "Enter an integer: ";
int reply;
cin >> reply;
FACTORIAL(reply);
cout << reply << "! = " << factorial << endl << endl;
}
return 0;
}
I like this one; it accepts much more than the other solution did, going as high as 33! without PROBLEMS. Looking back on my code, for some reason after 16 I get the negative of the correct answer, so I need to go back over that. I truly do like this better. Code: [Select]typedef unsigned long int ULONG;
class A
{
public:
A::A(int x): theVal(x) {}
ULONG operator!();
private:
ULONG theVal;
};

ULONG A::operator!()
{
ULONG theFactorial = 1;
for(int i = 1; i <= theVal; i++)
{
theFactorial *= i;
}
return theFactorial;
}
Code: [Select]#include <iostream>
#include "factorial.hpp"
using std::cout;
using std::cin;
using std::endl;

//NOTE: !A(variable || number) is factorial, NOT the "not" modifier.
int main()
{
cout << "Enter an integer: " << endl;
ULONG input;
cin >> input;
ULONG x = !A(input);
cout << input << " factorial is " << x << endl;
return 0;
}
This is the original program, revamped. It has all integers re-done as ULONG, which is typedef'd as unsigned long int. The program accepts up to 33! before returning 0.

However, I still like the macro better; it's smaller and easier to read. Too bad it can't be made perfect. Oh well. PS you only need to put using namespace std;In common usage I have seen ! being used as factorial.
Since we've got a bumpfest going on...


Code: [Select]Public Function Factorial(ByRef Num as Double) as Double
Factorial = Num * Factorial(Num-1)
End Function

VB6 doesn't let you do operator overloading though...


Quote from: Ashutosh32 on February 11, 2009, 10:17:19 AM

In common usage I have seen ! being used as factorial.

That's why Dilbert has defined the ! as an operator, Silly

the ! is one of a slim number of Postfix operators, where the operator appears after the number/value it operates on. NOT fun to try to parse an expression and handle these... Definitely a bigger pain then your standard UNARY operator (such as minus)
What is an expressionQuote from: diDy on March 15, 2010, 07:29:25 AM
What is an expression
This section of the forum is for answering questions that are frequently asked, just like yours. If you can't find your answer in this section of the forum, try this section: Computer Programming