Lab 0: Getting Started with C++


Introduction

The main purpose of this lab is to introduce you to the computing environment of your laboratory. You will use the ideas in this lab again and again throughout this course, so you should make every effort to understand not only what, but why you are doing what you are doing at each step.

Before we can begin our session, your instructor must inform you how to begin a session with the computer at your particular institution. The way this is done differs from school to school, according to the kind of computer being used, whether they are networked or stand-alone, whether a security system is in place, and so on. Among the things your instructor will tell you will be the answers to the following questions:

  1. Should the computer be turned on at the beginning of the exercise and off at the end of the exercise, or does it remain on all of the time?
  2. Do users of the computer have personal accounts (requiring one to login to begin an exercise), or can anyone use the computer?
  3. If users have personal accounts:
    1. How do I find out my username (the name by which I am known to the computer)?
    2. How do I find out my password (the secret word that allows access to my account)?
    3. Is it necessary to change my password (and if so, how is it done)?
  4. In your windowing environment (e.g., MacOs):
    1. Must I do something special to enter that environment?
    2. What role does the mouse play in that environment?
    3. How do I exit that environment?
  5. What must I do to quit a session using the computer?

About this Manual

In this (and every other) exercise, instructions will be printed in this default font (the one you are reading). To help you distinguish the instructions from what appears on your screen, text that you should see displayed on your screen will be shown in this font. Text that you are to type or enter will be shown in the this font.

The distinction between typing something and entering something is as follows:

Getting Started

Follow your instructor's instructions for beginning a session. When you see an arrow on the screen (pointing to about the 11-oclock position), the machine is ready for you to begin. If you have not used a mouse before, move it around on its pad and note how the arrow moves in response. The arrow is called the mouse cursor, and it is used to point at objects on the screen.

If you are not accustomed to using a mouse, take a few moments to practice pointing at objects on the screen.

Interacting with the Computer

The way in which you interact with a computer depends upon the computing environment of its operating system. For example, an environment in which you use a mouse to interact with menus, windows, and icons on a computer's screen is called a graphical user interface, or GUI (pronounced gooey) environment. MacOS, Windows-95 and Windows-NT all provide similar GUI environments.

Since you are reading this, you are presumably doing so using a software application called a web browser, such as Netscape or Internet Explorer. A web browser is an application that provides a GUI environment for exploring the World Wide Web, a network of computers from around the world linked together to share information. As you have (presumably) already discovered, a web browser lets you download information from remote computers simply by pointing the mouse at a link and clicking its left button.

In contrast to a GUI, there are environments in which you repeatedly:

  1. are prompted for a command,
  2. enter a command, and
  3. the machine displays the result of the command.
These are called command-line environments -- environments in which you interact with the machine by entering commands following the system prompt. MS-DOS (a precursor of Windows-95 and Windows-NT) and UNIX are examples of operating systems that use the command-line environment.

In order to use a command-line environment, you must learn those commands that the environment "understands." This in general makes a command-line environment more difficult to use than a GUI, since you must be able to recall the right commands to use the system. By contrast, users of a GUI environment need only be able to recognize the proper menu choice, link, or icon they need to select in order to make something happen.

Let's begin by learning about the mouse. The mouse button is usually used to select and open an object on the screen. Selecting an object is accomplished by pointing the mouse at the object and clicking once, opening is is similar, but requires a double-click (clicking the left button twice in rapid succession).

To illustrate, there should be a tiny picture (called an icon) in the upper right corner of your computer's screen. Different institutions use different pictures and names for this icon, so we will refer to it using the generic term hard drive icon. Point the mouse at your hard drive icon and click the left mouse button. The icon should darken, indicating it has been selected.

Next, double-click while pointing at your hard drive icon, to open it. A new window should appear listing some of the folders and files that are in your computer's hard drive.

Moving back and forth between windows is easy -- if you have your browser running, you can select it by just moving the mouse over any part of the browser and clicking the mouse button. Note that the titlebar at the top of the selected window darkens to indicate that the window is selected. Since you may have multiple windows on your screen at the same time, the MacOS darkens the titlebar of whichever window is currently selected, which is known as the active window.

Operations with the Mouse Button

One of the most common things people want to do with windows is reposition them on the screen. This is quite easy in the MacOS: just point the mouse at the titlebar of the window, hold down the mouse button, and move the mouse until the window is where you want it. This is called dragging the window. Then release the mouse button and the window will stay put (until you drag it somewhere else). This is called dropping the window. Dragging and dropping makes it easy to reposition a window.

