# Need C++ project ideas!



## Maelstrom (Jan 27, 2011)

So I have to learn a little C++ for a freshman eng class, and in the future, with the degree I plan to go for, I imagine I'll have to learn a lot more C++. So I decided to go ahead a teach myself more than the class I'm currently in will (found a tutorial, and I can find more stuff online when the time comes). The issue is that I need ideas for programs to write so I can apply what I learn, and I cannot come up with any on my own. So TPU, what are some good C++ projects? Can be a wide array of difficulty, as I can tackle the harder ones in the future (I hope )


----------



## Batou1986 (Jan 27, 2011)

its a shot in the dark but something to group edit media tags like on videos and pictures would be something useful.


----------



## hellrazor (Jan 27, 2011)

Try to see if you can't make a program to draw a perfect circle, no matter what the resolution of the picture is.


----------



## Maelstrom (Jan 27, 2011)

Thanks guys for the quick responses. Keep 'em coming, even if the idea seems stupidly easy or hard.


----------



## streetfighter 2 (Jan 27, 2011)

I'd start with data structures.  Create a linked list and/or hash table using nothing more than pointers and basic variable types (so you can't _#include <vector>_).  Being able to create your own data structures will help you when thinking about solving problems using programming.

You can also do some work in algorithms.  If you want something really basic try solving the knapsack problem by implementing the greedy algorithm in C++.  For a slightly larger challenge you can try implementing Dijkstra's algorithm (but it may require a math background).

Now if everything I've said up to this point is spitting in the wind then I'd suggest you try something incredibly fundamental:
"_You need to go to work every day, and you need to come back home every night.  You have an umbrella, but you only bring it with you when it's raining.  So if it rains in the morning and your umbrella is at your house then you will bring your umbrella to work; but if it doesn't rain in the evening you'll leave your umbrella at work.  If I gave you the probability that it rains in the morning, lets call it M, and the probability that it rains in the evening, lets call it E, what's the probability that on any given day you'll be caught in the rain without your umbrella?

Solve it by running a large simulation of several thousand (or more) days and keeping track of how many days you get caught in the rain without an umbrella._"

If by some chance you've done everything I just said, then try writing multi-threaded programs:  create your own multi-threaded merge-sort; solve the dining philosophers problem using semaphores; create a local chat client using shared memory or pipes

BTW, most of the projects I mentioned were picked specifically because solutions to them in C++ are widely available.  No one should be forced to learn without examples IMO .


----------



## matobinder (Jan 27, 2011)

I'd vote to think data. Skip anything to do with a GUI/Graphics. All that is just bells and whistles.(but yes that can be where the money is...)

Adding a GUI just complicates the matter. Your objective is to learn C++.

With that said. You need something to muck with. If you don't have a GUI you need something tangible.

This is where I thought a Data Systems class I took was helpful.  Yes that was about 15 years ago, but the idea still holds the same and you will learn whatever language you are using...

let me make up a problem. Lets go start with the cast of this movie.

MachineX: This machine eats fig newtons.
UserY     : This machine is interested in how MachineX is doing.
ProcessX: This program reads in data data about what MachineX is doing and passes it to UserY     


So your goal is to write ProcessX. What does our Manual about MachineX say?
   MachineX logs its metrics data to a local file called XYZ. It closes out this file once a day, and renames it abcdefg.date. The data in this file is continuous, and represents the following format.

The first 16 bytes is the header:
The next 256 bytes is the data:

header is defined as
{
  byte 0-7 time stamp
  byte 8-12 is IP address
  byte 13-15 is unused
}

data is defined as
{
  byte 0-3 : Something ABC
  byte 4-7 : Something blah
  byte 8-15 : Something 16 bit...
  byte... you get the picture
}

---- 
So that was the end of our simple manual on what MachineX does.

SO write ProcessX to read in these binary  files, i.e first the header, then the data and repeat. Parse the info out. And then print a simple text report for UserY.

Heck here, if you want a GUI, make your data logical that would fit into a nice plot. Spit it out into a CSV and load it into a spreadsheet.

This makes sense to me. Hopefully more than just me. If you want to learn a language, first throw out anything thought of a GUI and focus on the basics. Data. Deal with data. Think about a GUI later.


----------



## matobinder (Jan 27, 2011)

Oh, I forgot my last part. Now the trick in all if this was in the details in the manual that I made up.

"MachineX logs its metrics data to a local file called XYZ. It closes out this file once a day, and renames it abcdefg.date. The data in this file is continuous, and represents the following format."

What this is telling you is that you are going to need to be reading data from a file in a certain directory. That file may be archive(moved) while you are reading it. It may grow in size. But there will always be a set of data in that directory. With a timestamped named on the file.

The simplest thing you can do is tell your User that they will only get data over 24 hours old. That way you don't need to worry about MachineX renaming/moving the file on you. UserX won't like that. So now is where it gets tricky.

The best part is this is all your own world. Start out with writing a simple MachineX that is really really nice. Don't have it do anything when you don't want it to. 

Write your app to read that data in.

Now start making MachineX evil. Make sure your app can handle that data in a sane manner


----------



## Kreij (Jan 27, 2011)

matobinder said:


> I'd vote to think data. Skip anything to do with a GUI/Graphics. All that is just bells and whistles.(



... and matrix transformation, vector mathematics, collision detection, artificial intelligencs, data structures, state machines, etc. I would hardly call it just "bells and whistles".

But anyway, how about writing a program that will take a file and encrypt it and then compress it. A good exercise in several areas.


----------



## streetfighter 2 (Jan 27, 2011)

Kreij said:


> ... and matrix transformation, vector mathematics, collision detection, artificial intelligencs, data structures, state machines, etc. I would hardly call it just "bells and whistles".
> 
> But anyway, how about writing a program that will take a file and encrypt it and then compress it. A good exercise in several areas.



Having written a lot of programs doing rather complex matrix/vector calculations for engineering finance, I can tell you that you don't need a GUI .  Also state machines, data structures, artificial intelligence, many physics/fluid simulations, statistics (matrices anyone? ) etc. (ad nauseam) can be done without any GUI whatsoever (but you'll probably want to plot the results later).  I've never done collision detection (at least not that I'm aware of).


