Chapter 3
In This Chapter
Entering your first C++ program
Compiling and executing your program
Examining some things that could go wrong
Executing your program
Reviewing how the program works
This chapter guides you through the creation of your first program in C++, using the Code::Blocks C++ environment. It’s a bit “cookbookish” because I assume this is your first time programming in C++. I explain all the parts that make up this program in subsequent chapters (beginning with Part II), but for now, you’ll be asked to accept a few things on faith. After you’ve had a chance to see it all work together once, all will be revealed — and everything you do in this chapter will make perfect sense.
As always, you must create a new project to house your program. Follow the abbreviated steps here (or you can use the detailed steps from Chapter 2):
If you followed the steps in Chapter 2, the “Folder to create project in” should already be set to Beginning_Programming-CPP. If not, it’s not too late to click the … button and create the folder in the root directory of your working disk. (Chapter 2 describes this process in detail.) The Code::Blocks Wizard fills in the name of the project (and the name of the resulting program) for you.
When you’re done, your window should look like that shown in Figure 3-1.
The next window allows you to change the target folders. You probably won’t need to; the defaults are fine.
Code::Blocks creates a new Project and adds it to the earlier HelloWorld project. (See the upcoming “Organizing projects” section for an explanation of why this happens.) The resulting display should look like Figure 3-2.
Windows has a bad habit of hiding the filename extensions when displaying filenames. For some applications this may be a good idea, but this is almost never a good idea for a programmer. With extensions hidden, Windows may display three or four files with the same name HelloWorld. This confusing state of affairs is easily cleared up when you display file extensions and realize that they’re all different.
After startup, navigate to the View tab of the Folder Options dialog box that appears. Scroll down until you find Hide Extensions for Known File Types; make sure that this box is unchecked. Then choose OK to close the dialog box.
In Windows 8, you can get to the Folder Options directly. From File Explorer, choose the View tab. In the Show/Hide section, click to put a check by File Name Extensions.
Follow these steps to enter the code that creates your first program using C++:
This indicates that it’s the active project. If it isn’t, right-click Conversion and select Activate Project from the drop-down menu.
Alternatively, you can choose which source files to close by clicking the small X next to the name of each file in the editor tab. You don’t want to edit the wrong source file inadvertently.
The drop-down menu reveals the single file main.cpp.
The result is shown in Figure 3-3.
This is definitely the hard part, so take your time and be patient as you enter this code:
//
// Conversion - Program to convert temperature from
// Celsius degrees into Fahrenheit:
// Fahrenheit = Celsius * (212 - 32)/100 + 32
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// enter the temperature in Celsius
int celsius;
cout << "Enter the temperature in Celsius:";
cin >> celsius;
// convert Celsius into Fahrenheit values
int fahrenheit;
fahrenheit = celsius * 9/5 + 32;
// output the results (followed by a NewLine)
cout << "Fahrenheit value is:";
cout << fahrenheit << endl;
// wait until user is ready before terminating program
// to allow the user to see the program results
cout << "Press Enter to continue..." << endl;
cin.ignore(10, '
'),
cin.get();
return 0;
}
What do I mean by “exactly as you see here”? C++ is very picky about syntax. It frowns on missing semicolons or misspelled words. It doesn’t care about extra spaces as long as they don’t appear in the middle of a word. For example int fahren heit; is not the same as int fahrenheit; but int fahrenheit; is okay. C++ treats tabs, spaces, and newlines all the same, referring to them all as whitespace.
Maybe it was just me, but it took me a long time to get used to the fact that C++ differentiates between uppercase and lowercase. Thus int Fahrenheit; is not the same thing as int fahrenheit;.
One final hint: C++ ignores anything that appears after a //, so you don’t have to worry about getting that stuff right.
Now comes the most nerve-wracking part of the entire software development process: building your program. During this step, C++ reviews your handiwork to see if it can make any sense out of what you’ve written.
Programmers are eternal optimists. Somewhere, deep in our hearts, we truly believe that every time we hit the Build button, everything is going to work, but it almost never does. Invariably, a missing semicolon or a misspelled word will disappoint C++ and bring a hail of error messages, like so much criticism from our elementary school teachers, crashing down around our ears.
Actually building the program takes just one step: You select Build⇒Build or press Ctrl+F9 or click the little Build icon.
No offense, but the Build step almost certainly did not come off without error. A Gold Star program is one that works the first time you build and execute it. You’ll almost never write a Gold Star program in your entire programming career. Nobody does. Don’t sweat it.
Fortunately, the Code::Blocks editor is so well integrated with the compiler that it can automatically direct you very close to your errors so you can fix them. Most times, it can place the cursor in the exact row that contains the error. To prove the point, let me take you through a couple of example errors.
Misspelled commands are the easiest errors to identify and correct. To demonstrate the point, I added an extra t to line 14 in the preceding code so that it now reads
intt celsius;
Unlike int, the word intt has no meaning to C++. Building the resulting program generated the display shown in Figure 3-4.
Notice first the small, red block on Line 14 that indicates a problem somewhere on this line. You can read all about it down in the Build Messages tab in the lower-right window. Here you can see the following messages:
In function 'int main(int, char**)':
14 error: 'intt' was not declared in this scope
14 error: expected ';' before 'celsius'
16 error: 'celsius' was not declared in this scope
The first line indicates the name of the function that contains the error. I don’t present functions until Chapter 12, but it’s easy to believe that all of the code in this program is in a function called main. The next line is the key. This says essentially that C++ didn’t understand what intt is on line 14 of the program. The error message is a bit cryptic, but suffice it to say you’ll get this same error message almost every time you misspell something. The remaining error messages are just by-products of the original error.
Another common error is to leave off a semicolon. The message that this error generates can be a little confusing. To demonstrate, I removed the semicolon from the declaration on line 14 so that it reads
int celsius
cout << "Enter the temperature in Celsius:";
The error reported by C++ for this offense points not to line 14 but to the following line, 15:
15 error: expected initialization before 'cout'
16 error: 'celsius' was not declared in this scope
This is easier to understand when you consider that C++ considers newlines as just a another form of whitespace. Without the semicolon, C++ runs the two lines together. There is no separate line 14 anymore. C++ can interpret the first part, but it doesn’t understand the run-on sentence that starts with cout.
If you just can’t get the program entered correctly, you can always copy the program from the online material at www.dummies.com/extras/beginningprogrammingcplusplus.
You have several ways to use the online material. The most straightforward is to copy and paste the contents of the file on the CD into your own as follows:
On a Windows machine, that would probably be C:CPP_Programs.
Code::Blocks opens the file in a new tab in the editor window.
Doing so selects the entire contents of the source file.
This copies the entire file to the Clipboard.
This overwrites the entire contents of the main.cpp that you’ve been working on with the contents of the corresponding file from the download.
You can execute the program once you get a clean compile (that is, 0 errors and 0 warnings) by following these steps:
This will execute the program without the debugger. (Don’t worry if you don’t know what a debugger is; Chapter 20 shows you how to use it.)
The program opens an 80 column by 25 row window and prompts you to enter a temperature in degrees Celsius.
The program immediately responds with the equivalent temperature in Fahrenheit, 212 degrees:
Enter the temperature in Celsius:100
Fahrenheit value is:212
Press Enter to continue …
Even though this is your first program, I didn’t want to leave this chapter without giving you some idea of how this program works.
The first part of the program I call the “Beginning Programming Template.” This is the same magic incantation used for all programs in this book. It goes like this:
//
// ProgramName - short explanation of what the
// program does
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// program goes here
// wait until user is ready before terminating program
// to allow the user to see the program results
cout << "Press Enter to continue..." << endl;
cin.ignore(10, '
'),
cin.get();
return 0;
}
The first few lines in this template appear to be free-form text. Either this “code” was meant for human consumption or the computer is a lot smarter than anyone’s ever given it credit for. These first four lines are known as comments. A comment is a line or portion of a line that is ignored by the C++ compiler. Comments enable the programmer to explain what she was doing or thinking while writing a particular segment of code.
A C++ comment begins with double forward slashes and ends with a newline. You can put any character you want in a comment, and comments can be as long as you like, though it’s customary to limit them to 80 characters or so because that’s what fits within a normal screen width.
Note: You may think it odd to create a command line in C++, or any other programming language, that is specifically ignored by the compiler; yet all programming languages have some form of comment. It’s critical that the programmer be able to explain what was going through her mind when a piece of code was written. It may not be obvious to the next person who picks up the program and uses it or modifies it. In fact, it may not be obvious to the programmer herself after only a few days working on something else.
The next few lines are called include statements because they cause the contents of the named file to be included at that point in the program. Include files always start with the statement #include in column 1 followed by the name of the file to include. (See Chapter 12 for further details.) Just consider them magic for now.
Every program must have a main() somewhere in it. Program execution begins at the open brace immediately following main() and terminates at the return statement immediately prior to the closed brace. An explanation of the exact format of the declaration for main() will have to wait.
Notice that the standard template ends with the statement cin.get()prior to the return 0. This command causes the program to wait for the user to hit the Enter key before the program terminates.
The remainder of the Conversion program, sans the template, appears as follows:
// enter the temperature in Celsius
int celsius;
cout << "Enter the temperature in Celsius:";
cin >> celsius;
// convert Celsius into Fahrenheit values
int fahrenheit;
fahrenheit = celsius * 9/5 + 32;
// output the results (followed by a NewLine)
cout << "Fahrenheit value is:";
cout << fahrenheit << endl;
Skipping over the comment lines, which C++ ignores anyway, this program starts by declaring a variable called celsius. A variable is a place you can use to store a number or character.
The next line displays the prompt to the user to "Enter the temperature in Celsius:". The object cout points to the console window by default.
The next line reads whatever number the operator enters and stores it into the variable celsius declared earlier.
The next two lines declare a second variable fahrenheit, which it then sets equal to the value of the variable celsius * 9 / 5 + 32, which is the conversion formula from Celsius to Fahrenheit temperature.
The final two lines output the string "Fahrenheit value is:" and the value calculated and stored in the variable fahrenheit immediately above.
3.144.37.38