course.wilkes.edu/CS125Labs
Welcome to the site for CS 125 labs!

 

Lab 0: Your First Program

Prev | Next | Lab 0

Your First Program

Once you are "in" the directory 0, 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).
The first step can be accomplished using a tool that allows you to create and edit files containing text (i.e., characters) and is thus called a text editor. The text editor used throughout this manual is named xemacs, a freely available text editor that is a collaborative effort of a number of companies and universities. Xemacs is a descendent of the original emacs text editor from The Free Software Foundation, and remains largely compatible with it; however xemacs provides a much nicer user interface for writing programs, including a menu bar providing push-buttons for common editing commands, and a color-editing mode that shows C++ keywords in one color, variable names in another color, comments in another color, and so on. In fact, this manual was written using xemacs!

Once we have created a file containing our source program, the second step can be accomplished through the use of a C++ compiler: a program that translates C++ programs into machine language (the binary 1s and 0s that a computer "understands." 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.

The C++ compiler used throughout this manual is named g++ and it (like emacs) is a freeware product of the Free Software Foundation.

Editing a File

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.) We can use xemacs to create the source program by entering:

	% emacs bases.cpp
(If you are using the X-window environment, use 'xemacs' and add an ampersand (&) at the end.)

Since the file bases.cpp does not exist in the working directory, emacs will create a new, blank editing window (called a buffer) named bases.cpp into which you can type a program. (If a file named bases.cpp existed in the working directory, then xemacs would create a blank buffer, open that file and read the file into the buffer). Note that xemacs displays the name of the buffer status bar near the bottom of the window, and that the name of a buffer is the name of the file it is displaying.

Within the bases.cpp buffer, we are going to enter (and personalize) the following C++ source program:

// bases.cpp demonstrates basic I/O in C++.
//
// Written by:  Jane Doe, November 21, 2009.
// Written for: CS 125, at Wilkes University.
//
// Specification:
//   Input(keyboard): aNumber, an integer;
//   Output(screen): the base 10, 8 and 16 representations of aNumber.
//**********************************************************************

using namespace std;

int main() { // declare an integer container to hold the input number int aNumber;

// 0. print a message explaining the purpose of the program. cout << endl << "This program inputs a base-10 integer" << endl << " and displays its value in bases 8 and 16" << endl;

// 1. ask the user to enter an integer. cout << endl << "Please enter an integer: ";

// 2. input an integer, storing it in variable aNumber. cin >> aNumber;

// 3. output the base-8 and base-16 representations of aNumber. cout << endl << endl << "The base-8 representation of " << aNumber << " is " << oct << aNumber << "," << endl << " and the base-16 representation is " << hex << aNumber << endl << endl;

return 0; }

If you are working from a terminal or via telnet, you will have to type in this program; but if you are using the X-window environment, you can instead copy-and-paste the text above from your browser's window into the xemacs window. Let's learn how to do this next.

In the X-window system, a block of text can be selected by dragging (holding down the left mouse button while moving the mouse) from the beginning to the end of the desired text.

Most X environments support a copy-paste short-cut:

  1. drag the mouse over the text you want to copy, selecting it;
  2. position the cursor where you want to paste by pointing the mouse there and clicking the left mouse button; and
  3. paste by pressing the middle mouse button.
If your environment does not support this short-cut, try clicking the right-mouse button with text selected, and a menu should appear providing cut, copy and paste menu choices.

Using one of these methods, copy the program shown above into the xemacs bases.cpp buffer.

Personalizing the Program

