Getting set up

Learning to program is hard enough, but it's easy to get tripped up before you even begin. First you need to chose a programming language (I recommend C++), then You need a compiler and a programming tutorial that covers the language you chose and that works with the compiler that you set up. This is all very complicated, and all before you even start to get to the fun parts. 

If you're still struggling with getting the initial setup, then check out our page on setting up a compiler and development environment (Code::Blocks and MINGW) which walks you through setting up a compiler with a lot of screenshots, and gets you up to the point of having an actual running program.

Thinking Like a Programmer

Have you seen the State Farm commercials where the car wash company returns the cars to customers with the soap suds still on the car? The company washes the car, but it didn't rinse it. This is a perfect metaphor for computer programs. Computers, like that car wash company, are very very literal. They do exactly, and only, what you tell them to do; they do not understand implicit intentions. The level of detail required can be daunting at first because it requires thinking through every single step of the process, making sure that no steps are missing. 
This can make programming seem to be a tough slog at first, but don't despair. Not everything must be specified--only what is not something the computer can already do. The header files and libraries that come with your compiler (for example, the iostream header file that allows you to interact with the user) provide a lot of pre-existing functionality. You can use websites like http://www.cppreference.com or our own function reference to find information on these pre-existing libraries of functionality. By using these, you can focus on precisely specifying only what is unique about your program. And even once you do that, you will begin to see patterns that can be turned into functions that wrap up a bunch of steps into a single function that you can call from everywhere. Suddenly complex problems will begin to look simple. It's the difference between:
Walk forward ten feet
Move your hand to the wall
Move your hand to the right until you hit an obstacle
...
Press upward on indentation
and
Walk to door
Find light switch
Turn on light
The magic thing about programming is that you can box up a complex behavior into a simple subroutine (often, into a function) that you can reuse. Sometimes it's hard to get the subroutine done up just right at first, but once you've got it, you no longer need to worry about it. 

You can go here to read more about how to think about programming, written for beginners.

Compiler Error Messages

This may seem like a small thing, but because most beginners aren't familiar with the strictness of the format of the program (the syntax), beginners tend to run into lots of complaints generated by the compiler. Compiler errors are notoriously cryptic and verbose, and by no means were written with newbies in mind. 

That said, there are a few basic principles you can use to navigate the thicket of messages. First, often times a single error causes the compiler to get so confused that it generates dozens of messages--always start with the first error message. Second, the line number is a lie. Well, maybe not a lie, but you can't trust it completely. The compiler complains when it first realizes there is a problem, not at the point where the problem actually occurred. However, the line number does indicate the last possible line where the error could have occurred--the real error may be earlier, but it will never be later. 

Finally, have hope! You'll eventually get really really good at figuring out what the compiler actually means. There will be a few error messages that today seem completely cryptic, even once you know what the real problem was, that in a few months time you will know like an old (if confused) friend. I've actually written more about this in the past; if you want more detailed help, check out my article on deciphering compiler and linker errors.

Debugging

Debugging is a critical skill, but most people aren't born with a mastery of it. Debugging is hard for a few reasons; first, it's frustrating. You just wrote a bunch of code, and it doesn't work even though you're pretty sure it should. Damn! Second, it can be tedious; debugging often requires a lot of effort to narrow in on the problem, and until you have some practice, it can be hard to efficiently narrow it down. One type of problem, segmentation faults, are a particularly good example of this--many programmers try to narrow in on the problem by adding in print statements to show how far the program gets before crashing, even though the debugger can tell them exactly where the problem occurred. Which actually leads to the last problem--debuggers are yet another confused, difficult to set up tool, just like the compiler. If all you want is your program to work, the last thing you want to do is go set up ANOTHER tool just to find out why. 

To learn more about debugging techniques, check out this article on debugging strategies.

Designing a Program

When you're just starting to program, design is a real challenge. Knowing how to think about programming is one piece, but the other piece is knowing how to put programs together in a way that makes it easy to modify them later. Ideas like "commenting your code", "encapsulation and data hiding" and "inheritance" don't really mean anything when you haven't felt the pain of not having them. The problem is that program design is all about making things easier for your future self--sort of like eating your vegetables. Bad designs make your program inflexible to future changes, or impossible to understand after you've written. Frequently, bad design exposes too many details of how something is implemented, so that every part of the program has to know all the details of each other section of the program. 

