Lab Assignment 2 Picking Sides in the Editor War & Getting Your C++ Legs Introduction ============ Last week's lab introduced you to the UNIX environment. The main goal of lab 1 was to give you a chance to play with the environment. In this lab, we will begin writing C++ code. The first step in this process is to "Choose your weapon", namely your text editor. The text editor is where you will spend most of your time when programming. After all, a program is nothing but text. There are many choices available to you in the realm of text editing, all with varying levels of complexity. The choice of editors is entirely up to you. I will have no way of testing which editor produces your source files. I strongly recommend that you use either vi or emacs as these editors come with built in capabilities to help you format and read code. Generally, programmers in UNIX tend to use one of these two editors. In the guided part of lab, you will be writing two programs. For the first, you will use vi. For the second, you will use emacs. These instructions will guide you through the basics of using these editors, and help you get a feel for which you prefer. After you complete the guided section, you should be able to edit and compile code. After you have made your choice of emacs... er, I mean after you have selected your text editor, it will be time to step out and write your first program. You will be provided with a skeleton of a procedure, but all the code and ideas will come from you. Savor this moment, for it is the first time you will go from a blank editor screen to a running program. To paraphrase Obi-Wan Kenobi, you are about to take your first steps into a larger world. Part I: Choosing Your Text Editor (Guided Lab) =============================================== In this part of the lab, we will take a look at the major text editors which are present on most UNIX systems. I will guide you through the use of two editors, emacs and vi. Before that, however, it is worth noting that these are not your only choices. So before the lab procedure, here's a rundown of UNIX text editors. Common Editors -------------- * ed ed was one of the earliest end user programs to be used on UNIX systems. This editor was created in 1971 by Ken Thompson. This editor contains many advanced features and went on to influence later editors. It was designed for an era in which UNIX terminals ran the gamut of devices. In fact, ed can be used on a teletype machine (basically a typewriter connected to a computer). As such, ed is not a visually interactive editor. After all, how can you be interactive when your output is printed on paper? ed is a modal text editor. This means that ed's responses to input depend on which mode you are in. There are 3 modes: 1. command - commands are entered in this mode. Example commands are a for "append text" or e for "edit file" 2. input - text is entered in input mode 3. view - the contents of the file are printed to the screen. You can print out the entire file, sections of the file, or single lines of the file. If you are interested in learning how to use ed, you can read its man page by typing "man ed" at the command prompt. ed is definitely an ancient text editor, and is really only mentioned here for historical purposes. However, you can gain some serious geek cred if you learn ed. Few people under the age of 50 know how to use it. Those that do know how to use it have found it useful in situations where no terminal emulation was available. * vi vi is the grandchild of ed. The lineage goes ed -> ex -> vi. The name is derived from the command which switched ex into visual mode. vi is a screen oriented editor, meaning that it is interactive and designed to be run on a screen, rather than on paper. vi first appeared in 1976, though very few people still use this version of vi directly. There are several variants of vi available, with the most important version being vim (VI iMproved). When you run the vi command, on most systems, you will actually be running vim. vim first appeared in 1991, and contains the original features of vi plus the ability to extend and customize the editor. For more information see "man vim" or run "vimtutor". Like ed, vi is a modal text editor. It consists of two modes: 1. Command - commands, mostly single character, are entered in this modes. Examples are 'i' - insert, 'a' - append, 'j' - move down, 'k' - move up, 'h' - move left, 'l' - move right. 2. Insert - in this mode, you are inserting text. What you type is what is added to the file. When vi starts, it starts in command/normal mode. You enter insert mode by typing either 'i' or 'a' as needed. to switch back to command mode, you press ESC. Note that all of the commands in vi are accessible without taking your hands out of the correct typing position. In a true coder's mind, anything which pulls your hands off the home row keys is an error. Arrow key usage is bad, the mouse is a catastrophe! The only thing that is a stretch in vi is finding the ESC key, but if you go the vi route, you'll soon be able to find that key at speed. vi is incredibly powerful and includes features like regular expressions, repeated commands, text buffers, and (in vim) multiple windows. Vim knows most programming languages, and so it provides features like syntax highlighting and auto-indentation. This will help you spot errors and write readable, well-formed code. vi has a steep learning curve because most modern computer users are not used to the modal operations. However, once you do learn vi, you will be able to rapidly edit text and less featureful editors will start to feel like toys. With a couple weeks of practice, you will be a natural. The next time you open up a different editor, you'll probably type about 20 j's at the top before you realize that you aren't in vi. You'll also begin to eye your classmates who chose emacs with suspicion. * emacs emacs came into being in 1976. It was originally written by Richard Stallman, and was based on the TECO editor. This was one of the first programs to become part of the GNU project. It was written in a combination of C and lisp. emacs is a highly extesnible editor, and can really do more for you than text editing. You can start emacs and stay there all day as you can read email, write email, organize your life, browse the web, access the shell, and more from right inside emacs. Emacs is one of the most extensible programs ever written. Its extensions and configuration files are written in a variant of lisp called "emacs lisp" so really, if you can program you can make emacs do whatever you please. Unlike the line of ed, emacs is not a modal text editor. The idiom it uses for input is sequences of key chords. A key chord is when you press 1 or more keys at the same time. Generally emacs key chords are 2 key presses and center around the Ctrl and Meta keys. On most keyboards, the meta key is the ALT key. Like vi, emacs key chords are written so you don't have to remove your fingers from the home row keys. Also, because it usually does not use ESC, people tend to be able to enter commands quite quickly. When you look at emacs commands on a cheat sheet and in the documentation, you will see things like this: C-x C-s This means hold down control, press x, release. Hold down ctrl, press s, release. In other words, when you see a dash, you push both keys simultaneously, and when you see a space, you release the keys before going on to the next. A common mistake is to try to push Ctrl, x, and s at the same time, which is difficult and does nothing. If you have a senquence of commands using the control key (or the alt key) you can continue to hold the ctrl throughout the command. For instance, the above example could be executed by holding Ctrl, tapping x, tapping s, then releasing control. Emacs is auto-documenting, and anytime you need help you can press M-x and then type "help" followed by enter. (M-x means Alt and x). This is the number 1 goto to get help with emacs. Also, pressing M-x and then typing "info" will give you access to an extended manual system from which you can learn about emacs, as well as most of the system. Emacs knows most programming language, and so it provides features like syntax highlighting and auto-indentation. This will help you spot errors, and write readable well-formed code. Emacs can have a steep learning curve, mainly because it has an overwhelming number of features. However, with just a week or two of practice, it will become second nature to you. You'll probably start locking up other editors when you hit the key chords that they don't understand. Fortunately, you can use emacs for everything, so you can stick with what you know. In time, you will take a look at the vi users and think that they are suspicious of you. They are, of course, right. Emacs users are plotting against them. In fact, we've even implemented vi in emacs-lisp, and that editor is called viper! (M-x viper-mode) * nano nano is about as close to notepad as your going to get on a UNIX system. It is designed to be easy to use, though it does this at the expense of features. Nano is a re-implementation of a program called pico, which is part of the pine email program. nano is not modal, and it only has single stroke commands. All nano commands start with control. When you see these written out they will be things like ^x, meaning "press Ctrl x", which is the most useful nano command (exit). Nano generally has a low estimation of its user's memory capacity, and so it constantly takes up the bottom two lines of the screen explaining how to use nano. Nano has virtually no advanced features, though it can do some rudimentary syntax highlighting. Nano is for normal people who want to send email and write text files. It is well suited for that purpose because it is easy for normal people to use. While it is very easy to learn nano itself, it's lack of programming features will make your life harder if you try to code in it. Also, other computer scientists will giggle behind your back if you use nano to code. It's there if you refuse the other editors, but I do not think it a very wise choice, though you are welcome to use it. * cat > file Ok, this is not really an editor, but I thought I would mention it as being the most minimalist way to enter text. cat reads a file and prints it to the screen. If you call cat with no argument, it will just repeat whatever you type in stdin to stdout. If you redirect this to a file, as in the above case, it will allow you to type text which the system will then save to a file. Pressing C-d will exit the program. The major drawback here is that you have no way to change text. Even text entered on the same line cannot be changed. If you're the sort of person who does everything perfectly the first time, then cat is your "editor" of choice! I mention it here for one reason. Back in my undergrad days, we used to compete with each other by seeing who could write the most elaborate program using only cat. This involved writing the code in our heads, and then simply entering it into cat. We usually played this game with a time limit of 15 minutes for text entry. I would like to see this tradition continue. Enjoy! Procedure --------- In order to explore which text editor is right for you, we will now try them on. This procedure should be carried out on a UNIX system. So after you have logged in, follow along! VI -- 1. Create a directory to store this lab. Name it lab2-1. Refer to your lab sheet from last week if you don't remember how to do this. 2. Change into the lab2-1 directory which you have just created. 3. We will start off with vi. As luck would have it, vim has a built in tutorial. To access it, type "vimtutor" at the command line and press enter. This will launch vim with a text file loaded containing several lessons on the use of vim. Follow the directions as listed. Note that when directed to save the file, you should save it as "TEST-VI" just so it stands out as being from vi. This file should contain your edits and will be submitted at the end of the lab for a grade. Finish the entire tutorial before moving on to the next step. Normally, starting vim can be done by simply typing "vim" or "vi" followed by the filename. This will launche the terminal version of vim. If you prefer a GUI, you can try "gvim" or select it from the application menu. 4. Using what you learned in step 3, use vi to create a file named hello-vi.cpp. To do this, type "vi hello-vi.cpp". 5. Now we are going to enter your first program. Traditionally, this is the hello world program. We are going to enter this program, compile, and then run it. You should know how to enter the program using the lessons you learned in step 3. So enter the following code before continuing. #include using namesapce std; int main(void) { cout << "Hello, world!" << endl; return 0; } 6. Save the file and exit vi. 7. Compile the program for execution. We do this by invoking g++. There are two ways to do this. The simplest way is to execute: g++ hello-vi.cpp This will result in an executable file named a.out. Go ahead and run this command and then do an ls to see that a.out was created. If g++ returns an error, open the file back up and try to fix the error. 8. You can execute the program by typing ./a.out. Go ahead and try that. 9. Now, usually we don't want to create programs named a.out. We could use mv to rename the file, but a more elegant solution is to have g++ generate the file of our choice. We do that with the -o option. Go ahead and try that out: g++ hello-vi.cpp -o hello-vi Now do an ls. Notice the hello-vi file? Try running it! NOTE: Be very careful with this. A common mistake would be to type something like "g++ hello-vi.cpp -o hello-vi.cpp". DON'T do this! What will happen is g++ will overwrite your source file with the binary. You'll be able to run your program, but your source code will go into the bit bucket from whence it can never be retrieved. 10. Now we are going to edit hello-vi.cpp. Add a line of code under the line which prints "Hello, world" to print "VI rocks!". HINT: This is a cout line. Also, this line must be before the return 0. 11. Compile and execute your modified program. Emacs ----- 11. Now we are going to move on to trying out emacs. Fire up emacs by typing "emacs -nw" and pressing enter. Press q to get past the welcome screen. Then type M-x (that's Alt + x) followed by "help" and press enter. When prompted for the topic, press t to begin the tutorial. This is pretty much the same thing as what vimtutor did, though it will take you through a bit more information about emacs. Be sure to save the tutorial file before you exit. Name this file TUTORIAL-EMACS. It should include your edits and it will be submitted at the end of the lab for credit. Finish the entire tutorial before proceeding. Emacs, just like vim, has a GUI available. To access it, just type "emacs" instead of "emacs -nw" at the command line. The "-nw" literally stands for "no window". 12. Now we are going to write some code with emacs. Create a file called "hello-emacs.cpp". If you are still in emacs, you can do this with "C-x C-f hello-emacs.cpp" If you are not in emacs any longer, you can do this from the command line by typing "emacs hello-emacs.cpp" and pressing enter. 13. Enter the same program we entered in step 5. 14. Compile this code giving the executable the name "hello-emacs". Refer to earlier steps if you need help compiling the code. 15. Open the source file up again. Before we alter it, I want you to see how you can run the shell from within emacs. The emacs tutorial showed you how to suspend and resume emacs, but there is an even better way. Once emacs is open, and you are looking at your beautiful hello world example, type "M-x shell". This will open the shell in an emacs buffer. Now, switch back to your hello-emacs.cpp buffer. 16. Alter the program by adding a message after the hello world message. This is a lot like what you did in the vi section, except this time you'll print out "Emacs rocks!". (Both statements are true. Both of these editors give you phenomenal power!) 17. Switch back to the shell buffer, and then compile the code. Run your program in the shell buffer. Note how nice it is to switch back and forth! Next Steps ---------- 18. Now, take a moment to reflect on these two editors. Which seemed right for you? If you can't decide now you can always switch back and forth. Your source code files are the same regardless of what you chose to create them with. Not to sway your choice or anything, but try these things out in emacs: M-x snake M-x zone M-x dunnet The key to learning these editors is a matter of exploration. For vi information, see the vim homepage http://www.vim.org, for emacs, see the help pages as well as the emacs wiki http://www.emacswiki.org. If you want to really get your edit-fu going, you are going to want to learn regular expressions. A good starting point on this path is to do a quick web search for "A Tao of Regular Expressions". Both vi and emacs support using regex to really empower your editing. You don't have to learn it right now, but if you are bored and curious, have a look! Turn in the Guided Lab ====================== 1. Start a script file named lab2-1.txt 2. List your current directory. 3. Display the contents of both your cpp files. 4. Compile both versions of the program. 5. Run both versions of the program. 6. End the script and submit it to the lab2-1 assignment on The Tartan. That's it for the guided part. Now on to the code which you will write yourself! Part II - Barometers are Falling! ================================= PROBLEM ------- A physics professor asked one of his students, "How could we determine the height of a building using a barometer?" The student replied, "I could tie a string to the barometer and lower it to the ground from the top. Then I could measure the string." The physics professor chuckled and said, "I want a more physics based solution." The student then said "Ok, I could drop the barometer from the top of the building and then time its decent and then calculate the height using the formula d=(1/2)*g*t^2. That's brilliant!" Much to the professor's horror, before he could correct his student the boy snatched the professor's prized barometer and raced to the stairs. Now, we know the professor is going to lose his barometer, so the least we can do is to help him make the most of it. We are going to design and implement a program which will measure the height of the building in terms of barometric catastrophe. A sample run of this program might be: ---- begin sample run ---- Drop your barometer. How long was it until you heard a crashing sound (in seconds)? 2.5 Your building is 30.65 meters tall. Now, you do realize that barometers are filled with mercury, right? Call the EPA NOW! ---- end sample run ---- Procedure --------- 1. Write out your pseudocode for how you are going to implement this program. Your pseuedocode should include a listing of the program's inputs, outputs, and the steps it performs. Also, during this part of the program, you'll want to identify the proper variable types for your inputs and outputs. 2. Set out a series of test cases (at least 5). Test cases should include a series of example inputs and the expected outputs. (see hints for how to do the math) 3. Using your favorite text editor, type out your pseudocode and test cases into a text file named "lab2-2-test". Now, run ~relowe/turnin You have no program yet, so just type exit when prompted for the compile. This is lab2-2-pseudocode. 4. Write your program in c++. Compile it, test it. Once it all works, create a script file (lab2-2.txt) which contains the following: - A listing of your program (cat your .cpp files) - A listing of your pseudocode. (cat your txt file) - Compile your program. - Test runs of your program. Submit your script file to The Tartan under lab 2-2. HINTS ----- - We want to make the program give output in meters. Therefore, our gravitational acceleration constant is g = 9.81 m/s^2. I would recommend creating a constant for g. - C does not have an exponent operator, therefore t^2 should be written as t*t. - The above example was computed as follows (in algebra, not C++): d = (1/2) * 9.81 * 2.5^2 = (1/2) * 9.81 * 6.25 = 30.65625 END NOTE: This document was completely typed using emacs. It is a plain text document, and so it should be readable on virtually every computational device known to man! Copyright (C) 2014 Robert Lowe This work is distributed under a Creative Commons Attribution-ShareAlike 3.0 Unported License (CC BY-SA 3.0) For more information, see http://creativecommons.org