----------



## Maelstrom (Jan 27, 2011)

Thanks ya'll. I did a bit of googling (googleing?) and found a good amount of project ideas as well. However, if you guys still have other ideas that might make a good project, don't hesitate to post it. I'm putting all the ideas in a word doc so I can I don't forget 'em


----------



## matobinder (Jan 27, 2011)

Yes, I wanted to keep it simple... but complex enough to justify writing it in C/C++


Something really neat to write, but does add the  need to dig into whatever OS internals you are on. Is a simple tool to take a directory name, and tell you want files are in it. You can then go farther, and decide "hey if its a jpg I can tell you more" since that is a nice defined type to be able to parse as a 3rd party.

But my basic statement still holds true I think. Don't worry about a big GUI presentation. Just have it be cout text. Try to deal with data. Whatever data you feel like. Just don't get caught up in the presentation of it.


----------



## Kreij (Jan 27, 2011)

streetfighter 2 said:


> Having written a lot of programs doing rather complex matrix/vector calculations for engineering finance, I can tell you that you don't need a GUI .  Also state machines, data structures, artificial intelligence, many physics/fluid simulations, statistics (matrices anyone? ) etc. (ad nauseam) can be done without any GUI whatsoever (but you'll probably want to plot the results later).  I've never done collision detection (at least not that I'm aware of).



SF2, you are absolutely correct. But no one ever screamed "HEADSHOT" while running one of those programs. rofl

@Mael ... You could always write a text only version of Tetris.


----------



## Maelstrom (Jan 27, 2011)

Kreij said:


> @Mael ... You could always write a text only version of Tetris



