• 0

[C++] give me a program idea


Question

I want to try writing a C++ program. I'm going to start with a Windows-based console app as I'm not ready to delve into GUIs. I plan to use MS Visual C++ 2010 but using native C++ (not C++/CLI). Can someone please give me an idea of a simple program? I'd like to incorporate some math, opening/saving text files, and working with more than one function.

Thanks!

Also, when I'm done I will post the source code in hopes of having it reviewed foe possible improvements.

Link to comment
Share on other sites

Recommended Posts

  • 0

Make a program to compute the first N numbers of the Fibinacci sequence, and then write it out to a file. That should get you knee-deep in functions, recursion, arrays/lists, and console/file IO.

You could also expand it to prompt a text menu to the user and offer other computations such as factorials, exponents, or custom functions/sequences.

Link to comment
Share on other sites

  • 0

maybe a calculator / simple expression solver?

e.g.: your program gets an expression like: "5 + 8 * 9 / 1.5" and prints out the result.

would definitely involve more than one function - if structured properly.

file IO could be used for expression input and result output?

Link to comment
Share on other sites

  • 0

^ what are Fibinacci numbers?

Sorry, I spelled it incorrectly. It's "Fibonacci". It's a numerical sequence created by a guy named Fibonacci. http://en.wikipedia....ibonacci_number

It's actually rather interesting. The sequence grows at a rate that's called the "Golden Ratio" in geometry, and such a ratio can be seen all around nature. From the way coral shells grow in spirals to the ratio of finger bone lengths in a human hand (if you curl your fingers, they make a spiral in similar proportions to the Golden ratio). It's a cool little sequence.

Link to comment
Share on other sites

  • 0

Sorry, I spelled it incorrectly. It's "Fibonacci". It's a numerical sequence created by a guy named Fibonacci. http://en.wikipedia....ibonacci_number

It's actually rather interesting. The sequence grows at a rate that's called the "Golden Ratio" in geometry, and such a ratio can be seen all around nature. From the way coral shells grow in spirals to the ratio of finger bone lengths in a human hand (if you curl your fingers, they make a spiral in similar proportions to the Golden ratio). It's a cool little sequence.

I reckon I will give that a try. :)
Link to comment
Share on other sites

  • 0

Write a program to count the number of characters, words, and lines in a text mode file. You could then write this metadata to another statistics file. It's not too difficult, but it should allow you to try the features of the language.

Other ideas you might want to try are,

1. A simple database application. Perhaps an accounts program. OO is good at modelling real world objects, so think Account, Transaction, and Payee classes/objects.

2. A simple network file downloader akin to wget. This will familarise you with network programming.

3. A simple OpenGL game. This will test your geometry knowledge.

Link to comment
Share on other sites

  • 0

Alright, so I went ahead and wrote a program that generates a series of Fibonacci numbers. I'm open to suggestions for improvement. The code is below. I also attached a ZIP file containing the CodeBlocks.

#include <iostream>

#include <sstream>

using namespace std;

int main()

{

// Ask the user how many Fivonacci numbers to generate

cout << "How many Fibonacci numbers would you like to generate? You must generate at least 3. \n" << endl;

// Declare a variable to hold the response

int NumberToGenerate;

// Set the default value of the variable

NumberToGenerate = 1;

// Get the number from the user

cin >> NumberToGenerate;

// Make sure cin >> NumberToGenerate is at least equal to 3. If not, ask the user for a

// new number until it is greater than 3.

while (NumberToGenerate < 3)

{

cout << "You must enter an integer equal to at least 3. \n";

cin >> NumberToGenerate;

}

// Put a separator line

cout << "----------------------------------------" << endl;

// Inform the user of the number of Fibonacci numbers being generated

cout << "You have decided to generate " << NumberToGenerate << " Fibonacci numbers." << endl;

// Put a separator line

cout << "----------------------------------------" << endl;

// Allocate a dynamic array

// This code adapted from http://www.fredosaurus.com/notes-cpp/newdelete/50dynamalloc.html

int* FibonacciArray = NULL; // Pointer to int, initialize to nothing.

FibonacciArray = new int[NumberToGenerate]; // Allocate NumberToGenerate ints and save ptr in FibonacciArray.

// Initialize all elements to zero.

for (int i = 0; i < NumberToGenerate; i++) {

FibonacciArray = 0; // Initialize all elements to zero.

}

// Define the first two numbers of the array

FibonacciArray[0] = 0;

FibonacciArray[1] = 1;

// Define a variable to use for the While statement

int WhileCounterVariable;

WhileCounterVariable = 2;

// Define two variables for the While statement

int MinusOne;

int MinusTwo;

// Generate the numbers

while (WhileCounterVariable < NumberToGenerate)

{

// Set the values of MinusOne and MinusTwo

MinusOne = WhileCounterVariable - 1;

MinusTwo = WhileCounterVariable - 2;

// Set the value of the Fibonacci number in the array

FibonacciArray[WhileCounterVariable] = FibonacciArray[MinusOne] + FibonacciArray[MinusTwo];

// Increment WhileCounterVariable by 1

WhileCounterVariable++;

}

// Output the series of Fibonacci numbers

cout << "Here is the Fibonacci series: \n";

WhileCounterVariable = 0;

while (WhileCounterVariable < NumberToGenerate)

{

// Output the number

cout << FibonacciArray[WhileCounterVariable] << endl;

// Increment WhileCounterVariable by 1

WhileCounterVariable++;

}

// End the program

return 0;

}

