Sunday, July 31, 2016

A step-by-step guide to becoming a C++ programmer...

Want to learn to code? Want to learn C++? Struggling to follow your lecturer or books and tutorials written for experts?
You're not alone.
As a professional C++ developer and former Harvard teaching fellow, I know what you need to know to be a great C++ programmer, and I know how to teach it, one step at a time. I know where people struggle, and how to overcome it. I cover every step of the programming process, including:
  • Getting the tools you need to program and how to use them
  • Basic language features like variables, loops and functions
  • How to go from an idea to code
  • A clear, understandable explanation of pointers
  • Strings, file IO, arrays, references
  • Classes, object oriented programming, and advanced class design
  • Data structures and the standard template library (STL)

Saturday, July 30, 2016

Code Completion Challenge - Guessing Game Solution

Guessing Game Solution
The following program will act as a guessing game in which the user has eight tries to guess a randomly generated number. The program will tell the user each time whether he guessed high or low:
#include <stdlib.h>
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));    
int number=rand()%100; 
int guess=-1;
int trycount=0;
while(guess!=number && trycount<8)

{
cout<<"Please enter a guess: ";
cin>>guess;

if(guess<number)
cout<<"Too low"<<endl;

if(guess>number)
 cout<<"Too high"<<endl;

trycount++;
}
if(guess==number)
cout<<"You guessed the number";
else
cout<<"Sorry, the number was: "<<number;
return 0;
}

Sunday, July 24, 2016

Setting up Code::Blocks and MINGW, A Free C and C++ Compiler, on Windows

By Thomas Carriero 

This tutorial gives you easy-to-follow instructions, with screenshots, for setting up a compiler (the MINGW compiler), a tool that will let you turn the code that you write into programs, and Code::Blocks, a free development environment for C and C++. This tutorial explains how to install Code::Blocks on Windows 2000, XP, Vista or Windows 7. Note: if you're running Linux, go here to learn how to use GCC; if you're on OS X, go here to get set up using Apple XCode.

Step 1: Download Code::Blocks

  • Go to this website: http://www.codeblocks.org/downloads
  • Follow the link to "Download the binary release" (direct link)
  • Go to the Windows 2000 / XP / Vista / 7 section
  • Look for the file that includes mingw in the name. (The name as of this writing was codeblocks-10.05mingw-setup.exe; the 10.05 may be different).
  • Save the file to your desktop. It is roughly 74 megabytes.

Step 2: Install Code::Blocks

  • Double click the installer.
  • Hit next several times. Other setup tutorials will assume you have installed in C:\Program Files\CodeBlocks (the default install location), but you may install elsewhere if you like
  • Do a Full Installation
  • Launch Code::Blocks

Step 3: Running in Code::Blocks

You will be prompted with a Compilers auto-detection window: 

Compiler Auto-Detection Window 

When you get the compiler auto-detection window, just hit OK. Code::Blocks may ask if you want to associate it as the default viewer for C/C++ files--I'd suggest you do. Click on the File menu, and under "New", select "Project..." 

The following window will come up: 

New Project Window 

Click on "Console Application" and hit the "Go" button. 

Click next until you get to the Language Selection Dialog: 

Language selection dialog 

You'll be asked to choose whether you want to use C or C++. If you're not sure, use C++. Otherwise, choose based on the language you are learning. (You can find tutorials here on both C and C++.) 

After clicking "Next", Code::Blocks will then prompt you with where you'd like to save the console application: 

Project Name and Location 

I'd recommend you put it in its own folder, as it may create several files (this is especially true if you create other types of projects). You will need to give your project a name, anything will be fine. 

Clicking "Next" again will prompt you to set up your compiler: 

Compiler Setup 

You don't need to do anything here. Just accept the defaults by hitting "Finish". 

You can now open the main.cpp file on the left: 

