Code Sample World

June 10, 2009

5 Ways You can Learn Programming Faster

Filed under: code project — admin @ 2:38 am

5 Ways You can Learn Programming Faster

by Alex Allain

Learning to program isn’t something you can do in an afternoon, but it doesn’t
have to be a life’s work, either. There are
lots of things you can do to make it easier on yourself when you are learning
to program. You already know about
The 5 Most Common Problems New Programmers Face–And How You Can Solve
Them
. Now, discover how to get the most out of your learning.

One common theme across many of these tips is:

don’t go too
fast; get it right before moving on
.

When I was teaching C, there were always a few students who came into the class
knowing a bit about programming. Inevitably, some of these students did great
in the first few weeks only to fall further and further behind as the course
went on. Why? They went too fast through the introductory part of the course,
thinking they knew it all–but they rarely did. They knew some of the
material, but not enough to have a strong grasp of the fundamentals.

At the same time, you must not stop making progress–you can go too slow as
well as too fast. Don’t avoid a topic after you’ve mastered everything leading
up to it. By facing more challenging ideas, you’ll help cement your grasp of
the basics.

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 possiblity 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, or post on our message board, or ask an expert.

In the coming days, I’ll be writing more about how to learn to program
effectively. Stay tuned, by subscribing to our RSS
feed
,
signing up for email
notifications
, or following @alexallain on twitter.

Bookmark and Share

src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png"
alt="subscribe to a feed">

Subscribe to
Cprogramming.com


Related Articles

The
5 Most Common Problems New Programmers Face–And How You Can Solve
Them

Common
Programming Mistakes–And How to Solve Them

How
to Avoid Getting Lost When Writing Programs, or, The Power of
Incremental Development

How to
Think About Programming, A Beginner’s Guide

—–

Subscribe
to cprogramming.com by Email

Interested in advertising

with us?

Please read our privacy

policy.

Copyright © 1997-2009

Cprogramming.com. All rights reserved.

How can Cprogramming.com Better Help You?

Filed under: code project — admin @ 2:38 am

The 5 Most Common Problems New Programmers Face–And How You Can Solve Them

Filed under: code project — admin @ 2:38 am

The 5 Most Common Problems New Programmers Face–And How You Can Solve
Them

by Alex Allain

When you’re just starting out with programming, it’s easy to run into problems
that make you wonder how anyone has ever managed to write a computer program.
But the fact is, just about everyone else who’s learned to code has had that
experience and wondered the same thing, when they were starting out. I’ve helped teach several introductory programming classes, and there are some
problems that trip up nearly every student–everything from getting started to
dealing with program design.

I’ll prepare you to get past these challenges–none of them are insurmountable.

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 alreay 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
“, “encapulation 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 throug 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.

I’ll be writing more on learning to program in the next few days, so stay tuned using our
RSS feed
,
subscribing
to cprogramming.com by email
, or following @alexallain on twitter.

Bookmark and Share

src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png"
alt="subscribe to a feed">

Subscribe to
Cprogramming.com


Related Articles

5
Ways You can Learn Programming Faster

Common
Program Mistakes–And How to Solve Them

How
to Avoid Getting Lost When Writing Programs, or, The Power of
Incremental Development

How to
Think About Programming, A Beginner’s Guide

—–

Subscribe
to cprogramming.com by Email

Interested in advertising

with us?

Please read our privacy

policy.

Copyright © 1997-2009

Cprogramming.com. All rights reserved.

5 Awesome (and time saving) Features of the Visual Studio Debugger

Filed under: code project — admin @ 2:38 am

5 Awesome Visual Studio Debugger Features

By: Alex Allain

So you know all the basic debugger features: breakpoints, stepping through the
code, viewing
the values of variables
. But there’s a lot more your debugger
can do to make it quicker to step through code, easier to test alternate
solutions, and even avoid rerunning the program.

Here, you’ll learn about some of Visual Studio’s more advanced debugger
features, such as stepping out of a function, taking advantage of the autos
window
, using run to the cursor to set temporary breakpoints, modifying
a variable’s value
to test potential fixes, and using Set Next
Statement
to turn back the clock and re-execute code.

Sample (Buggy) Code

Each of the following examples use this code, which contains several bugs:

#include <vector>
#include <iostream>

class Data
{
public:
	Data ()
	{
		_values.push_back( 1 );
		_values.push_back( 2 );
	}
	int getSum()
	{
		int total;
		for ( std::vector<int>::iterator itr = _values.begin(), end = _values.end(); itr != end; ++itr )
		{
			total += *itr;
		}
		return total;
	}
	int getCount() { return _values.size(); }
private:
	std::vector<int> _values;
};

double compute_average( int sum, int count )
{
	return sum / count;
}

int main()
{
	Data d;

	std::cout << compute_average( d.getSum(), d.getCount() ) << std::endl;
}

1. Step Out of the Current Function

So you’ve written a function call, like so:

int main()
{
	Data d;

	std::cout << compute_average( d.getSum(), d.getCount() ) << std::endl;
}