One great example is writing a checkers game. You need some way to represent the board--so you pick one. A fixed-sized global array: int checkers_board[8][8]. Your accesses to the board all go directly through the array: checkers_board[x][y] = ....; Is there anything wrong with this approach? You betcha. Notice that I wrote your accesses to the board all go directly through the array. The board is the conceptual entity--the thing you care about. The array happens to be, at this particular moment, how you implement the board. Again, two things: the thing you represent, and the way you represent it. By making all accesses to the board use the array directly, you entangle the two concepts. What happens when you decide to change the way you represent the board? You have an awful lot of code to change. But what's the solution? 

If you create a function that performs the types of basic operations you perform on the checkers board (perhaps a get_piece_on_square() method and a set_piece_to_square() method), every access to the board can go through this interface. If you change the implementation, the interface is the same. And that's what people mean when they talk about "encapsulation" and "data hiding". Many aspects of program design, such as inheritance, are there to allow you to hide the details of an implementation (the array) of a particular interface or concept (the board). 

Now go eat your spinach! :) 

A good follow-up to learn more about these issues is to read about programming design and style

For a more advanced article on this topic, you can go here and read about object oriented class design

Another way to make your program more easily modified in the future is to clearly comment it. 

8 Common Programming Mistakes

1. Undeclared Variables

int main()
{
  cin>>x;
  cout<<x;
}
"Huh? Why do I get an error?" 

Your compiler doesn't know what x means. You need to declare it as a variable.
int main()
{
  int x;
  cin>>x;
  cout<<x;
}

2. Uninitialized variables

int count;
while(count<100)
{
  cout<<count;
  count++;
}
"Why doesn't my program enter the while loop?" 

In C++ variables are not initialized to zero. In the above snippet of code, count could be any value in the range of int. It might, for example, be 586, and in that situation the while loop's condition would never be true. Perhaps the output of the program would be to print the numbers from -1000 to 99. In that case, once again, the variable was assigned a memory location with garbage data that happened to evaluate to -1000. 

Remember to initialize your variables.

3. Setting a variable to an uninitialized value

int a, b;
int sum=a+b;
cout<<"Enter two numbers to add: ";
cin>>a;
cin>>b;
cout<<"The sum is: "<<sum;
When Run:
Enter two numbers to add: 1 3
The sum is: -1393
"What's wrong with my program?" 

Often beginning programmers believe that variables work like equations - if you assign a variable to equal the result of an operation on several other variables that whenever those variables change (a and b in this example), the value of the variable will change. In C++ assignment does not work this way: it's a one shot deal. Once you assign a value to a variable, it's that value until you reassign the values. In the example program, because a and b are not initialized, sum will equal an unknown random number, no matter what the user inputs. 

To fix this error, move the addition step after the input line.
int a, b;
int sum;
cout<<"Enter two numbers to add: ";
cin>>b;
cin>>a;
sum=a+b;
cout<<"The sum is: "<<sum;

4. Using a single equal sign to check equality

char x='Y';
while(x='Y')
{
  //...
  cout<<"Continue? (Y/N)";
  cin>>x;
}
"Why doesn't my loop ever end?" 

If you use a single equal sign to check equality, your program will instead assign the value on the right side of the expression to the variable on the left hand side, and the result of this statement is the value assigned. In this case, the value is 'Y', which is treated as true. Therefore, the loop will never end. Use == to check for equality; furthermore, to avoid accidental assignment, put variables on the right hand side of the expression and you'll get a compiler error if you accidentally use a single equal sign as you can't assign a value to something that isn't a variable.
char x='Y';
while('Y'==x)
{
  //...
  cout<<"Continue? (Y/N)";
  cin>>x;
}

5. Undeclared Functions

int main()
{
  menu();
}
void menu()
{
  //...
}
"Why do I get an error about menu being unknown?" 

The compiler doesn't know what menu() stands for until you've told it, and if you wait until after using it to tell it that there's a function named menu, it will get confused. Always remember to put either a prototype for the function or the entire definition of the function above the first time you use the function.
void menu();
int main()
{
  menu();
}
void menu()
{
  ...
}

6. Extra Semicolons

int x;
for(x=0; x<100; x++);
  cout<<x;