Main Editor View (You may need to expand the contents of the "Sources" folder if you don't see main.cpp.) 

At this point, you will have your main.cpp file, which you can modify if you like. For now, it just says "Hello World!", so we can run it as is. Hit F9, which will first compile it and then run it. 

Running Program 

You now have a running program! You can simply edit main.cpp and then hit F9 to compile it and run it again. 

Now that you've finished setting your compiler up, it's time to learn to program: Intro to C++ (or if you're learning C, Intro to C).

Troubleshooting

The most common error people see if things don't work is a message like

"CB01 - Debug" uses an invalid compiler. Probably the toolchain path within the compiler options is not setup correctly?! Skipping..."

First, make sure that you downloaded the right version of Code::Blocks, the one that included MinGW. If that doesn't solve the problem, it is likely a problem with compiler auto-detection. Here's how you can check your current "auto-detected" state. Go to "Settings|Compiler and Debugger...". Then on the left, choose "Global Compiler Settings" (it has a gear icon) and on the right, select the "Toolchain executables" tab. This tab has a "Auto-detect" button that you can use. That might fix the problem--if it doesn't, you can manually fill out the form. Here's a screenshot demonstrating what things look like on my system. Change the path marked "Compiler's installation directory" if you installed to a different location, and make sure everything else is filled in as shown.

Once you've done that, try pressing F9 again to see if you get a running program.

Loops

Loops are used to repeat a block of code. Being able to have your program repeatedly execute a block of code is one of the most basic but useful tasks in programming -- many programs or websites that produce extremely complex output (such as a message board) are really only executing a single task many times. (They may be executing a small number of tasks, but in principle, to produce a list of messages only requires repeating the operation of reading in some data and displaying it.) Now, think about what this means: a loop lets you write a very simple statement to produce a significantly greater result simply by repetition.



One Caveat: before going further, you should understand the concept of C++'s true and false, because it will be necessary when working with loops (the conditions are the same as with if statements). There are three types of loops: for, while, and do..while. Each of them has their specific uses. They are all outlined below. 

FOR - for loops are the most useful type. The syntax for a for loop is 

for ( variable initialization; condition; variable update ) {
  Code to execute while the condition is true
}
The variable initialization allows you to either declare a variable and give it a value or give a value to an already existing variable. Second, the condition tells the program that while the conditional expression is true the loop should continue to repeat itself. The variable update section is the easiest way for a for loop to handle changing of the variable. It is possible to do things like x++, x = x + 10, or even x = random ( 5 ), and if you really wanted to, you could call other functions that do nothing to the variable but still have a useful effect on the code. Notice that a semicolon separates each of these sections, that is important. Also note that every single one of the sections may be empty, though the semicolons still have to be there. If the condition is empty, it is evaluated as true and the loop will repeat until something else stops it. 

Example:
#include <iostream>

using namespace std; // So the program can see cout and endl

int main()
{
  // The loop goes while x < 10, and x increases by one every loop
  for ( int x = 0; x < 10; x++ ) {
    // Keep in mind that the loop condition checks 
    //  the conditional statement before it loops again.
    //  consequently, when x equals 10 the loop breaks.
    // x is updated before the condition is checked.    
    cout<< x <<endl;
  }
  cin.get();
}
This program is a very simple example of a for loop. x is set to zero, while x is less than 10 it calls cout<< x <<endl; and it adds 1 to x until the condition is met. Keep in mind also that the variable is incremented after the code in the loop is run for the first time. 

WHILE - WHILE loops are very simple. The basic structure is 

while ( condition ) { Code to execute while the condition is true } The true represents a boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). It can be any combination of boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the code while x equals five or while v equals 7. Notice that a while loop is the same as a for loop without the initialization and update sections. However, an empty condition is not legal for a while loop as it is with a for loop. 

Example:
#include <iostream>

using namespace std; // So we can see cout and endl

int main()
{ 
  int x = 0;  // Don't forget to declare variables
  
  while ( x < 10 ) { // While x is less than 10 
    cout<< x <<endl;
    x++;             // Update x so the condition can be met eventually
  }
  cin.get();
}
This was another simple example, but it is longer than the above FOR loop. The easiest way to think of the loop is that when it reaches the brace at the end it jumps back up to the beginning of the loop, which checks the condition again and decides whether to repeat the block another time, or stop and move to the next statement after the block. 

DO..WHILE - DO..WHILE loops are useful for things that want to loop at least once. The structure is
do {
} while ( condition );
Notice that the condition is tested at the end of the block instead of the beginning, so the block will be executed at least once. If the condition is true, we jump back to the beginning of the block and execute it again. A do..while loop is basically a reversed while loop. A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and loop while the condition is true". 

Example:
#include <iostream>

using namespace std;

int main()
{
  int x;

  x = 0;
  do {
    // "Hello, world!" is printed at least one time
    //  even though the condition is false
    cout<<"Hello, world!\n";
  } while ( x != 0 );
  cin.get();
}
Keep in mind that you must include a trailing semi-colon after the while in the above example. A common error is to forget that a do..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, adding to the confusion). Notice that this loop will execute once, because it automatically executes before checking the condition. 