And the compute_average function is not returning the correct value. If you
were to use a debugger, and you wanted to step into compute_average, you could,
of course, put a breakpoint inside compute_average, but what if it were called
from several places? Visual Studio has a very convenient feature of its
debugger, that will allow you to step into compute_average very quickly.

Set a breakpoint on that line:



Once the debugger hits it, then step into the function. getSum and getCount
will both be called before compute_average. Normally, you’d keep hitting next
to get out of getSum and getCount, but with Visual Studio, you can quickly hit
Shift-F11 to step out of the current function and return to the next call.



Once you step out of the current function, you’re taken back to the original
breakpoint. But now you can step in again, to got to the next function.
Repeat until you’ve drilled down into the function you want.

When to Use This Trick

Obviously, there are times when it makes more sense to just set a breakpoint in
your target function. But when doing so would require ignoring hundreds of calls to that function to find the one you want,
it might not be worth it. Using
step out provides a quick way of getting into a function without having to find
the function and set a temporary break point (or use run to cursor).

2. Use the Auto Window to See Result of Functions

One of the most frustrating parts of debugging is when you have a function call
whose result isn’t stored anywhere, and you really want to know what it
returned.

Somtimes, programmers write code like this, just to work around the issue:

int computed_avg;

computed_avg = compute_average( d.getSum(), d.getCount() );

std::cout << computed_avg << std::endl;

(Obviously, in this case, the program prints out the value, so all is not lost.
This is rarely true in the general case.)

Fortunately, the autos window has good courtesy to display the result of a
function evaluation:



When to Use this Trick

Whenever you want to see a return value! Note that you the autos window will eventually erase the return value as you execute code, so be sure to check your return value immediately.

Did you know…

Most return values are also stored in the EAX register–you can look in EAX to find the return value, if you need it.

3. Run to Cursor

Run to cursor is a great way of avoiding the
step-step-step-step-step-oh-no-I-stepped-over-it problem, where you know where
you want to be, getting to it requires stepping multiple times, and you get
impatient.

In effect, run-to-cursor is just a shortcut for setting a breakpoint that is
immediately cleared once it’s hit; nevertheless, it’s a very convenient
feature. It is most useful when you have a piece of code that is called
frequently from different places, and you only care about one code path. Then
you can place a breakpoint at the start of that path and use run-to-cursor to
get to the point you really care about.

Going back to our sample program, we can use run-to-cursor rather than the
step-out trick, to get into compute_average. (Of course, we could just put a
breakpoint in compute_average; for the purpose of making this example sensible,
please imagine 15-20 calls to compute_average that all work correctly, taking
place before the broken call.)



When to Use this Trick

Any time you want a throwaway breakpoint or want to avoid single-stepping through a lot of code. Be careful, though, that you run to a part of the code that will actually be executed. Watch out for early returns from a function within a loop, for instance.

4. Modify Any Variable

Now that we’re in the compute_average function, and we know that the value
being returned is waayyy too big, we can check the arguments to the
function. It turns out that sum is very large. We’ll deal with that in a bit.
First, let’s test and make sure that the function works if we do get the right
value.

Obviously, one way of doing this would be to pass in a new value. But Visual
Studio conveniently makes it easy to change any value in memory. In fact,
let’s do that with the value of sum, and make sure that it returns the correct
value.

All you need to do is click on in the Value column of the auto or watch window
and change the value. (You can also do this when the variable’s value pops up
while hovering over a variable in the source code.)



and voila:



Continuing execution of the program demonstrates that, in fact, we still get
the wrong answer–this time, it returns the value 1. This suggests that
truncation is taking place due to integer division.

Before recompiling, we can add in a cast to solve this problem:

return (double) sum / count;

When to Use this Trick

This trick is powerful, and is particularly helpful when you have found one bug, but want to prove that the rest of your code will work. This is particularly handy when your debugging session requires a great deal of setup–for instance, you have to perform a lot of UI to get the right inputs or your code takes a long time to build. (An alternative would be to consider writing a unit test that demonstrates the bug and doesn’t require so much setup.)

On the other hand, you can’t rely on this trick when you are inside a loop or a function that is called frequently–it’s just too much of a pain to have to manually set variables all the time.

5. Set Next Statement

Set Next Statement is a real power tool. If you’re debugging, and you’ve
accidentally (or not so accidentally) stepped past the point where something
interesting happens, you can sometimes “unwind” execution. What this really
means is that, maintaining the current state of the world, you can tell Visual
Studio to go back and start executing from a previous instruction.

You can also use set next statement to jump over code that you believe is
buggy, or to jump past a conditional test on an if statement to execute a path
of code that you want to debug without having to make the condition true.

Setting the next statement can be dangerous and lead to instability if the
stack or registers aren’t in a valid state for the line being executed. And
because it won’t restore the state of the world, if your code depends on that
state, changing the next statement might not be useful. On the other hand, if
you want to make a call that you’re pretty confident won’t behave differently,
it can be a great way of avoiding recreating a specific failure just because
you accidentally stepped too far.

For instance, take the following debugging state, where you’re about to return
the value total from getSum:



If you had accidentally run too far, it might be very convenient to be able to
simply say, ok, let’s start that again:



and then you can go back through executing the loop, perhaps setting the value
of total to 0, since you notice that it wasn’t initialized, and then checking
to see if the program gives the correct sum (in which case, you can be pretty
confident that the lack of initialization was the problem).



When to Use this Trick

Many of the same considerations that apply to resetting variable values also apply here. However, you should also be aware that the further ahead or back in a function you set the next statement, the more likely the debugger will not be able to compensate and your program will crash. I usually use this trick to skip over very small chunks of code, or to go back only to a single previous function call.

src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png"
alt="subscribe to a feed">

Subscribe to
Cprogramming.com

Bookmark and Share

Related articles

Skip Stepping Into Functions
with Visual Studio’s NoStepInto Option
.

Debugging with Visual Studio Part 1: Debugging Concepts

Debugging
with Visual Studio Part 2: Setting up the Debugger

Debugging
with Visual Studio Part 3: Using Breakpoints Effectively

Debugging
with Visual Studio Part 4: Setting up Code for the Debugger

Debugging
with Visual Studio Part 5: Using Trace and Log Messages

Debugging with Visual Studio Part 6: Remote Debugging

—–

Subscribe
to cprogramming.com by Email

Interested in advertising

with us?

Please read our privacy

policy.

Copyright © 1997-2009

Cprogramming.com. All rights reserved.

Debugging with Visual Studio, Part 6: Remote Debugging

Filed under: code project — admin @ 2:38 am

Discover how to debug code running on a one machine from your main development box using remote debugging with Visual Studio



(full text retrieval failed)

Debugging with Visual Studio, Part 5: Using Trace and Log Messages

Filed under: code project — admin @ 2:38 am

Part 5 in a series on debugging with Visual Studio. Discover how to use tracing and logging to make debugging easier.



(full text retrieval failed)

Debugging C and C++ with Visual Studio 2005/2008, Part 4: Setting up Code for the Debugger

Filed under: code project — admin @ 2:38 am

Part 4 in a series on debugging C and C++ in Visual Studio



(full text retrieval failed)

Debugging C++ Using Visual Studio 2005/2008, Part 3: Using Breakpoints Effectively

Filed under: code project — admin @ 2:38 am

Part 3 in a series on debugging with Visual Studio



(full text retrieval failed)

Ask an Expert

Filed under: code project — admin @ 2:37 am

The Ask an Expert hage has been updated with a link to Cprogramming.com’s very own expert grid, featuring experts from our message board community and others!



(full text retrieval failed)

Constructors and Destructors in C++

Filed under: code project — admin @ 2:37 am

Learn about the subtleties of constructors and destructors in C++



(full text retrieval failed)

April 9, 2009

Using Expression Encoder 2 Silverlight 2 Templates in your project

Filed under: code project — admin @ 1:00 am

How to use Expression Encoder 2 Silverlight 2 Templates in your project.

Combinations in C++, Part 2

Filed under: code project — admin @ 1:00 am

Introduce 4 new algorithms on finding combinations

Find which dll / exe created a window.

Filed under: code project — admin @ 1:00 am

The GetWindowModuleFileName() functions can be used to find which exe or dll have created a window. But the problem with this function is that, it will not work across process.When ever we create a window, we have to pass the an HINSTANCE into it. And later we can use GetWindowLong to get that HINST

Hide / Minimize dialog on startup

Filed under: code project — admin @ 1:00 am

Have you ever tried to minimize a dialog during the startup of a dialog based application? The problem is in a dialog based application, we will not get the control after the dialog is completely created. Even a call to ShowWindow() from the OnInitDialog() function, will not work. So what will we do

Nested Generic Lists? Cool!

Filed under: code project — admin @ 1:00 am

While answering a question on the Asp.Net forums, I was pleasantly surprised to find nested Generic Lists are possible. They seem much easier than multidimensional arrays. Here is the key line:     List> MyListOfIntLists;      protected void Button1_Click(object sender, EventArgs e)    {

Visual Form File format

Filed under: code project — admin @ 1:00 am

XAML this, XAML that, blah, blah, blah. I get so sick of hearing about how great XAML is, as if this were the most mind altering, earth shaking technology to hit the streets in years. Bah Humbug!We’ve had something like this for years in the VCF! And the predecessor to XAML dates back even further t

Working with Delegates in Visual Form Files

Filed under: code project — admin @ 1:00 am

How to work with delegates in Visual Form Files.

Advanced Report Viewer

Filed under: code project — admin @ 1:00 am

The article shows how to extend ReportViewer control that comes with Visual Studio 2008. The most important extension is adding export to MS Word.

Convert MAC Address string into Bytes

Filed under: code project — admin @ 1:00 am

The code snip converts MAC Address String Format into Bytes

Create an XSD Schema….without knowing a darn thing about XSD.

Filed under: code project — admin @ 1:00 am

Back in the old days, when dinosaurs roamed the earth, developers wanting to exchange data between applications used binary formatted data, hardcoded text field lengths, or delimited text files. Much parsing and error checking was involved. It was tedious. With XML files a lot of that work can be d

Powered by WordPress