Lol that sounds awesome . If I do, I'm totally making it like the college humor video: 
Tetris God (watch it, it's funny)

LINE PIECE!!!!!


----------



## matobinder (Jan 27, 2011)

:> Write Tetris for a VT340 in Regis. If I can find it, I have the basis of it, as I tried doing thata few years back. 

The manual
http://vt100.net/docs/vt3xx-gp/

The graphic
http://en.wikipedia.org/wiki/ReGIS


That was back in my VMS days... I miss my VAX assembly...

yes this is why I think I hate graphics programming...


----------



## Kreij (Jan 28, 2011)

One of my early coding endeavors was on my TI99/4A (16K RAM).
I wrote a simple game where you were looking down a hallway at an intersection.
Randomly a space ship would fly across the hallway for you to shoot at.
It worked great until I wrote the collision detection, which ran it out of memory. 

My advice is to not just pick random projects, but pick something that interests you.
In my experience, the normal school projects are rather boring little exercises.

It all depends upon your experience too.
Many years ago a good friend of mine (I consider him a mentor) was working on a CS project for his Masters in CS and Electronic Engineering, and I asked him about the project.
He shrugged and said, "We have to write a compiler parser. A quaint little exercise." 
I look back now and realize that would be rather droll and tedious.


----------



## ctrain (Jan 28, 2011)

I found it a lot of fun to get into graphics stuff. My first project was a simple 2d scrolling starfield effect. It's very simple once you think about it and it's fun to watch. Later you can branch into a simple 3d one is only a little more so since it's super simple to do the 3d transform if your view is centered in the world, no matrix or vector math needed.

Basic drawing is simple to set up on Windows.


----------



## Maelstrom (Jan 28, 2011)

Thanks for all the ideas and advice guys, I really appreciated it! Oh and Kreij, while you are correct that the school projects are generally "boring", they can be hilariously fun when you know more than you should and add stuff that shouldn't be there (but that actually helps the program). Or at least, I found it fun xD


----------



## Bot (Jan 28, 2011)

how about a refrigerator inventory program that automatically creates a shopping list with re-order items. best of all, integrated barcode scanner. 
something is empty, scan it and it automatically gets taken off the inventory and added to the re-order list, which can then be printed out.


----------



## Maelstrom (Jan 28, 2011)

Bot said:


> how about a refrigerator inventory program that automatically creates a shopping list with re-order items. best of all, integrated barcode scanner.
> something is empty, scan it and it automatically gets taken off the inventory and added to the re-order list, which can then be printed out.



That's actually a really cool idea, thx!


----------



## codyjansen (Jan 28, 2011)

Bot said:


> how about a refrigerator inventory program that automatically creates a shopping list with re-order items. best of all, integrated barcode scanner.
> something is empty, scan it and it automatically gets taken off the inventory and added to the re-order list, which can then be printed out.



that would be amazing.


----------



## olithereal (Jan 29, 2011)

Hey guys, just want do stop by and say that I've been looking at project ideas for C++ too, and that I have saved all of yours! It's good stuff, hoping to get on that soon, when I get some time!

College semester just started so I don't have much time. Network Programming class and COBOL (fuck yeah!) class' exercises take a huge amount of time, so yeah. When I get more time I'll jump on these!


----------



## Kreij (Jan 31, 2011)

Bot said:


> how about a refrigerator inventory program that automatically creates a shopping list with re-order items. best of all, integrated barcode scanner.
> something is empty, scan it and it automatically gets taken off the inventory and added to the re-order list, which can then be printed out.



I was thinking about this and it would really be pretty easy to code.

Hmmm .. so did someone else. Looks like it took them about 10 hours to do it as an online app using Python and MySql.
Grocist
His does not appear to keep a running inventory list, though, just what to re-order. Still a cool idea.


----------



## W1zzard (Jan 31, 2011)

make that an iphone/android app using the integrated camera that creates the shopping list for you on the device


----------



## Bot (Jan 31, 2011)

Kreij said:


> I was thinking about this and it would really be pretty easy to code.
> 
> Hmmm .. so did someone else. Looks like it took them about 10 hours to do it as an online app using Python and MySql.
> Grocist
> His does not appear to keep a running inventory list, though, just what to re-order. Still a cool idea.



thanks, that is pretty .. RSS feed for a grocery list? nice


----------



## Kreij (Feb 1, 2011)

Have you picked a project, Mael? If so what are you working on?
Inquiring minds want to know !! lol


----------



## joomlads07 (Feb 5, 2011)

Linux system tools. I do a lot of these because you don't have to waste hours of your life writing a pretty user interface

The sorts of things I am doing lately are as follows...

* RPN math solver (command line math or read from file).
* Assembly Language interpreter (a proprietary conceptual demo).
* C/MySQL interface generator (builds corresponding DB tables and C structs based on lists).


----------



## Maelstrom (Feb 9, 2011)

Kreij said:


> Have you picked a project, Mael? If so what are you working on?
> Inquiring minds want to know !! lol



Oh crap, sorry, didn't realize people we're still responding to this thread, lol.

Project wise? Nothing. This semester has become much busier than I expected it to be (a ton of reading for multiple classes). So basically what I have been doing is reading the c++ tutorial on cplusplus.org (.com?) and then using all that I learn on making my c++ assignments waaaaaay overcomplicated . It's lots of fun, plus I am learning a good deal too. Once I have some time I'll sit down and work on some of the projects y'all suggested (spring break/summer). Damn college and its work, shouldn't it know by now that college is for fun and goofing off


----------



## Kreij (Feb 9, 2011)

Good for you. Stick with it and all the hard work will pay off.


----------



## xbonez (Feb 9, 2011)

While its extremely important to learn by reading concepts and stuff, one thing I have realized from personal experience is things don't persist in mind for long unless you actually utilize them. What I do, when learning a language is learn a concept (say dictionaries), then write a tiny program right away to use them. Keep building on this, so if the next concept u learn is serializing/deserializing XMLs, write a program that, say, deserializes an xml, adds the data to a dictionary.


----------



## MadClown (Feb 13, 2011)

make a video game, about dolphins with flamethrowers


----------



## Kreij (Feb 16, 2011)

MadClown said:


> make a video game, about *zombie* dolphins with flamethrowers



Fixed. lol


----------



## Brandenburg (Feb 17, 2011)

I go through the same thing as the OP on what projects to undertake. But for me.. I do a sort of cost/time/usability analysis..As my time it worth something.. even to me.Kind of abstract concept and rarely is anything put to paper... Took me 6+ months to decide on my last project.. A board game to PC convert thats in VB and is like 5000 lines now..  not a small undertaking Originally.. It was just to learn new ideas AND was never really meant to finish it.. 55% or so percent later.. LOL.. I think I will eventually finish it

When I was in school for Electronics, I wrote two programs.. One was for instantaneous voltage/current and the other was a very professional looking program for my physics teacher called Vector Summation..Granted.. all are written in Visual Basic 2007 but I could of done it in C++,Java, or C#..BUT VB is so much faster and VB is my love. I'm at the point now, it's what I call.. "Perpetual Learning"..



> While its extremely important to learn by reading concepts and stuff, one thing I have realized from personal experience is things don't persist in mind for long unless you actually utilize them. What I do, when learning a language is learn a concept (say dictionaries), then write a tiny program right away to use them. Keep building on this, so if the next concept u learn is serializing/deserializing XMLs, write a program that, say, deserializes an xml, adds the data to a dictionary.



I do the same thing but I start out with a larger project that has alot of concepts in it

My next idea might be to scan my movies/music folder and catalog all items and export it to an excel file

@ the OP
Let us know what project idea you have decided on..To be honest.. I cant think of any projects for you.. Last project in C++ I did was to write the game farkle using GDI and to start on a black jack game done in console


----------



## Maelstrom (Feb 17, 2011)

Spring break is getting closer (hellz ya!), just gotta get through 4 o'clock quizzes (think midterm, but instead of 2 exams per semester, its 3). Once that's done, its selling pc parts/c++ project time! Was thinking about going through this list I found of project ideas http://www.cplusplus.com/forum/beginner/3473/. # 25 on the list would be useful for my differential equations and linear algrebra class  (though my calculator can already do them )

Edit: Holy crap, got the best idea ever for my math class. Expand on matrix multiplication/addition and make it so the program can do E.R.O http://en.wikipedia.org/wiki/Elementary_row_operations. Oh ya, that's my next project, as that will be very helpful for my class!!


----------



## Brandenburg (Feb 17, 2011)

After reading what I had wrote again



> BUT VB is so much faster



VB is faster to develop BUT not in actual speed of execution ...  Most new what I meant I feel but.......


----------



## Kreij (Feb 17, 2011)

> A board game to PC convert thats in VB and is like 5000 lines now.. not a small undertaking



They asked me to write a database based ERP program at work. Last time I checked it was at about 50,000 lines of code. DOH !! lol

What keeps me interested in the project is that I know someone will use it and it is custom designed for them so they like it a lot. The downside is I'm the only coder and I have to generate all the reports (as well as manage the networks, computers, and be a DBA for two companies).

I guess I love being a geek. 
More beer please.

@Brandenburg : With the compile optimizations that occur, the .Net languages are all pretty close in execution speed.


----------



## W1zzard (Feb 17, 2011)

110k lines of code for gpuz, got curious, spent like 10 minutes finding a LOC counter, ended up using http://www.jsankey.com/software/csl/csl.htm


----------



## PVTCaboose1337 (Feb 17, 2011)

W1zzard said:


> 110k lines of code for gpuz, got curious, spent like 10 minutes finding a LOC counter, ended up using http://www.jsankey.com/software/csl/csl.htm



Do you count "}" and similar as a line of code?  If so I would imagine that is about 20% of the code.


----------



## Kreij (Feb 18, 2011)

Heck yeah you count the "}" lines. Bragging rights you know. lol


----------



## xbonez (Feb 18, 2011)

If you're counting physical lines, you count everything including {s. Some people prefer a count of logical lines, in which case the count is a lot lesser.


----------



## Kreij (Feb 18, 2011)

It really doesn't matter unless you are getting paid by lines of code.
I'm not, so for me it's just an eye opener to see how much work I've actually done.
Sort of a personal best kind of thing since I am not competing with anyone.

A little off topic, but it's interesting to examine projects from a dependancy view.
What I mean is that both W1zz's GPU-Z and my ERP program (although private) have outlived many multi-million dollar game budgeted productions.
People (whether many or a few) who depend on your work keep it alive and create a continual need for it to be robust and adaptive for a changing environment, which in turn requires you as a programmer to adapt to those needs in your code.
As a coder, there is no better feeling than when someone says, "It's just what I needed/wanted, well done."


----------



## PVTCaboose1337 (Feb 18, 2011)

Because I went off topic I'll give you some ideas of what I did for fun:

-I made a RAR and JPG combiner, which would hide RAR's in JPG files.  Worked faster than cmdprompt.  

-I made a hidden RAR finder.  I then tested it by lurking 4chan and downloading 1000 pictures.  I found a WHOLE bunch of hidden RARs.  And a whole bunch of porn inside them.  '

-I made a program to put up a wall between the router and the internet.  Pretty much it would redirect the router to thinking the internet was coming from an imaginary place.  Therefore it would not work.  I did this on my router, not the schools.  

-I made a program in order to automatically broadcast the TPU recent posts to login window in Windows.  This does still not work as it should.  

Kinda fun to mess around with good and evil, as long as you have access to things to test on, with permission.  Or just buy your own gear.  

I also was messing with a little AI stuff, but I was unable to get too far with my limited understanding of structures of logic.


----------



## Brandenburg (Feb 18, 2011)

Only mentioned the lines of code on my "small" project because its in VB which does a lot of things for you so theoretically it should be less lines. In my experience C++ takes a minimum of 4 times the amount of code to do a windows program than VB...i.e. Not Console..  In the game im writting.. I exclusively use classes,properties,enumerators and several functions that are reused 1000's of times.. In other words.. Its written very lean and IMO efficient... Its so well organized that once the groundwork was laid out.. everything just fell into place..To me.. Its a work of art in code..

Ill post some snapshots of it tomorrow in a new thread.. I'm sure some will laugh but  it works and the forms are laid out pretty good.. Still haven't decided on a few things though...Its perhaps 50% done

here is a screenshot of a program I did for my physics instructor that earned me a +10 on a test.. Just did it because I was bored.. I showed it to him in a impromptu meeting.. and he loved it..  asked me to make a few changes..  mainly with the calculations of the 4th quadrant as in certain situations... it would calculate the wrong value






Next project will be an automatic catalog program for my movies/music on my PC..Never scanned folders before..  Will be very new to me

My suggestion to the OP is to make a "tool" that has a legitimate use for him...and sorry for mildly hijacking your thread


----------



## Maelstrom (Feb 18, 2011)

It's all good. Started my E.R.O program, and its proving difficult to transform what I do when solving these problems (which is a lot of comparisons, multiplication, addition, and subtraction between the rows of matrices) into code. Granted, c++ probably isn't the best language to do what I'm doing, but I'm still going to go for it anyways xD


----------



## xbonez (Feb 18, 2011)

After you're done with it, you could try porting it to a C# Winforms app so you can have a nice GUI too


----------



## Kreij (Feb 18, 2011)

If he's using Visual C++ he has access to all the same GUI classes as Visual C# does.
You get even more control if you write the GUI in WPF using XAML, but it's kind of a pain in the ass. Very powerful though.


----------



## W1zzard (Feb 18, 2011)

Kreij said:


> If he's using Visual C   he access to all the same GUI classes as Visual C# does.



not in "normal" unmanaged c++ using mfc


----------



## Kreij (Feb 18, 2011)

I haven't done much in C++ lately. 
Visual C++ 2010 is still unmanaged code without Win32 wrappers and completely allows for unsafe code, no?


----------



## Maelstrom (Feb 20, 2011)

Maelstrom said:


> It's all good. Started my E.R.O program, and its proving difficult to transform what I do when solving these problems (which is a lot of comparisons, multiplication, addition, and subtraction between the rows of matrices) into code. Granted, c++ probably isn't the best language to do what I'm doing, but I'm still going to go for it anyways xD



OK, so I just finished my E.R.O program. Just a little over 300 lines (I know that is nothing, but I'm still impressed by it ). It can also add/subtract and multiple matrices! I had thought it would take me longer, oh well. Now, I gotta pick a new project . 

Also, do you think I could post my code to have some of ya'll look at it? So ya'll can critique it, and such. Just as a reference point for what I know, I've read  this tutorial up to pointers, have a little experience in Java from my AP comp sci class, and a little other c++ knowledge from googling.

Edit: realized a weakness in the code, need to fix it, but I'll go ahead and post it (dealing with division by zero for the E.R.O part).


----------



## Brandenburg (Feb 20, 2011)

Post away..


----------



## Maelstrom (Feb 20, 2011)

Here it is, would probably be easier to read to just c-n-p it to a doc or something: Edit: Fixed the division by zero issue (i think), just had to add two if statements. 

```
/*
 * File:   main.cpp
 * Author: Maelstrom
 *
 * Created on February 18, 2011, 2:25 PM
 */

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <vector>

/*
 * This program asks the user to enter a matrix, and then offers the user a number of operations the user can do to the matrix they
 * entered. The program starts off by having the user input the dimensions of the matrix. Then, it asks for each element of the matrix. Current
 * operations the user can can select are addition, subtraction, and multiplication.  E.R.O will be added in the future.
 */
void add(std::vector < std::vector <double> >, int, int); //will add two matrices, one of which is a parameter.
void e_r_o(std::vector < std::vector <double> >, int, int);
void multi(std::vector < std::vector <double> >, int, int); //will multiple two matrices, one of which is a parameter.
void print(std::vector < std::vector <double> >, int, int); //prints out the matrix.

int main() {
    std::cout << "Welcome to the Matrix manipulation program! This program can do a number of different mathmatical operations to matrices"
            " including Gaussian elimination. ";
    std::cout << "Please enter the dimensions and the elements of the matrix. Once completed"
            ", you will be given a number of mathmatical operations that can be applied to the matrix. "
            "Note: if you wish to find the solutions to a linear system, make sure to include what the equations are equal to." << '\n';
    int column, row; //for dimensions of the mxn matrix.
    std::string input; //used to store all input.
    while (true) { //infinite loop, will on be exited out of when user enters appropriate info.
        std::cout << "Enter the number of rows for the matrix: "; //asks for # of rows.
        std::getline(std::cin, input); //takes input as a string
        std::stringstream convert(input); //enters string into the stringstream.
        if (convert >> row) { //checks if the input can be converted into a double. If it can, it enters the number into row.
            if (row != 0) { //can't go having a matrix with 0 rows
                break; //exits out of loop.
            }
        }
        std::cout << "Error, please enter an appropriate number of rows." << '\n';
    }
    while (true) { //does the same as above, but for the number of columns.
        std::cout << "Enter the number of columns for the matrix: ";
        std::getline(std::cin, input);
        std::stringstream convert(input);
        if (convert >> column) {
            if (column != 0) {
                break;
            }
        }
        std::cout << "Error, please enter an appropriate number of columns." << '\n';
    }
    std::vector <std::vector <double> > matrix; //creates a multidimensional vector. Used instead of an array for ease of parameterizing.
    matrix.resize(row);
    for (int i = 0; i < row; ++i) {
        matrix[i].resize(column);
    } //makes the vector the desired size by using .resize
    std::cout << "Please enter each element for the row." << '\n';
    int r = 0;
    while (r < row) { //asks user for the elements in each row of the matrix. Will repeat while r < row.
        int c = 0;
        std::cout << "Row " << r + 1 << ": ";
        std::getline(std::cin, input);
        std::stringstream convert(input);
        while (true) { //loops indefinately, until each element has a double.
            if (convert >> matrix[r][c]) { //checks to see if input can be converted into a double
                ++c; //moves to next column
            }
            else {
                break;
            }
            if (c == column) { //once the last column has a double, will break out of while loop.
                ++r; //moves to next row
                break;
            }
        }
    }
    while (true) { //asks user to select which operation they would like to do to the matrix.
        std::cout << "Select which operation you would like to use on the matrix. " << '\n';
        std::cout << "0) Print matrix" << '\n';
        std::cout << "1) Matrix addition and subtraction" << '\n';
        std::cout << "2) Matrix multiplication" << '\n';
        std::cout << "3) Gaussian elimination" << '\n';
        std::cout << "Selection? ";
        std::getline(std::cin, input);
        std::stringstream convert(input);
        int selection;
        if (convert >> selection) {
            if (selection == 0) { //allows user to print their matrix in all its glory!
                print(matrix, row, column);
                break;
            }
            else if (selection == 1) {
                add(matrix, row, column); //calls the add function, which will add to user inputed matrices.
                break; //breaks out of infite while loop.
            }
            else if (selection ==2 ) {
                multi(matrix, row, column);
                break;
            }
            else if (selection == 3) {
                e_r_o(matrix, row, column);
                break;
            }
        }
        std::cout << "Please enter an appropriate selection." << '\n';
    }
    std::cout << "Would you like to rerun the program?" << std::endl; //gives user the option to rerun program by using recursion.
    std::cout << "Y/N? ";
    std::getline(std::cin, input);
    if (input == "y" || input == "Y") {
        return main();
    }
    return 0;
}
/*
 * Allows for the addition and subtraction, based on user choice, of two matrices. The first one is taken from the main, along with
 * the row and column length of the first matrix. Using a multidimensional vector, a second matrix is made with the same dimensions
 * as the first matrix. User is then asked to input each element. Finally, the matrices are either added or subtracted, and then
 * the result is printed out, using the print function.
 */
void add(std::vector < std::vector <double> > nom, int row, int column) {
    std::cout << "Please enter the elements for the row. Note: in order to add or subtract matrices, the dimensions of both must be the same."
            " The dimensions of the first matrix you entered will be used for this one." << '\n';
    //using same method to acquire details of second matrix.
    std::string input;
    std::vector <std::vector <double> > nom2;
    nom2.resize(row);
    for (int i = 0; i < row; ++i) {
        nom2[i].resize(column);
    }
    int r = 0;
    while (r < row) {
        int c = 0;
        std::cout << "Row " << r+1 << ": ";
        std::getline(std::cin, input);
        std::stringstream convert(input);
        while (true) {
            if (convert >> nom2[r][c]) {
                ++c;
            }
            else {
                break;
            }
            if (c == column) {
                ++r;
                break;
            }
        }
    }
    std::cout << "Addition or subtraction? "; //user can chose to add or subtract.
    std::getline(std::cin, input);
    if (input == "Add" || input == "add" || input == "Addition" || input == "addition") {
        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < column; ++j) {
                nom [i][j] += nom2 [i][j]; //adds each corresponding element of the two matrices together. Goes row by row.
            }
        }
        print(nom, row, column);
    }
    else if (input == "Subtract" || input == "subtract" || input == "Subtraction" || input == "subtraction") {
        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < column; ++j) {
                nom [i][j] -= nom2 [i][j]; //same as above, just with subtraction.
            }
        }
        print(nom, row, column);
    }
    else {
        std::cout << "Please choose to add or subtract." << '\n';
    }
}
/*
 * Uses Gaussian-Jordan elimination to put the matrix into the reduced row-echelon form. It then prints out the matrix.
 */
void e_r_o(std::vector < std::vector <double> > nom, int row, int column) {
    //puts the matrix into row-echelon form.
    int a = 0, b = 0, c = 1;
    while (a < row - 1) {
        if (nom [a][b] != 0) {
            int y = 0;
            std::vector <double> holder;
            holder.resize(row - 1);
            for (int i = c; i < row; ++i) {
                holder [y] = (nom [i][b]) / (nom [a][b]);
                ++y;
            }
            int z = 0;
            for (int i = c; i < row; ++i) {
                for (int j = b; j < column; ++j) {
                    nom [i][j] -= holder [z] * nom [a][j];
                }
                ++z;
            }
        }
        ++a;
        ++b;
        ++c;
    }
    //makes leading element for each row a leading one.
    for (int i = 0; i < row; ++i) {
        double k = nom [i][i];
        for (int j = 0; j < column; ++j) {
            nom [i][j] /= k;
        }
    }
    //makes the row-echelon formed matrix into a reduced row-echelon form.
    int d = row - 1, e = column - 2, f = row - 2;
    while (d > 0) {
        if (nom [d][e] != 0) {
            int y = 0;
            std::vector <double> holder;
            holder.resize(row - 1);
            for (int i = f; i > -1; --i) {
                holder [y] = (nom [i][e]) / (nom [d][e]);
                ++y;
            }
            int z = 0;
            for (int i = f; i > -1; --i) {
                for (int j = (column - 1); j > -1; --j) {
                    nom [i][j] -= holder [z] * nom [d][j];
                }
                ++z;
            }
        }
        --d;
        --e;
        --f;
    }
    print (nom, row, column);
}
/*
 * Multiplies two matrices together, and then prints out the product. Gets the first matrix from the parameter, and the second
 * is created by the user.
 */
void multi(std::vector < std::vector <double> > nom, int row1, int column1) {
    std::cout << "Please enter the dimensions of the second matrix. Note: The number of columns of the first matrix must "
            "equal the number of rows of the second matrix." << '\n';
    std::string input;
    int row2, column2;
    while (true) { //asks for number of rows. Checks to make sure it equals the number of columns in the first matrix.
        std::cout << "Number of rows (must be same as number of columns of first matrix!): ";
        std::getline(std::cin, input);
        std::stringstream convert (input);
        if (convert >> row2) {
            if (row2 == column1) {
                break;
            }
        }
        std::cout << "Please enter an appropriate value." << '\n';
    }
    while (true) { //asks for number of columns.
        std::cout << "Number of columns: ";
        std::getline(std::cin, input);
        std::stringstream convert (input);
        if (convert >> column2) {
            if (column2 != 0) {
                break;
            }
        }
        std::cout << "Please enter an appropriate value." << '\n';
    }
    std::vector < std::vector <double> > nom2; //creates the second matrix based off the entered dimensions.
    nom2.resize(row2);
    for (int i = 0; i < row2; ++i) {
        nom2[i].resize(column2);
    }
    std::cout << "Please enter the elements for each row." << '\n';
    int r = 0;
    while (r < row2) { //User enters each element for each row. Has checks in place to make sure user enters doubles.
        int c = 0;
        std::cout << "Row " << r+1 << ": ";
        std::getline(std::cin, input);
        std::stringstream convert(input);
        while (true) {
            if (convert >> nom2[r][c]) {
                ++c;
            }
            else {
                break;
            }
            if (c == column2) {
                ++r;
                break;
            }
        }
    }
    std::vector < std::vector <double> > nom3; //creates a third matrix to hold of the values of other two matrices multiplied.
    nom3.resize(row1); //has row1 rows, and column 2 columns.
    for (int i = 0; i < row1; ++i) {
        nom3[i].resize(column2);
    }
    /*
     * Algorithm for multiplying the two matrices. Multiples the corresponding element of the ith row of the 1st matrix and jth column
     * of the 2nd matrix. Adds them together, and places the final number into the a(i,j) element of the product matrix.
     */
    int z = 0;
    while (z < row1) {  //Z is used to track the row number for the 3rd and 1st matrix. Stops once it equals row1.
        for (int a = 0; a < column2; ++a) { //Used to track the column of the 3rd and 2nd matrix. Stops once it equals column2.
            for (int b = 0; b < row2; ++b) { //Used to track the column for the 1st matrix, and the row for the 2nd matrix.
                nom3[z][a] += nom[z][b] * nom2[b][a]; //Multiplies the elements together, then adds the product to the corresponding element in nom3.
            }
        }
        ++z;
    }
    print(nom3, row1, column2);
}

/*
 * Prints each element of the matrix.
 */
void print(std::vector < std::vector <double> > nom, int row, int column) {
    for (int i = 0; i < row; ++i) {
        for (int j = 0; j < column; ++j) {
            std::cout << nom[i][j] << " ";
        }
        std::cout << std::endl;
    }
}
```


----------



## ctrain (Feb 21, 2011)

Kreij said:


> I haven't done much in C++ lately.
> Visual C++ 2010 is still unmanaged code without Win32 wrappers and completely allows for unsafe code, no?



Visual C++ is just the IDE, not a language, C++/CLI is the replacement for managed C++.


----------



## Brandenburg (Feb 21, 2011)

Maelstrom said:


> Here it is, would probably be easier to read to just c-n-p it to a doc or something: Edit: Fixed the division by zero issue (i think), just had to add two if statements.



Yea.. Computers dont like it when you try to divide by zero... 

I guess you did something similar to this.. No surprise my code looks like VB..  VB just flows more naturally to me..

if (dividend<>0) then
      quotient=divisor/dividend
end if

Code looks good... There is a reason I dont do C++ anymore  LOL..  I did notice on your Cout statements.. you wrote them like std::cout<<"Blah".. IMO.. An easier way to write it would of been to use this statement right below your last include.. *using namespace std;*.. When using this.. You just have to say cout<<. To me.. its just cleaner looking

Here is a small snippet of code for a game I did in C++ like 4 years ago..Its relatively simple I think.. One of my strong suits is nested statements...

```
case WM_LBUTTONDOWN:{
	XCoord=(int)LOWORD(lparam);
	YCoord=(int)HIWORD(lparam);
		if (StartFlag==true){
			for (int i=0;i<=MaxDie-1;i++){
				if (DiceRolls[i]>=0){
					if (Die_Selected[i]==false){
						if (XCoord >=DiceShell[i].left && XCoord <=DiceShell[i].right){
							if (YCoord >=DiceShell[i].top && YCoord <=DiceShell[i].bottom){
										FillRect(g_Hdc,&DiceShell[i],RedBrush);
										FrameRect(g_Hdc,&DiceShell[i],OutLineBrush);
										Die_Selected[i]=true;
										PrintNumbers();
							}
						}
					}else{
						if (XCoord >=DiceShell[i].left && XCoord <=DiceShell[i].right){
							if (YCoord >=DiceShell[i].top && YCoord <=DiceShell[i].bottom){
										FillRect(g_Hdc,&DiceShell[i],WhiteBrush);
										FrameRect(g_Hdc,&DiceShell[i],OutLineBrush);
										Die_Selected[i]=false;
										PrintNumbers();
							}
						}
					}
				}
			}
	}
	return(0);
	break;
}
```


----------



## Maelstrom (Feb 22, 2011)

Yeah I know about using namespace std, but from what I've read, it generally isn't advised as there can be potential conflicts (source) (although it probably doesn't matter to me since my programs aren't all that complex and such). But yeah, I've made a number of modifications and added some more stuff to the program as well. This will probably be my main project until school is over (I'd like it to be able to help me with all my math homework, and maybe even chem homework )


----------



## Brandenburg (Feb 22, 2011)

Thx for the link..  When I was in school, they told us to the the using namespace std;


----------



## Maelstrom (Feb 22, 2011)

Brandenburg said:


> Thx for the link..  When I was in school, they told us to the the using namespace std;



Yeah I was taught that too, but then they also taught us to use system("pause"), which is a huge no-no.


----------



## streetfighter 2 (Feb 22, 2011)

Maelstrom said:


> Yeah I was taught that too, but then they also taught us to use system("pause"), which is a huge no-no.


You're only hearing that (and the "using std" bit) from veteran programmers who are working on non-trivial programs.  For a program of the complexity you wrote it's not exactly going to break the bank with performance/portability; it's just "good practice" and programmers like their "good habits". 

I still use "printf()" for debugging, and I know I shouldn't. 

I didn't post earlier because I don't want to be a dick but you know there are quite a few (free) math libraries for C/C++ that implement those functions.  I still think you wrote a solid program and I like your commenting style.


----------



## Maelstrom (Feb 22, 2011)

streetfighter 2 said:


> You're only hearing that (and the "using std" bit) from veteran programmers who are working on non-trivial programs.  For a program of the complexity you wrote it's not exactly going to break the bank with performance/portability; it's just "good practice" and programmers like their "good habits".
> 
> I still use "printf()" for debugging, and I know I shouldn't.
> 
> I didn't post earlier because I don't want to be a dick but you know there are quite a few (free) math libraries for C/C++ that implement those functions.  I still think you wrote a solid program and I like your commenting style.



Yeah, I know why they tell us to use them, and for my programs it doesn't matter if I use them or not, but I still like doing it the more "correct way" I guess. As for your second comment: well that wouldn't be fun! I could of taken the easy way out and just had mathematica solve my math problems, but that wouldn't have given me c++ experience, lol


----------



## Brandenburg (Feb 22, 2011)

I believe in commenting based on the job i'm doing.. If I know others might need to maintain my code in the future, ill comment more heavily but if its just for me.. Ill comment ever so often and only at the function/procedure level.. Rarely line by line unless it is ASM.. 

I was involved in a class project to program and build a stop light and to control a sequence of lights via microcontroller (PIC16F87XA) Since I had the most programming experience, I volunteered to do the bulk of the programming... No one argued with me BTW.. LMAO.. Mainly my part was a menu system via buttons and lights on a circuit board,debouncing of those buttons,timer,Demo mode and to incorporate everybody's light sequences into the program..NOW this project I commented ALOT because future students in the following semesters might edit the code...  Its easy to read FOR ME.. but for others with little or no coding skills .. it might be a bit confusing

On my personal projects, I just use very descriptive qualified names and that is sufficient in most cases to get away with few comments..Proper organization of the code helps I also mainly code in visual Basic and its more readable than C++ IMO

Here is the code for the microcontroller..Just thought id post it... Pretty simple EVEN though the PIC High C compiler is quirky as hell. Spent ALOT of time wrestling with that.. The demo.cpp is left out .. basicall its just all the sequences in a big main loop and a loop for each sequence.. Iterations can be varied by the GLOBAL.H file..  Organizational of a programn are just as important as comments IMO.. DIGBIRT function is mine btw..  Wasnt obligated to write a light sequence but i did it.. yea.. im a showoff .. I also modified everyones code to work with the main code.I used defines on the LEDS and wanted it to be consistent throughout.
TRAFFICLIGHTS.ccp

```
//Neil W. Reich
//4-1-10

//CREDITS:

#include <htc.h>
#include "Sequences.h"
#include "Demo.h"

//*********************************
// CONFIGURATION FLAGS	
//DEBUGGER MODE			
__CONFIG(XT & WDTDIS & PWRTDIS & BORDIS & LVPDIS & WRTEN &
DEBUGEN & DUNPROT & UNPROTECT);

////PROGRAMMER MODE
//__CONFIG(XT & WDTDIS & PWRTDIS & BORDIS & LVPEN & WRTEN &
//DEBUGEN & DUNPROT & UNPROTECT);

//Prototyped functions
void Init();
void ProgramStart();

//Variable Declarations
int Selection;
long Idle;
bit DemoFlag;

//Functions
void Init(){
	ADON=0;			//Analog turned off
	PORTA=0;			
	PORTB=0;			
	TRISB= 0b00000001;			//Sets port B0 for input
	TRISA4=1;			//Sets port A for input
	Selection=0;
	Idle=0;
	DemoFlag=0;
}
/////////////////START OF PROGRAM////////////////////////////
void main(){
	Init();
	ProgramStart();
/////////////////////M E N U /////////////////////////
		switch(Selection){
			case 1:
				FancyDance_LEE();
				break;
			case 2:
				StopLight_MC();
				
				break;
			case 3:
				Chaser_Willie();
				break;
			case 4:
				SpeedTrap_LEE();
				break;
			case 5:
				thingamajig_Jensen();
				break;
			case 6:
				DOGBIRT();  
				break;
			case 7:
				DEMO();
				break;
			default:
				 DEMO();
				break;
		}
}
void ProgramStart(){
	do{
		Idle++;						//counts inactivity
		if(is_button_RA4_pressed()==1){//listens for button activity.  a return value of 1 is yes,0 is no
			Idle=0;						//resets because of Activity
			Selection++;					//counts the times the butten is pressed
				PORTB=Selection<<1;	//Displays the count in binary
				if (Selection>7){			//resets the counter when 7 is reached
					Selection=1;
					PORTB=Selection<<1;
				}
		}
							
		Delay(3);
		if (Idle > LIMIT-1){		//Starts demo if true
			Idle=0;
			DEMO();
			Init();
		}
   	}while(is_button_RB0_pressed() ==0);	//Exits loop when RB0 is pressed
}
```
BUTTONS.H

```
//DELAY FOR LED'S AND BUTTONS
void Delay( int duration){
	unsigned int i;
	for(;duration!=0;duration--){
		for(i=0;i<=TIME;i++){
			NOP();
			NOP();
			NOP();
		}
			NOP();
			NOP();
	}
}
///////////////////DEBOUNCED BUTTONS//////////////////////////
unsigned char is_button_RA4_pressed(void){
	if (RA4==0)	{				// is button pressed?
		Delay(60);				// wait 
		if (RA4==0)	{			// is button still has pressed status after delay?
			return 1;			//  if key pressed,return 1
		}
	}
		return 0;		// if key is not pressed, return 0
}
unsigned char is_button_RB0_pressed(void){
	if (RB0==0)	{				// is button pressed?				
		Delay(60);				// wait 
		if (RB0==0)	{			// is button still has pressed status after delay?
			return 1;			//  if key pressed,return 1
		}
	}
	return 0;					// if key is not pressed, return 0
}
```
GLOBAL.H

```
//CALIBRATION DATA
#define 	TIME 			100			//for calibrating the delay.. # of NOP's X3
#define 	LIMIT			2000		//Maximum inactivity( interations of while) allowed

#define 	MAXDEMO		1			//Maximum time demo will repeat
//Used for Dogbirt function only
#define		BASEDELAY	10			//Default Delay Time
#define		MAXTIMES	10			//Maximum interations in one direction
#define		PLACER			50			//Multiplier for delay
```
SEQUENCES.H

```
//Neil W. Reich
//4-0-10
#include <htc.h>
#include "Global.h"

//Header file that contains all of the various light sequences
//DEFINES LEDS
#define 	RED			0x02
#define 	YELLOW		0x04
#define 	GREEN			0x08
#define		CLEAR			0x00
//***************LIGHT SEQUENCES**************
void SpeedTrap_LEE(){
	while (is_button_RB0_pressed() ==0){
		PORTB = GREEN;
		Delay(700);
	
		PORTB =YELLOW;
		Delay(150);
	
		PORTB = RED;
		Delay(700);
	}
}
void FancyDance_LEE(){
	while (is_button_RB0_pressed()==0){
		PORTB = GREEN+RED;
		Delay(400);

		PORTB = YELLOW;
		Delay(100);

		PORTB =GREEN+RED;
		Delay(400); 
	}
}
void StopLight_MC(){
	while (is_button_RB0_pressed()==0){
		PORTB = RED;
		Delay(400);
	
		PORTB = YELLOW;
		Delay(400);
	
		PORTB =RED;
		Delay(400);
	
		PORTB = GREEN;	
		Delay(400);

		PORTB = YELLOW;
		Delay(400);
	
		PORTB =GREEN;
		Delay(400);
	}
}
void Chaser_Willie(){
	while (is_button_RB0_pressed()==0){
		PORTB = RED;
		Delay(253);

        PORTB =YELLOW;
		Delay(253);

        PORTB = GREEN;
		Delay(253);

		PORTB = YELLOW;
		Delay(253);
	}
}
void thingamajig_Jensen(){
	while (is_button_RB0_pressed()==0){
		PORTB =YELLOW+GREEN;
	//	RB3=CLEAR;
		Delay(400);

        	PORTB = GREEN+RED;//
		Delay(300);

        	PORTB = GREEN+YELLOW;
		Delay(300);

        	PORTB = GREEN+RED;//
		Delay(300);
	}	
}
void DOGBIRT(){
	int Count=0;
	int Count1=0;

	while(1){
		Count++;
		if (Count<MAXTIMES){
		//	BaseDelay=(BaseDelay+PLACER);
			for(int j=1;j<=4;j++){
				PORTB=1<<j;     //interation j1=2;j2=4;j3=8\
				Delay(BaseDelay);
			//	MaxLimit=BASEDELAY+(PLACER*Count);
			}
		}else{	
			for(int j=0;j<=3;j++){
				PORTB=8>>j;     //interation j0=2;j1=4;j2=8
				//Delay((PLACER*Count)-MaxLimit);
			}
		}
		if (Count>=MAXTIMES*2){
			Count=0;
		}
	}//end while
}
```


----------



## Maelstrom (Feb 23, 2011)

Very impressive Brandenburg!


----------



## Brandenburg (Feb 23, 2011)

thx.. was just lucky it all fell into place..  volunteering to take the lead in such a project is taking a gamble IMO..  If my part wasn't done right.. It literally effected everyone else in the class..  LOL..Main reason I volunteers because I knew I could do it better than anyone in class.. Hell.. I suspected they would of fucked it up.. Already had a CS degree and was working on my electronics degree.. So I guess I had slightly more experience being a code monkey than anyone in my department 

everyone else spent maby an hour doing their part.. I spent maby 15 in total.. but I was excused from building the modified street light for the most part even if i did do a bit of soldering... Basic street light that was modded extensively..Turned out very clean and is used as a recruitment tool now

That compiler is damn quirky though.. You literally had to hook shit up to the circuit board in a strict sequence or you had to reboot.. Took me alot of trial and error to nail the sequence down. I got so sick of rebooting..  Had to reboot because if the sequence wasn't just right.. it would refuse to recognize the port I needed to use..  i.e.  wouldn't turn on the lights.. Anyone that has ever used PIC MicroChip PicDemo 3 board knows what I mean..

As I said... I don't do C/C++ that much anymore though.. Mainly I do Visual basic 2008 which I love. I'm much more proficient at VB..


----------



## Maelstrom (Feb 23, 2011)

Yeah, I think my father taught himself VB recently and is writing an options trading program to work along with excel. 

As for my program, I now have it solving determinants of an an nxn matrix (I have tested a 4x4 and a 5x5, it calculated the right answer for both). All I can say is, yay for recursion!


----------