Another common window-related task is resizing a window. Again, MacOs makes this easy: just point the mouse at the lower right-hand corner where you see two small boxes. Then drag the corner of the window in or out until it is the size you want. By dragging, dropping, and resizing you can arrange the objects on your screen according to your personal tastes.

In the upper right corner of every window is the zoom button. Clicking it either enlarges (zoom in) or shrinks (zoom out) the window. Clickint it again restores it to its previous position and size. Take a moment to try it with your hard drive's window.

In the upper left corner of every window is the close box. Clicking it causes your window to close and (if appropriate) return to iconic form. Take a moment and try it with your hard drive window.

If you click the close box of a running program, it may terminate that program resulting in the loss of any unsaved work, so use this button with caution.

Navigating in Your Computer

Ok! We're ready to explore! If you have a floppy disk, insert it into your computer's floppy drive, and let's get started.

If your floppy is already formatted for storing files, a new floppy disk icon should appear on the right side of your screen. If your floppy was not formatted, you will see a message indicating that the disk needs to be initialized. Go ahead and initialize it, and the floppy icon will (eventually) appear.

Double-click this icon to open it and view the contents of whatever disk you placed in the drive. If this is a new disk, its window may well be empty.

Each of the icons can be explored in exactly the same way as we just saw -- by double-clicking on the icon for that device, and then in its window, clicking on whatever icon(s) you want to examine next.

Folders

Very soon, we'll be entering and running a simple C++ program. But when we are done, we'd like to be able to save your program somewhere "safe" -- somewhere that, if the power goes off, your program can still be retrieved. To save your program safely, the computer stores it on magnetic media (usually a hard or floppy disk) in a container called a file.

During this course, we'll create dozens of files, and so some means of organizing them is needed. Just as the documents in a filing cabinet are often kept in manila file folders, MacOs lets us create a folder container in which we can store related files.

To do so, begin by making sure that your hard disk window is selected. (Your instructor may instead have a particular folder on the desktop where you are to work. If so, open this folder instead.) Then point the mouse at your File menu near the top left of your screen and click and hold the mouse button to display the File Menu. Move the mouse downwards until it points at the File -> New Folder choice, and release the mouse button when the choice darkens. You should see a folder icon labeled untitled folder appear in your active window.

When the new folder appears its name is automatically selected, so that you can give it a more descriptive name. Since we are creating a folder in which to store our labs, type labs to rename this folder appropriately.

Viewing the Contents of a Folder

To see what's inside of a folder is easy -- just double-click on the folder icon to open it! Take a moment to look inside your labs folder. It should be empty, since we have not yet put anything into it. Note that a new window appears but the old one remains nearby -- you can always return to the 'parent' window by clicking on it.

For practice, navigate back to the window containing labs and make three other folders: one named "practice", one named "projects" and one named "myLib".

Discarding a Folder

We made practice just for practice, to learn how to get rid of unwanted folders. Click on practice, drag it to the Trash icon (the icon will darken when the mouse is properly positioned over it) and drop it there. Your folder should disappear "into" the Trash, and if the Trash was empty, its icon should bulge to indicate that it is no longer empty.

If you throw something away and later decide you want to get it back, you can open the Trash by double-clicking on it and drag what you want to retrieve from the window back to your hard disk or floppy disk. If you are certain that you will not want to retrieve anything from the Trash, you can empty the trash by pointing the mouse at the Special menu, and choosing the Special -> Empty Trash menu choice. This operation cannot be undone, so use it with caution.

Your First Program

Once you have created your labs folder, you are ready to write your first C++ program. For now, writing a program consists of two steps:
  1. Writing a source program in a high-level language (i.e., C++) and storing that program in a file; and
  2. Translating that source program into a machine-language program (i.e., a binary executable).
CodeWarrior uses what is called an integrated desktop environment (IDE) to conveniently perform both of these steps (and other tasks). More precisely, the CodeWarrior IDE provides a text editor window in which you can enter the text of a program, and then save that program in a file. Once your program is saved, you can translate it into your computer's machine language (the binary 0s and 1s that a computer "understands") using the CodeWarrior compiler and linker. Graphically the process can be pictured as follows:

As we shall see in a later lab exercise, this is a bit of a simplification, but it is sufficiently accurate to give you an idea of what is occuring. For now, just realize that the IDE's text editor is what you use to enter a program, and its compiler and linker are what you use to translate it.

Starting CodeWarrior

To get started, invoke CodeWarrior according to your instructor's directions. (This may involve double-clicking on an icon on your computer's desktop, or clicking on the Apple menu and choosing CodeWarrior from that menu.) The only change should be that the rightmost menus at the top of your screen will be replaced by menus specific to CodeWarrior.