As given above, bases.cpp is the work of a fictitious person (Jane Doe) on today's date at Wilkes University. Edit the program's opening comment (the part after the // symbols) as appropriate to make it your work on the current date, in your course at your university.

If you are using xemacs in the X-windows environment, 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 editor command C-d (typing the Control and d keys simultaneously) can be used to delete the character beneath the cursor, and C-k can be used to delete from the cursor to the end of the line.

If you are running xemacs outside of the X-windows environment, you can move the cursor by the editor commands:

  • C-p (previous line) to move up one line,
  • C-n (next line) to move down one line,
  • C-b (back) to move left one character, and
  • C-f (forward) to move right one character.
Alternatively, you can use the arrow keys on your keyboard to move the cursor. If you mistype something, it can be erased using the delete (or backspace) key.

If you make a mistake, you can always undo the effects of any xemacs command, either by using the undo command: C-x u (type Control and x simultaneously, then type the u key by itself), or by using the Undo button on the xemacs menu bar.

The undo command can be used to undo the effects of an xemacs command that has completed. However some xemacs commands take a significant length of time, and you may wish to get out of the command while it is still being performed. For this, you can use the get-out command: C-g, which we find to be useful in a wide variety of situations.

Saving Your Work.

When the bases.cpp buffer contains the bases.cpp program, you can store this program in a file by entering the editor save files command C-x s (hold down the Control and x keys simultaneously; then type the s key separately). Xemacs will ask you to confirm the operation (in the mini-buffer at the bottom of the window):

	Save file .../labs/0/bases.cpp? (y, n, !, ., q or C-h)
To save the contents of the buffer in a file named bases.cpp, answer 'yes' by typing y:
	Save file .../labs/0/bases.cpp? (y, n, !, ., q or C-h) y
Xemacs will then confirm the save operation by displaying the Wrote file ... message shown above. Since we have saved bases.cpp in the subdirectory ~/labs/0, we can visualize our situation as follows:

Translating Your Program

When your source program is entered and saved, it is time to translate it into the computer's machine language. In xemacs, this can be done using the editor compile command M-x compile (press and release the Meta, Escape, or Edit key, then press the x key, and then type the word compile) at which point xemacs will echo what you type in the mini-buffer. This will shift the cursor to the mini-buffer (at the bottom of the window) where xemacs will print

	Compile command: make -k

For simple programs like this one, the easiest way to translate our program is to replace the make -k with an explicit call to the GNU C++ compiler g++. Using the delete (or backspace) key, erase the make -k and replace it as follows:

	Compile command: g++ bases.cpp -Wall -o bases
This changes the compile command from a call to make (a program we will learn about in a few weeks) to an explicit call to the GNU C++ compiler g++, asking it to translate the program in the file bases.cpp. The -Wall is an optional switch that tells g++ to warn us on all potential sources of error. The switch -o bases tells g++ that it should write its output (i.e., the binary executable program) to a file named bases.

Once you have edited the compile command, press the Return key and xemacs will split its window in two, displaying the bases.cpp buffer (containing your source program) in one half and displaying a new *compilation* buffer (containing the results of your compile command) in the other half. If bases.cpp is free of errors, then you should see a message like:

	Compilation finished at Mon Sep 5 9:12:44
in the *compilation* buffer.

If you instead see an error listing:

	bases.cpp: In function `int main()':
	.
	.
	.
	Compilation exited abnormally with code 1 at Mon Sep 5 9:12:44
then you have made typing errors in entering the program. The editor next-error command: C-x ` (Control and x, followed by the left-quote (not the single-quote) key) will move the cursor to the line in your source program where it discovered the error (but the error may be on a previous line). Compare the program above with what you have written and then change what you have written to fix the error. Then use the compile command again to see if you fixed the mistake. Repeat this edit-compile cycle as many times as necessary, until your program compiles correctly. Once your program compiles correctly, g++ writes the resulting executable file to the working directory, giving us this picture:

Use ls to verify that your directory contains the executable file named bases (it may also contain additional files, such as automatic back-up files created by xemacs).

Running Your Program from the Command-Line.

Running program bases is the same as running any other program: We must enter its name following an operating system prompt.

If you are using the X-window environment, the xemacs window is just one of many independently running windows. Locate a different window in which the system prompt is displayed (i.e., the xterm window from which you invoked xemacs). Simply move the mouse into this window (or perhaps click in it) and the cursor should appear, indicating that it is ready for your command.

If you are using a terminal or telnet instead of the X-window system, use the xemacs suspend command: C-z. The operating system will then suspend xemacs and display the system prompt, indicating it is ready to accept a command.

Once you are at the operating system prompt, use pwd to check that your working directory is your 0 subdirectory. (If not, change directory to make it so.) Then use ls to display the contents of 0, to make sure that both the source file bases.cpp and the binary executable bases are there. At that point, you can enter

	% bases
and your program should execute successfully. If it does not, ask your instructor for help.

Returning from the Command-line to Xemacs

If you are using the X-window environment, simply move the mouse from your xterm window back into the emacs window. (If necessary, click the mouse.)

If you are using a terminal or telnet and you suspended xemacs using C-z, then enter:

	% fg
which changes xemacs from being suspended to being a foreground process.

Printing a Hard Copy

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.

In an AT&T UNIX command-line environment, you can usually print a hard copy of this file by entering

	% lp bases.cpp
or
	% lp -d PrinterName bases.cpp
while in the Berkeley UNIX command-line environment, you can usually print a hard copy by entering
	% lpr bases.cpp
or
	% lpr -PPrinterName bases.cpp
Your instructor will inform you of the details of printing at your institution.

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

Using the mouse, position your xemacs and xterm windows so that you can see both of them simultaneously. Run the bases program one or more times and study its behavior, particularly the points at which lines end and blank lines appear. Then study the text of bases.cpp and see if you can see anything within the program that might be causing lines to end.

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 your hypothesis. (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 is not false.

When your experimental hypothesis is not proven 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.

As noted above, an experiment in which your hypothesis is not rejected does not prove that it is correct!

Miscellaneous Other Useful Commands

In the remainder of this exercise, we examine some other useful commands.

Quitting xemacs

To quit xemacs (as opposed to suspending it), you can type the editor quit command: C-x C-c (Cntrl and x, followed by Cntrl and c).

Copying a File

It is sometimes useful to be able to make a copy of a file, so that we can modify a copy without modifying the original. To make a copy of bases.cpp in a different file named bases.2, enter:

	% cp bases.cpp bases.2

The cp command makes a copy of the file with the first name (i.e., bases.cpp), and names the copy the second name (i.e., bases.2). Here is the pictorial representation:

Use the ls command to verify that cp command worked.

It's more often the case that we need to make a copy of a file in a directory different from the one in which the file currently resides. How are we to do this? The key is to learn a bit about how files and directories are named. Both of the names bases.cpp and bases.save are the relative names of these files. To use these names, we must be in the same directory as they are.

However, every file or directory also has an absolute name: a name that starts with the root directory (i.e., /), and lists each directory between there and the file name, just as we saw in the output from pwd. For example, the absolute name of bases.cpp on my machine is as follows: /home/adams/C++/labs/0/bases.cpp (or more briefly ~/C++/labs/0/bases.cpp.

To use a file's (or directory's) absolute name, you need not be in the same directory as that file! For example, try entering:

	% mkdir ~/projects/0

What did we just do? We used the mkdir command to make a new directory, but where did we make it? Recall that earlier in this exercise, we made two new directories within our home directory: labs and projects. Since ~ is another name for our home directory, we just made a new directory inside projects, called 0, using an absolute path name! Here is the picture:

Almost all of the UNIX file manipulation commands accept either relative or absolute file names. For example, you don't need to be "in" a directory to see its contents: Enter

	% ls ~/projects
and you should see the directory you just made.

Similarly, to put a copy of bases.cpp in that new directory, you can enter:

	% cp bases.cpp ~/projects/0
and a copy of bases.cpp will be stored in that directory.

The cp command thus behaves differently, depending on whether you specify a file or a directory as the second name: if you specify a file as the second name, then the cp command will store the copy in a file with that name. If you specify a directory as the second name, then cp will place a copy in that directory with the name as the original.

Using ls and an absolute path name, verify that there is a copy of bases.cpp in ~/projects/0.

Renaming a File

Sometimes we decide after the fact that a file would be better off with a different name. To change the name of bases.2 to bases.save, enter:

	% mv bases.2 bases.save
The mv command changes the name of (or moves) the name of the file on the left to the name on the right. Our picture changes as follows:

It can be used with both relative and absolute file names, and can be used to rename directories.

Creating and Printing a Hard Copy of an Execution

Besides a hard copy of one's program, it is often useful to have a hard copy of the output from one's program. To do this, we must

  1. record the output of the program in a file; and
  2. print that file using lp (or lpr).
To record the output of bases in a file, enter
	% script
The script command runs a program that records everything that appears on the screen of a terminal (or everything that appears within an xterm window). Thus, if you subsequently execute bases, then its output will be recorded by script. Once bases has terminated, enter
	% exit
to terminate the script program, which informs you that its recording is in a file named typescript. A hard copy of the file typescript can then be printed using lp (or lpr), as described previously.

Cleaning Up Your Directory

The various files you have created take up valuable disk space, and so we will remove all of the files from 0 except for our source program bases.cpp (the others can always be easily re-generated from your source program.) To remove bases.save, enter

	% rm bases.old
The rm command removes (or deletes) whatever file you specify. Note that it does not ask you for confirmation! (If you want such confirmation, call rm with the -i switch.) Earlier we saw that when rm is invoked with the -r switch, it recursively removes a directory and everything within it.

Use the rm command to remove the files typescript, bases.cpp~ (a back-up file created by xemacs) and the executable file bases. Then use the ls command to verify that all of the files except bases.cpp are gone. If there are other files remaining in your 0 directory, use the rm command to remove them, as well.

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

Until such a time as you remember the various commands, here are two quick reference pages to help you "look up" commands: one listing some of the commonly used UNIX commands and one listing some of the commonly used xemacs commands. Print hard copies of these, and store them in a convenient place!

To learn to use these quick references, I would recommend that you review today's exercise, and find each of the commands we used in the exercise on the appropriate quick reference sheet. Then study the description of that command on the quick reference sheet, so that you associate the two in the future.

Submit:

Your original hard copy of bases.cpp, a hard copy of your modified bases.cpp annotated with the details of your experiment, and the script file showing its execution.

Phrases you should now understand:

Environment, Command-Line, Directory, File, Editor, Compiler, Hard Copy, Printer.

Prev | Next | Lab 0

 
  Home

Help

Lab 0

Lab 1

Lab 2

Lab 3a

Lab 3b

Lab 4

Lab 5

Lab 6

Lab 7

Lab 8

Lab 9

Lab 10

Lab 11

Lab 12

Lab 13



Membership

Login




Last update: Tuesday, August 28, 2001 at 4:30:55 PM.
visitors to this page.