"Why does it output 100?" 

You put in an extra semicolon. Remember, semicolons don't go after if statements, loops, or function definitions. If you put one in any of those places, your program will function improperly.
int x;
for(x=0; x<100; x++)
  cout<<x;

7. Overstepping array boundaries

int array[10];
//...
for(int x=1; x<=10; x++)
  cout<<array[x];
"Why doesn't it output the correct values?" 

Arrays begin indexing at 0; they end indexing at length-1. For example, if you have a ten element array, the first element is at position zero and the last element is at position 9.
int array[10];
//...
for(int x=0; x<10; x++)
  cout<<array[x];

8. Misusing the && and || operators

int value;
do
{
  //...
  value=10;
}while(!(value==10) || !(value==20))
"Huh? Even though value is 10 the program loops. Why?" 

Consider the only time the while loop condition could be false: both value==10 and value==20 would have to be true so that the negation of each would be false in order to make the || operation return false. In fact, the statement given above is a tautology; it is always true that value is not equal to 10 or not equal to 20 as it can't be both values at once. Yet, if the intention is for the program only to loop if value has neither the value of ten nor the value of 20, it is necessary to use && : !(value==10) && !(value==20), which reads much more nicely: "if value is not equal to 10 and value is not equal to 20", which means if value is some number other than ten or twenty (and therein is the mistake the programmer makes - he reads that it is when it is "this" or "that", when he forgets that the "other than" applies to the entire statement "ten or twenty" and not to the two terms - "ten", "twenty" - individually). A quick bit of boolean algebra will help you immensely: !(A || B) is the equivalent of !A && !B (Try it and see; you can read more about this rule on Wikipedia:DeMorgan's Law). The sentence "value is other than [ten or twenty]" (brackets added to show grouping) is translatable to !(value==10 || value==20), and when you distribute the !, it becomes !(value==10) && !(value==20). 

The proper way to rewrite the program:
int value;
do
{
  //...
  value=10;
}while(!(value==10) && !(value==20))


By Ubaid sardar

Foreword to Same Game

In this five part series, we'll be creating a version of a game called SameGame using the Microsoft Foundation Class library from start to finish. We'll include features beyond the simple removing of blocks in the game. We'll implement an undo/redo subsystem and some user configuration dialogs. We'll show you step by step with not only source code but screenshots how to build a fun game from start to finish and how to use Microsoft's MFC classes. Every article comes with complete source code, so you can build and run the game yourself.
The rules to the SameGame are quite simple, you try to remove all of the colored blocks from the playing field. In order to remove a block the player must click on any block that is next to, vertically or horizontally, another with the same color. When this happens all of the blocks of that color that are adjacent to the clicked block are removed. All of the blocks above the ones removed then fall down to take their place. When an entire column is removed, all columns to the right are shifted to the left to fill that space. The blocks aren't shifted individually but as a column. The game is over when there are no more valid moves remaining. The goal is to end with an empty board in as little time as possible. Some versions of the SameGame use a scoring algorithm that can be implemented as an additional exercise for the user.

Prerequisites

You'll need to have a basic C++ knowledge of functionsrecursionclasses, and inheritance. The code was written usingVisual Studio 2005 on Windows XP although later versions of Visual Studio should be fine although the screenshots will look slightly different from what you will see. You must use the Standard or Professional edition of Visual Studio; Visual Studio Express cannot be used, because it does not come with MFC.
If you are student, you may be able to get the Professional Version of Visual Studio for FREE from Microsoft DreamSpark.
If you are not a student, and you do not have the full version of Visual Studio, can work through this tutorial using a trial version of Visual Studio.

What You'll Learn

First and foremost, you'll learn some basics of how to create your own game. You'll learn about the Microsoft Foundation Class library and some basic usage and the Document/View architecture paradigm.
Here's an outline of the series, with links to each article:

Why MFC?

MFC is an easy-to-use library, especially for a simple game like the one we want to make. It will make it easy to create an application with a true Windows look-and-feel.

Starting the Same Game Project