Our first program will input a base-10 integer and display that same value in base-10 (decimal), base-8 (octal) and base-16 (hexadecimal). We will thus name the executable program bases, and name the source program bases.cpp (C++ source programs end in .cpp by convention.)

Creating a Project

The CodeWarrior IDE provides a convenient feature called a project that simplifies the translation of a source program into machine language. The normal procedure is to create such a project first, before we create any source files for our program, (though it is quite easy to add existing source files to a project.)

To create a project, move the mouse to the File menu and choose New Project... from the menu. This should cause a dialog window named New Project to appear, containing a right-arrow named MacOs (and possibly other right-arrows). Click on the MacOS right-arrow and three more arrows should appear. Click on the one labeled C_C++. Two more right-arrows will appear. Click on the one labeled Standard Console, and a list of various Macintosh console types will appear. If you are working on a PowerPC Macintosh, select the Std C++ Console PPC choice and then click the Ok button (or just double-click on the choice).

We have just chosen the kind of project we are making. Each of the exercises in this manual will use this same kind of project. Since you will need to repeat these steps in each subsequent exercise, try and commit them to memory now.

Another dialog box will appear in which you can specify the name of the project. Click in the blank box and type the name bases.project. It is always a good idea to give the project the same name as your program, but with the .project extension.

Above this box is a list of the files and/or folders in the directory where CodeWarrior will save your project. Above that list is a small box giving the name of the directory where CodeWarrior will save it. If these are not where you wish to save your project (i.e., not on your floppy drive), click on the top-most box and hold down the mouse button. A cascading list will appear that allows you to navigate back "up" through the folder hierarchy to your desktop. (Alternatively, you can just click the Desktop button.) Once there, you can navigate "down" to the folder where you wish to save your project by opening the appropriate folder(s) in the file/folder list.

Once the top-most box contains the name of the folder where you wish to save your project, and you have specified that its name is to be bases.project, click the Save button and CodeWarrior will create a new folder there containing your project. A new project window named bases should appear, containing three right-arrows: one labeled Sources, one labeled ANSI Libraries, and one labeled Mac Libraries.

Creating the Source Program

Next, we want to create a new file named bases.cpp in which to store our program. To do so, move the mouse to the File menu within the and choose File -> New again. A blank window will appear, named untitled. To give it the proper name, choose File -> Save and in the dialog box that appears, type bases.cpp and then click on the Save button. The window will then be renamed bases.cpp. Then choose Project -> Add Window and bases.cpp will be added to your project.

One final bit of housekeeping and then we will be ready to begin on the program. Return to bases, the project window. (If it is hidden by bases.cpp, you can use Window -> bases to make it the active window and bring it into view.) In that window, click the right-arrow labeled Sources. You should see both bases.cpp and another file named HelloWorld.cp. By default, CodeWarrior places this file in each project, and so we must remove it from each new project we create. (This is a bit of a nuisance, but a minor one.) Click on HelloWorld.cp and hold the mouse button down. A mini-menu will appear from which you can choose Remove Selected Item. Do so and HelloWorld.cp will be removed from your project.

Within the bases.cpp subwindow, enter (and personalize) the following C++ source program:

/* bases.cpp demonstrates basic I/O in C++.
 *
 * Author: Jane Doe.
 * Date: 2/29/99.
 * Purpose: Lab 0 in CS-1 at the University of Gallifrey.
 *
 * Specification:
 *   Input(keyboard): aNumber, an integer;
 *   Output(screen): the base 10, 8 and 16 representations of aNumber.
 ***********************************************************************/

#include <iostream>
using namespace std;

int main()
{
   // 0. print a message explaining the purpose of the program.
   cout << "\nThis program inputs a base-10 integer"
        << "\n\tand displays its value in bases 8 and 16\n";

   // 1a. ask the user to enter an integer.
   cout << "\nPlease enter an integer: ";
   // 1b.declare an integer container to hold the input number
   int aNumber;
   // 1c. input an integer, storing it in variable aNumber.
   cin >> aNumber;

   // 2. output the base-8 and base-16 representations of aNumber.
   cout << "\n\nThe base-8 representation of " << aNumber << " is "
        << oct << aNumber
        << ",\n\tand the base-16 representation is "
        << hex << aNumber
        << "\n\n";
}
One shortcut is to copy-and-paste the text above from your browser's window into the bases.cpp window. Let's learn how to do this next.

