Chapter 3

Writing Your First Program

In This Chapter

arrow Entering your first C++ program

arrow Compiling and executing your program

arrow Examining some things that could go wrong

arrow Executing your program

arrow 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.

Creating a New Project

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):

  1. With Code::Blocks open, select File⇒New⇒Project.
  2. Select Console Applications and select Go (or double-click the Console Applications icon).
  3. Select C++ as your language of choice and select Next.
  4. Enter Conversion as the Project Title.

    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.

    9781118823873-fg0301.tif

    Figure 3-1: The Project window for the Conversion program.

  5. Select Next.

    The next window allows you to change the target folders. You probably won’t need to; the defaults are fine.

  6. Select Finish.

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.

9781118823873-fg0302.tif

Figure 3-2: The initial display after creating the Conversion project.

Filename extensions

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.

tip.eps To minimize confusion, disable the Windows Hide Extensions feature. Exactly how you do that depends upon the version of Windows you’re using:

  • Windows XP with Default View: Select Start⇒Control Panel⇒Performance and Maintenance⇒File Types.
  • Windows XP with Classic view: Select Start⇒Control Panel⇒Folder options.
  • Windows Vista with Default view: Select Start⇒Control Panel⇒Appearance and Personalization⇒Folder Options.
  • Windows Vista with Classic view: Select Start⇒Settings⇒Control Panel⇒Folder options.
  • Windows 7: Select Start⇒Control Panel⇒Appearance and Personalization⇒Folder options.

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.

Entering Your Program

Follow these steps to enter the code that creates your first program using C++:

  1. Make sure that Conversion is bolded in the Management window (refer to Figure 3-2).

    This indicates that it’s the active project. If it isn’t, right-click Conversion and select Activate Project from the drop-down menu.

  2. Close any source-file windows that may be open by selecting File⇒Close All Files.

    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.

  3. Open the Sources folder by clicking the small plus sign next to Sources (it’s underneath Conversion in the Management window).

    The drop-down menu reveals the single file main.cpp.

  4. Double-click main.cpp to open the file in the editor.
  5. Edit the contents of main.cpp by entering the following program exactly as it appears here.

    The result is shown in Figure 3-3.

    9781118823873-fg0303.tif

    Figure 3-3: The edited main.cpp file of the Conversion program.

    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.

  6. Save the file by selecting File⇒Save all files.

Building the Program

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.

Finding What Could Go Wrong

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.

remember.eps These are just two of the myriad ways to screw up in C++. I can’t possibly show you all of them. Learning how to interpret what the compiler is trying to tell you — with its error and warning messages — is an important part of learning the language. It can come only from many months of practice and gaining experience with the language. Hopefully, these two examples will get you jump-started.

Misspelled commands

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.

9781118823873-fg0304.tif

Figure 3-4: The error messages resulting from misspelling int.

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.

warning.eps One C++ error can generate a cascade of error messages. It’s possible to identify and fix multiple errors in a single build attempt, but it takes experience to figure out which errors stem from which others. For now, focus on the first error message. Fix it and rebuild the program.

Missing semicolon

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.

tip.eps Missing semicolons often generate error messages that bear little resemblance to the actual error message, and they’re almost always on the next line after the actual error. If you suspect a missing semicolon, start on the line with the reported error and scan backward.

Using the Online Material

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.

tip.eps You should really try to enter the program by hand first, before you resort to the online material. It’s only through working through mistakes that you develop a feel for how the language works.

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:

  1. Download the file CPP_Programs.zip and unzip this file somewhere can find it easily.

    On a Windows machine, that would probably be C:CPP_Programs.

  2. Select File⇒Open from within Code::Blocks. Navigate to CPP_Programs/Conversion.
  3. Select the file main.cpp.

    Code::Blocks opens the file in a new tab in the editor window.

  4. Select Edit⇒Select All or press Ctrl+A.

    Doing so selects the entire contents of the source file.

  5. Select Edit⇒Copy or press Ctrl+C.

    This copies the entire file to the Clipboard.

  6. Select the main tab corresponding to your program.
  7. Select Edit⇒Select All or press Ctrl+A again.
  8. Select Edit⇒Paste or press Ctrl+V.

    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.

  9. Close the tab containing the downloaded version of the file by clicking the small X next to the filename.

Running the Program

You can execute the program once you get a clean compile (that is, 0 errors and 0 warnings) by following these steps:

  1. Select Build⇒Run or press Ctrl+F10.

    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.

  2. Enter a known temperature like 100 degrees. Press Enter.

    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 …

  3. Press Enter twice to exit the program and return to the editor.

How the Program Works

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 template

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;
}

Comments

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.

Include files

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.

main

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.

technicalstuff.eps The call to cin.get() isn’t necessary as long as you’re running your programs from the Code::Blocks environment. Code::Blocks waits for the user to enter a key before closing the console application window anyway. However, not all environments are so understanding. Leave this off and very often C++ will close the application window before you have a chance to read the output from the program. (I get lots of hate mail when that happens.)

The Conversion program

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.74.160