In this article we'll be using Visual Studio 2005 to create our game. The following instructions can easily be adapted to all other versions of Visual Studio. First start up Visual Studio and create a new project. The type of project is "Visual C++" -> "MFC" -> "MFC Application".
Next the MFC application wizard will appear. If you do not choose the name SameGame, then the names of your classes will be slightly different than those that appear in this article. This allows you to select quite a few options that the resulting generated code will include. For our simple game we can disable quite a few of these options. The following graphics show which options to select in order to get the project just the way we want it.
Selecting "Single document" allows the application to use the document/view architecture when multiple documents aren't necessary. The last setting of interest on this page is "Use of MFC". The two options are for a shared DLL or as a static library. Using a DLL means that your users must have the MFC DLLs installed on their computer, which most computers do. The static library option links the MFC library right into your application. The executable that is produced will be larger in size but will work on any Windows machine.
Advance through the next three pages, taking the defaults until the following page is displayed.
(If you are using Visual 2010, this screen does not have a "None" option for Toolbars. Just choose "Use a Classic Menu" without checking either toolbar.) A thick frame allows the user to resize the window. Since our game is a static size, un-check this option. A maximize box isn't needed, nor is a status bar or a toolbar. Advancing to the next page will bring you to the "Advanced Features" page.
Turn off printing, ActiveX controls and set the number of recent files to zero. Since we won't actually be loading any files, this option won't be necessary. The last page of the MFC Application Wizard presents you with a list of generated classes.
Four classes that will be generated for you are the basis for the game. The first on the list is the view class, here it is called CSameGameView. I will come back to this class in a minute. The next class in the list is the application class. This class is a wrapper for the entire application and a main function is provided for your application by this class. The base class isn't selectable and must be CWinApp.
The next class in the list is the document class, CSameGameDoc based on the CDocument class. The document class is where all of the application data is stored. Again the base class cannot be changed.
The last class is the CMainFrame class. This CFrameWnd based class is the wrapper class for the actual window. The main frame class contains the menu and the client area view. The client area is where the actual game will be drawn.
Now back to the view class. The base class is a dropdown with a list of views that are generally available, each with its own use and application. The default view type is CView, which is a generic view where all of the display and interaction with the user must be done manually. This is the one that we want to select.
I will quickly go down the list and explain what each view type is used for, just for your information. The CEditView is a generic view which consists of a simple text box. The CFormView allows the developer to insert other common controls into it, i.e. edit boxes, combo boxes, buttons, etc. The CHtmlEditView has an HTML editor built into the view. The CHtmlView embeds the Internet Explorer browser control into the view. The CListView has an area similar to an Explorer window with lists and icons. The CRichEditView is similar to WordPad; it allows text entry but also text formatting, colors and stuff like that. A CScrollView is a generic view similar to CView but allows scrolling. Finally the CTreeView embeds a tree control into the view.
Finishing the MFC Application Wizard will produce a running MFC application. Since we haven't written any code yet it is a very generic window with nothing in it, but it is a fully functioning application all the same. Below is a screenshot of what your generic application ought to look like. To build your application, you can go to the Debug menu, and select Start without Debugging. Visual Studio may prompt you to rebuild the project—select "Yes".
Notice it has a default menu (File, Edit and Help) and an empty client area. Before we get to actual coding I'd like to explain a little about the document/view architecture that is used in MFC applications and how we are going to apply it to our game.


1. Look at the Example Code

Reading is usually about the words on the page, but learning to program is about code. When you're first learning to program, you should make sure to look at, and try to understand, every example. When I first learned to program, I would sometimes read the code examples before the text, and try to figure out what they did. It doesn't always work, but it did force me to look at the example very carefully, and it often helped make the writeups clearer. 

If you want to see what sample code looks like, you can read this site's introductory programming tutorial. This tutorial spends a great deal of time talking about the sample code to help you work through exactly what the code does.

2. Don't Just Read Example Code--Run It

But when you're reading a programming tutorial (or book), it's easy to look at the sample code and say "I get it, I get it, that makes sense". Of course, you might get it, but you might not get it, and you just don't know it. There's only one way to find out--do something with that code. 

If you haven't already, get a compiler like Code::Blocks set up. 

Then type the sample code into a compiler--if you type it, instead of copying and pasting it, you will really force yourself to go through everything that is there. Typing the code will force you to pay attention to the details of the syntax of the language--things like those funny semicolons that seem to go after every line. 

Then compile it and run it. Make sure it does what you think it does. 