In MacOS, a block of text can be selected by pointing the mouse at the top of the block of text, and dragging downward to the bottom of the block of text. To copy-and-paste the selected text:

  1. Choose Edit -> Copy from the Edit menu You can alternatively use the keyboard shortcut Apple-c (hold down the key with an apple on it and type c) to copy whatever you have selected.
  2. Move the mouse to the window in which you want to paste the text, and position the mouse cursor (i.e., click) where you want the text to be inserted.
  3. Choose Edit -> Paste from the Edit menu of the window in which you want to paste. You can alternatively use the keyboard shortcut Apple-v to paste whatever you most recently copied.

Using this approach, copy the program shown above into the bases.cpp subwindow.

Personalizing the Program

As given above, bases.cpp is the work of a fictitious person (Jane Doe) on a fictitious date (February 29, 1999), in a fictitious course (CS-1) at a fictitious university (the University of Gallifrey). Edit the program's opening comment (the part between the /* and */ symbols) as appropriate to make it your work on the current date, in your course at your university.

As you've probably figured out, you can use the mouse to position the cursor at an arbitrary point by pointing at that point and clicking the left mouse button. The arrow keys (or the mouse) can be used to reposition the cursor.

If you mistype something, it can be erased using the delete (or backspace) key. On many keyboards, the Delete key is set up to erase whatever is to the right of the cursor, while backspace erases whatever is to the cursor's left.

If you make a mistake, you can always undo your most recent typing using the undo command: Ctrl-z or by using the Edit -> Undo menu choice.

Saving Your Work.

When the bases.cpp subwindow contains the bases.cpp program, you can store this program in a file by choosing File -> Save or by using the keyboard shortcut Apple-s. If you look in the your project folder, you will see that it is no longer empty, but now contains bases.project, bases.cpp, and a variety of other files. Don't worry about these other files for the moment -- they are just administrative files CodeWarrior uses to keep track of what is where.

Translating Your Program

When your source program is entered and saved, it is time to translate it into the computer's machine language. In CodeWarrior, this can be done using the Project -> Make menu choice, or the keyboard shortcut Apple-m. When this is done, CodeWarrior displays a Building bases.project subwindow in which you can watch the translation as it proceeds through the compilation and linking stages. If all is well, the window should disappear returning you to where you were.

On the other hand, if your program contains typographical errors, CodeWarrior will display a Errors & Warnings window in which it will list the errors it discovered in your program. If you double-click on a given error, CodeWarrior will highlight the line in bases.cpp where that error was discovered. (Often, this is the line following the line where the error actually occurred.) CodeWarrior will not run a program that contains errors, so you must correct all errors in a program before proceeding.

To illustrate this, delete the final semicolon in the program (the one on the next-to-last line). Then use Project -> Make to rebuild your program. When the Errors & Warnings window appears, double-click on the error.

Note how CodeWarrior highlights the last line, even though the error is on the preceding line. This is because the Errors & Warnings window lists the line where the error was discovered. Since the error was at the end of the next-to-last line, and C++ is not oriented around lines, CodeWarrior did not discover that the semi-colon was missing until it began processing the last line. Fix the error, rebuild your program, and then continue.

Running Your Program

Running your program is just as easy as anything else in CodeWarrior. Choose Project -> Run or use the keyboard shortcut Apple-r and the IDE will run the program for you. A window named Std C++ Console PPC.out will appear, in which your program will be executed.

When it prompts you for input, enter an easy-to-check number (like 15, 16 or 17) and verify that you get the correct results.

Printing a Hard Copy of Your Program

A paper copy of electronic information is called a hard copy. It is often useful to have a hard copy of one's source program, which is in the file bases.cpp. As with much of CodeWarrior, this is quite easy: just make sure that bases.cpp is the active window and choose File -> Print, or use the keyboard shortcut Apple-p. A Printer dialog box should appear. You should just be able to click its Print button to print a hard copy of your program's output. If you must do anything beyond this (such as specify a printer), your instructor will inform you of the details.

Printing an Execution Trace

It is often useful to be able to print a hard copy of the output from your program, especially for more complicated programs. As is usually the case in CodeWarrior, this is quite easy: just make sure that Std C++ Console PPC.out is the active window and then choose File -> Print, or use the keyboard shortcut Apple-p.

Once you have a hard copy of your program's execution, you can tell your program to quit by choosing File -> Quit (or by typing Apple-q). A dialog window will then appear asking if you want to save the output from your program in a file. Since we do not need to save this output, click the Don't Save button.

Applying the Scientific Method

An important part of any science, including the science of computing, is to be able to observe behavior, form hypotheses, and then design and carry out experiments to test your hypotheses. The next part of this exercise involves applying the scientific method to infer (from the statements within bases.cpp) how the certain aspects of C++ output system work. Since two heads are (sometimes) better than one, feel free to work through this section with the person sitting next to you.