int NextFibonacciNumber(int PreviousNumber1, int PreviousNumber2)

{

int NewNumber;

NewNumber = PreviousNumber1 + PreviousNumber2;

return NewNumber;

}

FibonacciNumbers.zip

Link to comment
Share on other sites

  • 0

A few things that come to mind:

1. if you're using a loop for "NumberToGenerate", also use it for the first iteration

2. I wouldn't use a C-array but a std::vector unless you don't want to delve into the STL yet.

3. please don't use NULL for anything in C++! It's really a bad hack and should not be used! either use "nullptr" or just initialize the array in one line. new throws an exception if you're out of memory, which would be the only case that your version would stay at "0" - NULL's actual value in C++?

4. I'd use a for-loop for the generation - saves you the two additional loops, furthermore you could merge the two loops (calculation & output)

5. Don't define and initialize a line later, initialize on definition!

Link to comment
Share on other sites

  • 0

First of all, I'd put all the logic to generate a number into its own function(s). That should help reduce the size of your main(), which let's be honest, is a bit unwieldy.

Second. Since your program accepts stdin values, it should really have a main program loop. This loop should continue to accept inputs until the user presses a special key (like 'q' for instance), or it receives an interrupt signal. Otherwise, your program just does a single run. This is fine for a program which is completely automated based on argv parameters, but for programs that read from stdin, it's better practise to process input in a main loop.

Third. Why not try using some OO features. Create a fibonacci class or something. As it stands, your code is basically C with C++ stream objects. Not that there's anything wrong with that, but if you want to learn C++, you should be focusing on OO design patterns, the STL, etc.

Link to comment
Share on other sites

  • 0

A hangman is a good program to build with the console. It'll require you to use

- loops

- conditionals

- strings

- text input/output

- random number generation

I wouldn't do that as a first program, but maybe 2nd or 3rd.

Link to comment
Share on other sites

  • 0

1. Don't captialise variables. That is only for class names.

2. Use /* */ for multi-line comments.

3. Use std::array or std::vector for arrays. Plain C-arrays are a big no no. (They automatically initialise to a default value or to nullptr if they are pointers)

4. Use nullptr over NULL. NULL is useless nowadays.

5. You should initialise the variable on the same line that it was declared, unless you need to initialize in a if statement to determine which one to set to it.

6. Use ++foo rather than foo++.

7. Use for (type value: array) { } rather than for (type; check; increment) { }

8. In your function you could have done return x + y; rather than make extra declarations.

Link to comment
Share on other sites

  • 0

Because post increment operator uses a temporary variable to

store the incremented value for a variable until it is used

in the next executed statement, whereas pre increment

operator not using any temp variable, it is just increase

that value at the time of execution using reference.

Link to comment
Share on other sites

  • 0

Because post increment operator uses a temporary variable to

store the incremented value for a variable until it is used

in the next executed statement, whereas pre increment

operator not using any temp variable, it is just increase

that value at the time of execution using reference.

This is what I call premature optimisation. You're trying to predict the behaviour and optimisations of compiler internals. This is a big no no. The OP should just concentrate on writing working code, and let the compiler deal with optimisations.

Link to comment
Share on other sites

  • 0

This is what I call premature optimisation. You're trying to predict the behaviour and optimisations of compiler internals. This is a big no no. The OP should just concentrate on writing working code, and let the compiler deal with optimisations.

Or just use it as a style everywhere, you may as well pick up a good style early on that just happens to be the faster way to do something.

As for examples there are plenty of basic games to do:

- Noughts and Crosses

- Sudoku

Then you can work on producing an AI to play against (minimax would be enough for Noughts and Crosses).

Or produce an automatic solver (Sudoku).

Link to comment
Share on other sites

  • 0

This is what I call premature optimisation. You're trying to predict the behaviour and optimisations of compiler internals. This is a big no no. The OP should just concentrate on writing working code, and let the compiler deal with optimisations.

Well I don't have much knowledge of C++, but PHP is written in C and I can definitely attest that ++$i is faster than $i++. It isn't trying to predict the behaviour of the compiler at all, it's just smart programming.

Using $i++ requires a temporary variable to be created, adding to the footprint by about 10%. KomaWeiss is correct.

More info on Google: Pre-increment vs post-increment C++

Link to comment
Share on other sites

  • 0

Using $i++ requires a temporary variable to be created, adding to the footprint by about 10%. KomaWeiss is correct.

More info on Google: Pre-increment vs post-increment C++