Then change it. Software is the most easily changed machinery on the planet. You can experiment easily, try new things, see what happens; the changes will happen almost immediately, and there is no risk of death or mayhem. The easiest way to learn new language features is to take some code that works one way, and change it.

3. Write your Own Code as Soon as Possible

Once you understand something about the language--or even if you're still getting your head around it--start writing sample programs that use it. Sometimes it's hard to find good ideas for what programs to write. That's OK, you don't have to come up with every idea at the beginning. 

You can find some programming challenges on this site. 

You can also reimplement the examples from the book or tutorial you are reading. Try to do so without looking back at the sample code; it won't be as easy as it seems. This technique can work especially well if you tweak the sample code. 

If you can't think of a small program to write, but you have in mind a larger program you want to implement, like a game, you could start building small pieces that you can later use for a game. Whether you use them later or not, you will get the same useful experience.

4. Learn to Use a Debugger

I already talked about the importance of debugging in The 5 Most Common Problems New Programmers Face--And How You Can Solve Them. But it bears repeating; the sooner you learn good debugging techniques, easier it will be to learn to program. 

The first step in doing so is to learn how to use a tool called a debugger, which allows you to step through your code. 

A debugger will allow you to step line by line through a piece of code. It will let you see the values of variables, and whether the code inside an if statement is executed. 

A debugger can help you quickly answer questions about what your code is doing.
int main()
{
        int x;
        int y;
        if( x > 4 )  // <-- what is the value of x here?
        {
                y = 5;   // <-- did this line of code execute?
        }
}


A final word about debuggers: the first time you learn about a debugger, it will take you longer to fix the problems with your code. After the tenth or so bug, it will really start to pay off. And believe me, you will have way more than ten bugs in your programming career. 

I often saw students unwilling to use a debugger. These students really made life hard on themselves, taking ages to find very simple bugs. The sooner you learn to use a debugger, the sooner it will pay off.

5. Seek out More Sources

If you don't understand something, there's a good possibility the way it was explained just didn't click. 

First, look for alternative explanations. The internet is filled with information about programming, and some explanations work better for different people; you might need pictures, someone else might not. There are also lots of good books with detailed explanations. 

But if that doesn't work, the easiest way to figure out where your misunderstanding lies is to ask someone else. But try to go beyond saying, "I don't understand. Please explain." You're likely to get a link back to the same text you didn't understand. Instead, rephrase your understanding of the text in your words. The more your question reveals about what you are thinking, the easier it will be for a knowledgeable expert to answer it. Programmers sometimes have a reputation for being grumpy about answering questions, but I think the reason is that they want to make progress in a conversation, and that requires both sides to put in effort. If you ask a smart, detailed question that shows you are thinking, you will generally get good results. 

There are plenty of places you can go to ask questions. You can always email me
Information technology (IT) is the application of computers and internet to store, retrieve, transmit, and manipulate data,[1] or an information often in the context of a business or other enterprise.[2] IT is considered a subset ofinformation and communications technology (ICT). In 2012, Zuppo proposed an ICT hierarchy where each hierarchy level "contain some degree of commonality in that they are related to technologies that facilitate the transfer of information and various types of electronically mediated communications."[3]Business/IT was one level of the ICT hierarchy.
The term is commonly used as a synonym for computers and computer networks, but it also encompasses other information distribution technologies such as television and telephones. Several industries are associated with information technology, including computer hardwaresoftwareelectronics,semiconductorsinternettelecom equipmentengineeringhealthcaree-commerce, and computer services.[4][a]
Humans have been storing, retrieving, manipulating, and communicating information since the Sumerians in Mesopotamia developed writing in about 3000 BC,[6] but the term information technology in its modern sense first appeared in a 1958 article published in the Harvard Business Review; authorsHarold J. Leavitt and Thomas L. Whisler commented that "the new technology does not yet have a single established name. We shall call it information technology (IT)." Their definition consists of three categories: techniques for processing, the application of statistical and mathematical methods to decision-making, and the simulation of higher-order thinking through computer programs.[7]
Based on the storage and processing technologies employed, it is possible to distinguish four distinct phases of IT development: pre-mechanical (3000 BC – 1450 AD), mechanical (1450–1840), electromechanical (1840–1940), electronic (1940–present),[6] and moreover, IT as a service. This article focuses on the most recent period (electronic), which began in about 1940.