Observe

Study your hard copies of bases.cpp and its output, positioning the pieces of paper so that you can see both of them simultaneously, side by side. Note in particular the points at which lines end and blank lines appear. Everything that appears in the output is caused by something in bases.cpp, so study the text of bases.cpp and try to identify what within the program causes the output lines of text to break to a new line where they do.

Hypothesis

Construct a hypothesis (i.e., a statement) that states how you think output text can be made to begin on a new line in a C++ program.

Experiment

Design an experiment using bases.cpp that tests whether or not your hypothesis is false. (Recall that the scientific method can only prove that a hypothesis is false; it can never absolutely prove a hypothesis to be true.)

Then modify bases.cpp as necessary to perform your experiment, re-translate bases.cpp into machine language, and run it. If the resulting behavior indicates that your hypothesis is false, repeat the preceding Observe-Hypothesis-Experiment steps until you form a hypothesis that you are unable to prove to be false.

When you are unable to prove your experimental hypothesis to be false, print a hard copy of your modified bases.cpp. On that hard copy, write down your hypothesis, your experiment, and circle that part of the program that performs your experiment. Then print a hard copy of its output and note on it the effects of your experiment.

Wrapping Up the Session

In the remainder of this exercise, we examine the final things you will need to do in most sessions.

Cleaning Up Your Project

As you can see in your project, a program may consist of source files and one or more libraries. In the course of writing and debugging a program, it may be necessary to compile the program dozens of times! Since all debugging is confined to the source files, recompiling the (unchanged) libraries each time would waste lots of time.

To avoid this inefficiency, once a file is compiled, a CodeWarrior project stores a copy of the compiled version called an object file. The Project -> Make command then recompiles any files that have been changed, and uses the existing object files of any files that have not been changed. By avoiding unnecessary recompilations, this saves lots of time.

Object files speed every Project -> Make after the first one, but they also consume disk space. You can see how much by looking at the Code and Data columns in your bases.project window. To save disk space, the object files should be removed from a project any time you are done working on it.

To remove these files, choose Project -> Remove Object Code Click Ok in the dialog that appears, and then watch the Code and Data columns in your bases.project window change to zeros as CodeWarrior removes the object files from the project!

Quitting CodeWarrior

To quit CodeWarrior, choose File -> Quit (or type Apple-q on your keyboard).

Cleaning Up Your Directory

The various files you have created take up valuable disk space -- as it stands, bases will not fit on a floppy disk -- and so we will remove the non-essential files from bases. So long as we keep our source program, and the project files, we can easily rebuild our program from within CodeWarrior.

Navigate back to your labs folder and select (without opening) folder bases. Then go to the File menu and choose File -> Get Info and a box will appear telling you (among other things) how much disk space bases consumes (980 Kilobytes -- just under 1 Megabyte -- on our system).

Click the close box on the bases info window. Then open bases and then drag everything except bases.cpp and bases.project to the Trash. Empty the Trash and then navigate back to your labs folder. There, select (again, without opening) bases and see how big it is now that we have deleted Debug. On our system, bases is now just 196 Kbytes, which is a big savings.

Since a floppy disk only stores 1.4 Mbytes, the morale of the story is, always clean out your project folder before trying to save your work to a floppy disk.

Copying Your Work to a Floppy Disk

If you brought a floppy disk with you, you can save a copy of your work by navigating to the folder containing labs, selecting your labs folder, dragging it to the icon of your floppy disk, and dropping it there. When you drop the folder, you should hear the drive motor activate as the copy is performed and then stop. Note that this truly is a copy operation -- the original folder remains on your hard disk. To avoid having someone else plagiarize your work, you should then drag your original labs folder to the Trash and then empty the trash.

Once you have cleaned up in this manner, end your session with the computer, following your instructor's instructions.

Note: If your head feels ready to explode, don't panic! This first lab covers a great deal of material, that you will use over and over again, and as you do so, you will begin to naturally memorize those commands that you use most frequently. You can speed up the process by reviewing each of the steps you took in this exercise and practicing in your free time.

Submit:

Your original hard copy of bases.cpp, the hard copy of its output, a hard copy of your modified bases.cpp annotated with the details of your experiment, and the hard copy of its output annotated as described in the exercise.

Phrases you should now understand:

Integrated Desktop Environment, Folder, File, Navigate, Editor, Compiler and Linker, Hard Copy, Printer.


Back to This Lab's Home Page

Back to the Prelab Questions

Forward to the Homework Projects


Copyright 1998 by Joel C. Adams. All rights reserved.