Saturday, July 16, 2016

Character Input and Output

Unless a program can read some input, it's hard to keep it from doing exactly the same thing every time it's run, and thus being rather boring after a while.
The most basic way of reading input is by calling the function getchargetchar reads one character from the ``standard input,'' which is usually the user's keyboard, but which can sometimes be redirected by the operating system. getchar returns (rather obviously) the character it reads, or, if there are no more characters available, the special value EOF (``end of file'').
A companion function is putchar, which writes one character to the ``standard output.'' (The standard output is, again not surprisingly, usually the user's screen, although it, too, can be redirected. printf, likeputchar, prints to the standard output; in fact, you can imagine that printf calls putchar to actually print each of the characters it formats.)
Using these two functions, we can write a very basic program to copy the input, a character at a time, to the output:
#include <stdio.h>

/* copy input to output */

main()
{
 int c;

 c = getchar();

 while(c != EOF)
  {
  putchar(c);
  c = getchar();
  }

 return 0;
}

This code is straightforward, and I encourage you to type it in and try it out. It reads one character, and if it is not the EOF code, enters a while loop, printing one character and reading another, as long as the character read is not EOF. This is a straightforward loop, although there's one mystery surrounding the declaration of the variable c: if it holds characters, why is it an int?
We said that a char variable could hold integers corresponding to character set values, and that an int could hold integers of more arbitrary values (up to +-32767). Since most character sets contain a few hundred characters (nowhere near 32767), an int variable can in general comfortably hold all char values, and then some. Therefore, there's nothing wrong with declaring c as an int. But in fact, it's important to do so, because getchar can return every character value, plus that special, non-character value EOF, indicating that there are no more characters. Type char is only guaranteed to be able to hold all the character values; it is not guaranteed to be able to hold this ``no more characters'' value without possibly mixing it up with some actual character value. (It's like trying to cram five pounds of books into a four-pound box, or 13 eggs into a carton that holds a dozen.) Therefore, you should always remember to use an int for anything you assign getchar's return value to.
When you run the character copying program, and it begins copying its input (your typing) to its output (your screen), you may find yourself wondering how to stop it. It stops when it receives end-of-file (EOF), but how do you send EOF? The answer depends on what kind of computer you're using. On Unix and Unix-related systems, it's almost always control-D. On MS-DOS machines, it's control-Z followed by the RETURN key. Under Think C on the Macintosh, it's control-D, just like Unix. On other systems, you may have to do some research to learn how to send EOF.
(Note, too, that the character you type to generate an end-of-file condition from the keyboard is not the same as the special EOF value returned by getchar. The EOF value returned by getchar is a code indicating that the input system has detected an end-of-file condition, whether it's reading the keyboard or a file or a magnetic tape or a network connection or anything else. In a disk file, at least, there is not likely to be any character in the file corresponding to EOF; as far as your program is concerned, EOF indicates the absence of any more characters to read.)
Another excellent thing to know when doing any kind of programming is how to terminate a runaway program. If a program is running forever waiting for input, you can usually stop it by sending it an end-of-file, as above, but if it's running forever not waiting for something, you'll have to take more drastic measures. Under Unix, control-C (or, occasionally, the DELETE key) will terminate the current program, almost no matter what. Under MS-DOS, control-C or control-BREAK will sometimes terminate the current program, but by default MS-DOS only checks for control-C when it's looking for input, so an infinite loop can be unkillable. There's a DOS command,
 break on
which tells DOS to look for control-C more often, and I recommend using this command if you're doing any programming. (If a program is in a really tight infinite loop under MS-DOS, there can be no way of killing it short of rebooting.) On the Mac, try command-period or command-option-ESCAPE.

Finally, don't be disappointed (as I was) the first time you run the character copying program. You'll type a character, and see it on the screen right away, and assume it's your program working, but it's only your computer echoing every key you type, as it always does. When you hit RETURN, a full line of characters is made available to your program. It then zips several times through its loop, reading and printing all the characters in the line in quick succession. In other words, when you run this program, it will probably seem to copy the input a line at a time, rather than a character at a time. You may wonder how a program could instead read a character right away, without waiting for the user to hit RETURN. That's an excellent question, but unfortunately the answer is rather complicated, and beyond the scope of our discussion here. (Among other things, how to read a character right away is one of the things that's not defined by the C language, and it's not defined by any of the standard library functions, either. How to do it depends on which operating system you're using.)
Stylistically, the character-copying program above can be said to have one minor flaw: it contains two calls to getchar, one which reads the first character and one which reads (by virtue of the fact that it's in the body of the loop) all the other characters. This seems inelegant and perhaps unnecessary, and it can also be risky: if there were more things going on within the loop, and if we ever changed the way we read characters, it would be easy to change one of the getchar calls but forget to change the other one. Is there a way to rewrite the loop so that there is only one call to getchar, responsible for reading all the characters? Is there a way to read a character, test it for EOF, and assign it to the variable c, all at the same time?
There is. It relies on the fact that the assignment operator, =, is just another operator in C. An assignment is not (necessarily) a standalone statement; it is an expression, and it has a value (the value that's assigned to the variable on the left-hand side), and it can therefore participate in a larger, surrounding expression. Therefore, most C programmers would write the character-copying loop like this:
 while((c = getchar()) != EOF)
  putchar(c);
What does this mean? The function getchar is called, as before, and its return value is assigned to the variable c. Then the value is immediately compared against the value EOF. Finally, the true/false value of the comparison controls the while loop: as long as the value is not EOF, the loop continues executing, but as soon as an EOF is received, no more trips through the loop are taken, and it exits. The net result is that the call to getchar happens inside the test at the top of the while loop, and doesn't have to be repeated before the loop and within the loop (more on this in a bit).

Stated another way, the syntax of a while loop is always
 while( expression ) ...
A comparison (using the != operator) is of course an expression; the syntax is
 expression != expression
And an assignment is an expression; the syntax is
 expression = expression
What we're seeing is just another example of the fact that expressions can be combined with essentially limitless generality and therefore infinite variety. The left-hand side of the != operator (its firstexpression) is the (sub)expression c = getchar(), and the combined expression is the expression needed by the while loop.

The extra parentheses around
 (c = getchar())
are important, and are there because because the precedence of the != operator is higher than that of the = operator. If we (incorrectly) wrote
 while(c = getchar() != EOF)  /* WRONG */
the compiler would interpret it as
 while(c = (getchar() != EOF))
That is, it would assign the result of the != operator to the variable c, which is not what we want.

(``Precedence'' refers to the rules for which operators are applied to their operands in which order, that is, to the rules controlling the default grouping of expressions and subexpressions. For example, the multiplication operator * has higher precedence than the addition operator +, which means that the expression a + b * c is parsed as a + (b * c). We'll have more to say about precedence later.)
The line
 while((c = getchar()) != EOF)
epitomizes the cryptic brevity which C is notorious for. You may find this terseness infuriating (and you're not alone!), and it can certainly be carried too far, but bear with me for a moment while I defend it.

The simple example we've been discussing illustrates the tradeoffs well. We have four things to do:
  1. call getchar,
  2. assign its return value to a variable,
  3. test the return value against EOF, and
  4. process the character (in this case, print it out again).
We can't eliminate any of these steps. We have to assign getchar's value to a variable (we can't just use it directly) because we have to do two different things with it (test, and print). Therefore, compressing the assignment and test into the same line is the only good way of avoiding two distinct calls to getchar. You may not agree that the compressed idiom is better for being more compact or easier to read, but the fact that there is now only one call to getchar is a real virtue.

Don't think that you'll have to write compressed lines like
 while((c = getchar()) != EOF)
right away, or in order to be an ``expert C programmer.'' But, for better or worse, most experienced C programmers do like to use these idioms (whether they're justified or not), so you'll need to be able to at least recognize and understand them when you're reading other peoples' code.