You linked to a google search which doesn't really tell me a damn thing about which site you think proves your point.

First I picked the site at the top of the list:

I compiled the above code with 0 and 1 for the #if macro and found that the resultant binaries were bitwise same. So, the preVspost changes contributed nothing for performance as the resultant binaries were exactly identical in either case. So, it's irrelevant if you use post or pre increment for the "for" loop index variable.

I realized that it does not matter if the operation is pre or post increment or assignment, if the value of the expression is not stored at all. So I modified the code to store the return value of the pre/post increment operations and decided to measure the performance. So the code became

?

The result was however surprising. Post-increment consistently outperformed pre-increment and finished faster always. I was startled about this observation.

http://psankar.blogspot.com/2011/03/pre-vs-post-increment-performance.html

Not surprising here: compilers notice that your code is basically doing the same damn thing in both cases and so produce identical binaries. In the second time he forced the code to produce slightly different outputs and found post-increment was faster. That's not right, maybe this guy is crazy!

Then I clicked one at random in the search results, somewhere near the middle of the first page (to avoid all the worthless sites at that top like "expert sexchange" that want you to register to see the discussion). Here's what I found:

These were both compiled using g++ -O0 to turn off compiler optimisation.

?

This was unexpected; the post-increment version appears to run faster. The actual difference in times was so tiny that for any meaningful loop body, the time spent in the loop body will be very much larger than the time difference between using i++ and ++i, so for all practical applications, either approach seems to be equally valid.

http://physical-thou...speed-test.html

If anything you've demonstrated the opposite of what you were arguing for, but I think a more charitable position is that it makes no appreciable difference (especially when you don't disable compiler optimization).

Do you have a more useful link to support your claim? One that doesn't intentionally hobble the compiler seems like something worth looking for.

Link to comment
Share on other sites

  • 0

Couldn't have said it better myself evn. Trying to optimise code by guessing what the compiler is going to do is a waste of time and effort, and in some cases actually has the opposite effect, as evn demonstated. Each compiler may perform optimisations differently, so it's impossible to predict the outcome.

A better post development method would be some sort of profile guided optimisation, but that should only be considered once an application is working to specifications already, and if speed is critical, otherwise, it's mostly a waste of time and resources that could be better spent writing code.

Link to comment
Share on other sites

  • 0

Holy **** ... I'm surprised so much discussion has been made on the topic of whether it's better to do var++ or ++var :o . Doesn't seem like such a big deal... I'm not writing a high-performance game or OS. LOL :p

Edit: is there a way using Visual Studio to test whether there is any performance difference between the two methods? I am kind of curious now.

Link to comment
Share on other sites

  • 0

Doesn't seem like such a big deal... I'm not writing a high-performance game or OS. LOL :p

It's really not a big deal, not even for a "high performance game or OS". The compiler is in a better position to decide how to optimise low level instructions. For high level programmers like us, It's best not to get bogged down with such trivial details.

Edit: is there a way using Visual Studio to test whether there is any performance difference between the two methods? I am kind of curious now.

In GNU/Linux, we can just do: time ./a.out. It's not really high precision though, and the differences are so small that it requires millions of loop iterations to measure anything.

As far as Windows goes, I believe it has a performance counters API as part of win32. That's if you want to monitor it internally. I'm sure there are external tools to do the same measurements too on windows.

Link to comment
Share on other sites

  • 0

<blah blah blah>

I was originally looking at the PHP docs on incrementing where 1 guy says:

$i++ took 8.47515535355 seconds and 2360 bytes

++$i took 7.80081486702 seconds and 2160 bytes

I moved on to a couple of other threads I found, and they all said the same thing.

As an example, here's a couple of Stack Overflow links:

http://stackoverflow...-performance-in

http://stackoverflow...i/561609#561609

I honestly couldn't care less.. look for yourself, the answers are out there... anything that requires a temporary variable to be created is obviously going to have a bigger footprint than something that does not.

Either way, as the OP has said, the effect of either is minimal.

Link to comment
Share on other sites

  • 0

I was originally looking at the PHP docs on incrementing where 1 guy says:

$i++ took 8.47515535355 seconds and 2360 bytes

++$i took 7.80081486702 seconds and 2160 bytes

And which interpreter was he using? You see the point. Each compiler/interpreter is different. It's quite possible the opposite might be true on a different compiler. You can't and shouldn't rely upon non-standard, undocumented compiler behaviour when writing code.

I honestly couldn't care less.. look for yourself, the answers are out there... anything that requires a temporary variable to be created is obviously going to have a bigger footprint than something that does not.

As evn pointed out, a lot of compilers will treat pre and post increment counters the same during compilation. Some might even optimise for post increment. No one really knows for sure, and therefore advocating one way or the other should be discouraged. Let the compiler worry about those details.

Either way, as the OP has said, the effect of either is minimal.

Agreed. There are far more important things to worry about than loop counter pre vs post increment operator debates.

Link to comment
Share on other sites

This topic is now closed to further replies.