Computer Science 111, Assignment 1

Tutorial on Unix, vi, gcc, and elementary C++ syntax

Copyright © 2001, 2002, 2004 by Dorothy L. Nixon. All rights reserved


CONTENTS OF THIS TUTORIAL

  1. Files and directories on a Unix system
  2. Creating directories for your homework
  3. Preventing interruptions from other venus users
  4. The vi text editor
  5. Your disk quota, and removing core dumps
  6. Typing, compiling, and running a C++ program
  7. Copying files, and more about pathnames
  8. Some C++ syntax basics
  9. Compiler error message tutorial, and more about elementary C++ syntax
  10. Integer vs. floating-point division
  11. Programming exercise
  12. More about data types
  13. Library functions
  14. Programming exercise with a library function


  1. Files and directories on a Unix system.
  2. An operating system is a program which runs all the other programs on a computer, manages the computer's memory, etc. The machine you will be using, venus, has an operating system called Unix. You will access venus from personal computers with the operating system Windows.

    Log on to your venus account, as instructed in the Tutorial on SSH, Pine Email, and SFTP.

    A computer stores information in files on a disk. Because a disk may have millions of files on it, the files must be organized somehow, to make them easier to find. Files are organized into directories. A directory can contain both files and other directories. Each user on a Unix system has a home directory containing the files and directories which belong to that user.

    When you are logged on to venus, you should see a prompt somewhat like the following:

    	[username@venus ~]$ 
    

    with your own actual user name in place of "username."

    Next to it, type:

    	pwd
    

    an abbreviation for "present working directory," and then press [Enter]. (You should likewise press [Enter] after all the Unix commands you'll be told about in this and the next section.) Note that Unix is case-sensitive, and the above command must be typed in lower case. The computer will respond with something like this:

    	/home/sp06/111/username
    

    with your actual user name in place of "username." Your user name is the name of your home directory (not to be confused with the directory whose name is "home"). Your present working directory is now your home directory (i.e. the directory whose name is your user name), which is inside another directory with the name 111, which in turn is inside a directory named sp06, which in turn is inside a directory named home, which in turn is inside the root directory, the one big directory which contains all the other directories on the venus's hard disk. (Note again that the directory named home is not your home directory, whose name is your user name.) When you type "pwd," the computer responds with a pathname, indicating the current directory and all the directories which contain it, up to and including the root (which is indicated by the initial slash, rather than by spelling out the word "root").

    As you type various commands, observe the movement of the cursor, which will always be either (1) to the right of the character you typed most recently, or (2) just to the right of the prompt, if you haven't yet typed anything on the current line. If you make a mistake while typing commands, use the [Backspace] key to erase the most recently typed character.

    To see the files and directories in your present working directory, type:

    	ls
    

    (i.e. lowercase L, followed by lowercase S), an abbreviation for "list." If you've completed the first part of the Tutorial on SSH, Pine Email, and SFTP, you should see at least the mail directory that was created when you first used pine.

    Note that the listing is very incomplete. For one thing, it doesn't tell you which of the listed items are files and which are directories. For another, it doesn't list quite all the files. To see a listing of all the files, type:

    	ls -a
    

    where the 'a' stands for "all." You should now see a listing somewhat like the following:

       .             .addressbook.lu   .bash_history  .bashrc  .emacs  mail     .zshrc
       ..            .aspell.en.prepl  .bash_logout   .canna   .gtkrc  Mail
       .addressbook  .aspell.en.pws    .bash_profile  cs111    .kde    .pinerc
    

    (Don't worry if your listing isn't exactly identical to the above.) The files whose names begin with a dot are called hidden files because you don't see them as part of a normal directory listing. They have been put there automatically to enable you to access software on the computer. They are hidden because, normally, you won't be doing anything with them. However, they are very important files, affecting how your account works. Make sure you don't delete those files! Also, you should never modify them until you've become very proficient with Unix.

    But the above listing still doesn't tell you which of the listed items are files and which are directories. To see that, plus some more information about the files and directories, type:

    	ls -la
    

    where the 'l' (that's lower-case 'L', not number '1') stands for "long," and the 'a' stands for "all." You should now see something like:

       total 168
       drwxr-xr-x   6 username group  4096 Feb  1 17:01 .
       drwx--x--x  15 root     root   4096 Jan 25 00:16 ..
       -rw-------   1 username group     0 Jan 30 15:20 .addressbook
       -rw-------   1 username group  2285 Jan 30 15:20 .addressbook.lu
       -rw-------   1 username group    24 Feb  1 17:01 .aspell.en.prepl
       -rw-------   1 username group    21 Feb  1 17:01 .aspell.en.pws
       -rw-------   1 username group   393 Feb  1 17:57 .bash_history
       -rw-r--r--   1 username group    24 Jan 25 00:16 .bash_logout
       -rw-r--r--   1 username group   191 Jan 25 00:16 .bash_profile
       -rw-r--r--   1 username group   134 Jan 25 00:16 .bashrc
       -rw-r--r--   1 username group  5619 Jan 25 00:16 .canna
       drwx------   2 username group  4096 Feb  1 16:59 cs111
       -rw-r--r--   1 username group   438 Jan 25 00:16 .emacs
       -rw-r--r--   1 username group   120 Jan 25 00:16 .gtkrc
       drwx------   3 username group  4096 Jan 25 00:16 .kde
       drwx------   2 username group  4096 Jan 30 15:20 mail
       drwx------   3 username group  4096 Jan 30 15:20 Mail
       -rw-------   1 username group 17180 Feb  1 14:47 .pinerc
       -rw-r--r--   1 username group   658 Jan 25 00:16 .zshrc
    

    The filenames you saw before are now in the rightmost column. To the left of each filename is the date and time when the file was last modified. To the left of the date is the size of the file, in bytes.

    At the extreme left, for each file or directory, is a string of 10 characters which may be 'd', 'r', 'w', 'x', or '-' (hyphen). The leftmost character indicates whether the listed item is a file or a directory, 'd' for "directory" and '-' for "file." The remaining 9 characters are the file permissions, which determine who can access the file or directory, and how. The first three of these 9 characters pertain to the owner of the file or directory (in most cases, the owner is you). The next three characters pertain to the other members of a group of users which includes the owner, and the last three characters pertain to all the other users on the system.

    For each of the three categories of users, the corresponding three characters are as follows: The first character is either 'r' or '-'. If it is 'r', then users in the relevant category can read the file or directory. If it is '-', then they cannot read it. The second character is either 'w' or '-' and determines whether users in the relevant category can write to the file or directory, i.e. modify it. The third character is either 'x' or '-' and determines whether users in the relevant category can execute the file or directory. (If the file is a program, executing it means running the program. In the case of a directory, executing it means accessing files within the directory.)

    Normally, only you should be allowed to write to files in your directory. But it may be necessary to allow other users to read and/or execute at least some of your files and directories, including your home directory. This is necessary if, for example, you have a website. However, you don't want other users to be able to read and execute your homework files or your E-mail. Note that your mail directory has file permissions set so that no one except you (and the system administrator) can access its contents at all. Later, you'll be shown how to create a similarly private directory for your homework.

    Look again at your latest file listing. In the column of filenames at the right, note that the first two listed directories are "." and "..". The single dot stands for the directory whose contents are being listed (in this case, your home directory), and the double dot indicates its parent directory, i.e. the directory which contains the current directory.

    The second column from the left, after the file permissions, indicates the number of files contained in the listed item.. For files, this number is 1. For directories, it may be more than 1.

    The third column from the left indicates the owner of the file or directory. In most cases, the owner is you. The parent directory (..) of your home directory is owned by root, i.e. it is owned by the system administrator.

    The fourth column from the left indicates the group of users to which the owner belongs. As of the time this tutorial was written, it appears that nearly all the users are in one big group called users.

    To see a detailed listing of files and directories other than the normally hidden files, type:

    	ls -l
    

    (i.e. ls followed by a space, then a hyphen, and then another lowercase L). Below, you will sometimes be asked to repeat commands you typed earlier. To save yourself the trouble of typing them all over again, you can use the up-arrow key to repeat previously-typed commands. Pressing the up-arrow key once makes the most recent command reappear. Pressing it again makes the second most recent command appear, and so on. Press [Enter] when the command that you want to repeat reappears. Experiment now with the up-arrow key for a while, and then continue.


  3. Creating directories for your homework.  Create a new directory by typing:

    	mkdir homework
    

    where "mkdir" means "make directory," and "homework" is the name of the new directory you are creating. Then, so that other students can't copy files from your homework directory, type:

    	chmod 700 homework
    

    where "chmod" means "change mode," and the exact significance of the number 700 will be explained at some later time. For now, simply note that the number 700, next to a chmod command, means you are setting permissions so that you can read, write, and execute the indicated file or directory, but that no one else (except the system administrator) can access the file or directory at all. To make sure you've set the permissions correctly, type again (or use the up-arrow to repeat):

    	ls -la
    

    (where, as usual, both instances of the character 'l' are lowercase L, not digit 1). For the new homework directory, the file permissions should be:

    	drwx------
    

    The permissions for all other files and directories should be the same as they were before.

    You now want to work inside your homework directory. Type:

    	cd homework
    

    where "cd" means "change directory." Now type (or repeat):

    	pwd
    

    and observe that your present working directory is now your homework directory, which is inside your home directory (the directory with your user ID as its name). Now type (or repeat):

    	ls -la
    

    and observe that there aren't yet any files in your homework directory. All that's listed, so far, is your current directory (homework), indicated by a single dot in the rightmost column, and its parent directory (your home directory), indicated by the double dot. You are the owner of both these directories.

    Now log out and log back in, as instructed in the Tutorial on Telnet, E-mail, and FTP.

    When you log in, the directory you always access first is your home directory, as you can confirm by typing the pwd command again. To get into your homework directory again, type:

    	cd homework
    

    and then confirm you are there by typing:

    	pwd
    

    Inside your homework directory, it is recommended that you have a separate directory for each homework assignment. For the first week's homework, create a directory named hw01 (that's "hw" followed by the number 1) by typing:

    	mkdir hw01
    

    and then go into it by typing:

    	cd hw01
    

    and then confirm you are there via the pwd command.

    As you change directories, the prompt also changes. On venus, the prompt will contain the name of your present working directory, but not the complete pathname. Other Unix systems may be set up to have different prompts.

    If you need to go back to your home directory for any reason, type:

    	cd ~
    

    where the tilde ('~') indicates your home directory. (To type a tilde, hold down the [Shift] key and press the key at the upper left corner of the main alphanumeric portion of your keyboard.) Then, type the following to get back to the hw01 directory from your home directory:

    	cd homework
    	cd hw01
    

    Later, if you need to take a break before you finish this tutorial, log out and then, after you log back in, type the above pair of cd commands to bet back to your hw01 directory from your home directory.


  4. Preventing interruptions from other venus users.  Preventing interruptions from other venus users. In the next exercise, you will begin learning how to use the vi editor. Before you do so, it is a good idea to type, at the "[username@venus ~]$" prompt:

    	mesg n
    

    This will prevent other users from interrupting your vi session with talk requests and other messages -- which, as you will find out if you allow it, can be extremely annoying.


  5. The vi text editor.  You will now be taught how to use vi, an old text editor program which is much more difficult to learn than most more recent text editors and word processors. If you are accustomed to using a word processor, vi will drive you crazy at first. However, once you do learn vi well, it can be used more efficiently than other editors, and it is available on all Unix systems. And having Unix skills, including vi, will look very good on your resume.

    In your hw01 directory, type:

    	vi practice.txt
    

    to use vi to create a new file practice.txt. (The same command could also open an already-existing file practice.txt, if there were one.) When vi opens, you should see a screen with a column of tildes ('~') down the left, and

    	"practice.txt" [New file]
    

    at the bottom. At the top left corner is the cursor, which indicates where you can begin entering text.

    The vi editor has two modes: (1) text input mode (also known as text entry mode or insert mode), in which you can type text in the file and do only minimal editing, and (2) command mode, in which you do most editing and can move around in the file, save the file, exit the program, etc. When vi first opens, it is in command mode, so you must first go into text input mode before you can put any text in the file. There are several different ways to go into text input mode, from command mode. The most common is to type:

    	i
    

    and do NOT press [Enter]. (Note that vi, like Unix, is case-sensitive, so there is a difference between lower-case i and capital I.)

    If you type i while in command mode, you will immediately go into text input mode. You can now start typing text. In this file, type any text you want. (You may, for example, copy a few paragraphs from this tutorial.) When you reach the end of a paragraph, press [Enter] to go to a new line. If you make a mistake, use the [Delete] or [Backspace] key to erase the most recently typed character. The [Delete] or [Backspace] key won't immediately appear to erase the characters, but the characters will disappear once you type over them with something else.

    However, you cannot use the [Delete] or [Backspace] key to erase any of the line breaks you created by typing [Enter], and you cannot go back and change anything you typed on an earlier line. To do these things, you must leave text input mode and enter command mode. To enter command mode, press the [Esc] key. (If you then press the [Esc] key again, while already in command mode, it will do nothing.

    Once in command mode, it is a good idea to save the file before you do anything else. To save the file, type:

    	:w
    

    and press [Enter]. (Note the colon before the w.) In general, especially if you are doing your homework at home, it is a good idea to get into the habit of saving your work every 15 minutes or so, so that, if your Internet connection is interrupted, or if venus goes down, you will not lose more than 15 minutes' worth of work.

    The above command saves the file and leaves you in vi. To save the file and exit vi, type:

    	:wq
    

    and press [Enter]. (The q stands for "quit".) Or, more briefly, you can type:

    	ZZ
    

    which will save the file and get you out of vi without need to type a colon or press [Enter]. When you leave vi, you will now see the "[username@venus hw01]$" prompt again, which will mean you are now in Unix.

    To get back into vi, editing the file practice.txt again, type:

    	vi practice.txt
    

    When practicing the commands described below, you may occasionally make mistakes and inadvertently do something strange, from which you don't know how to recover. When this happens, make sure you are still in command mode (by pressing [Esc]). Then, type ZZ to save and exit the file, and then come back into vi again.

    It would be nice if vi would tell you whether you are in command mode or text entry/insert mode at any given time, so you don't have to remember which mode it is in. To make it tell you this, type:

    	:set smd
    

    Then, whenever you are in text entry/insert mode, it will say INSERT MODE at the bottom.

    When in command mode, you can move the cursor around by typing the following letters (lower case only). Do NOT press [Enter] after the following:

    h - moves the cursor to the left, one character position
    j - moves the cursor to the down, one line.
    k - moves the cursor to the up, one line.
    l - moves the cursor to the right, one character position

    Note where the keys for these four letters are on your keyboard. They are all together in a row, with h the leftmost and l the rightmost. Use this fact to remember that h moves the cursor to the left, and l moves the cursor to the right. Also, the letter j has a tail hanging down, which you can use to remeber that j moves the cursor down.

    The following commands move the curser more than one character position at a time, or more than one line at a time:

    $ - go to end of current line
    0 - go to beginning of current line
    ^ - go to first nonspace character on current line
    e - move to end of current word
    w - go forward one word
    b - go back one word
    G - Go to last line of file
    nG - Go to line number n (e.g. 4G goes to line number 4, if possible)

    Note that all these commands are case sensitive. In the command nG, do NOT type the letter n but, instead, replace n by the appropriate line number (1, 2, 3, etc).

    Experiment for a while with all the above cursor movement commands.

    Then, try deleting stuff from the file. First, to delete only one character at a time:

    x - delete the character at the current cursor position. (What [Delete] would do in a word processor.)
    X - delete the character before the current cursor position. (What [Backspace] would do.)

    To delete more than one character, use the d command, which can be combined with any of the cursor movement commands to delete text between the current cursor position and the indicated position. For example:

    dw - delete word (i.e. the character at the cursor, and characters to the up to and including the next space)
    db - delete preceding word (i.e. characters left of cursor back to the first beginning-of-word character)
    ndw - delete n words forward (e.g 3dw deletes the current word and 2 more words afterward)
    ndb - delete n words back (e.g. 3db deletes the current word and 2 more words before)
    ndh - delete n characters to the left (e.g. 4dh deletes 4 characters to the left of the cursor)
    ndl - delete n characters to the right (e.g. 4dl deletes the current character and 3 more characters rightward)

    To delete the entire current line, type:

    dd

    To delete a line return, and thereby Join two lines, don't use the d command, but, instead, type:

    J

    with the cursor positioned anywhere on the first of the two lines to be joined.

    After you have deleted most of the file by practicing various ways to delete text, go back into text input mode, so you can type more text. Following are various different ways to go into text input/insert mode:

    i - insert text before current cursor position
    I - Insert text at beginning of current line
    a - append text after current cursor position
    A - Append text at end of current line
    R - Replace or overtype text
    o - open a new line after current line
    O - Open a new line before current line

    Experiment with all the above ways of going into insert mode. Go back and forth between command mode and text entry mode, pressing [Esc] to go into command mode. Each time you go into text entry mode in one of the above-listed ways, type some text and see where it goes. When in command mode, before you go into text entry mode, position the cursor various different places in your text (beginning, middle, and end), to see how this affects what happens when you go into text entry mode via the above commands.

    Another thing you can do in vi is copy and paste. Most copying is done via the y ("yank") command. Like the d command, the y command can be combined with various cursor movement commands to indicate what text is to be copied. For example:

    yw - copy word (i.e. the character at the cursor, and characters to the up to and including the next space)
    yb - copy preceding word (i.e. characters left of cursor back to the first beginning-of-word character)
    nyw - copy n words forward (e.g 3yw copies the current word and 2 more words afterward)
    nyb - copy n words back (e.g. 3yb copies the current word and 2 more words before)

    To copy whole lines, you can use the Y (upper case) instead of y (lower case) command. For example:

    Y - copy current line
    nY - copy n lines (e.g. 5Y copies 5 lines)

    After copying, move the cursor to where you want to paste a copy of the text, and then paste it as follows:

    p - paste copied text after cursor
    P - Paste copied text before cursor

    Practice copying and pasting using all the above variations on the y and Y commands. Then try combining the y command with various other cursor movement commands listed earlier.

    Keep adding more text to the file, either by entering text directly or by copying and pasting, until the file is several screenfulls long. Then try the following additional cursor movement commands, for faster movement up and down:

    ^D - scroll down 13 lines
    n^D - scroll down n lines (e.g. 20^D scrolls down 20 lines)
    ^U - scroll up 13 lines
    n^U - scroll up n lines (e.g. 10^U scrolls up 10 lines)
    ^F - scroll forward one screen
    ^B - scroll back one screen

    ^D is an abbreviation for [Ctrl]-D, meaning that you press the D key while holding down the [Ctrl] (control) key. Do NOT actually type a caret ('^'), and do NOT hold down the [Shift] key as well as the [Ctrl] key. Likewise for the other characters above that are preceded by a caret.

    To go to a particular line within the file, type:

    nZ - go to line n

    typing an actual number in place of n.. Lines are numbered, starting at the top of the file. To see the line numbers displayed, type:

    :set number

    To turn off line numbering, type:

    :set nonumber

    One more very important command is:

    u - undo your most recent change, whatever it may have been

    It is now recommended that you spend at least another few hours just practicing vi, using the file practice.txt, before you go on to use vi to type programs in the other exercises below. Keep practicing vi until your fingers can remember most of the commands quickly and easily. When you are finished, save the file and exit vi.

    For more about the vi editor, see also this other vi tutorial.


  6. Your disk quota, and removing core dumps.  In the next exercise, you will begin typing, compiling, and running C++ programs. Every now and then, you may see an error message that says something like "Disk quota exceeded. Write failed." The message means that your files are taking up more than your allotted share of disk space, and hence you are not allowed to put any new files on the disk.

    When this happens, it may be because some earlier error of yours caused a core dump to be generated. A core dump is a huge file which could help an assembly language programmer diagnose what you did wrong. But, if you are not an assembly language programmer, then a core dump is useless. All it does is take up lots of space on the disk. So, you should delete it.

    To find out whether you generated a core dump, use the ls command to see if there is a file named core. If there is, remove it by typing:

    	rm core
    

    Often when you remove a core dump, there will also be another large file l.out which you should remove also, by typing:

    	rm l.out
    

    (where the 'l' is a lowercase L).


  7. Typing, compiling, and running a C++ program.  In your hw01 directory (which should be inside your homework directory), open a new file hello.cpp in vi by typing:

    	vi hello.cpp
    

    In that file, go into text input mode and type EXACTLY the following C++ program:

       // hello.cpp
    
       #include <iostream>
    
       using namespace std;
    
       int main()
       {
          cout << "Hello, world!" << endl;
          return 0;
       }
    

    Remember that C++, like Unix and vi, is case-sensitive. And be very careful with the punctuation. Do not confuse curly braces, parentheses, and angle brackets! (The word "iostream" is enclosed in angle brackets. To the right of the word "main" is an empty pair of parentheses. On the next line after the main() heading is an opening curly brace. On the last line is a closing curly brace.) Don't forget any of the semicolons! Also, note that the '0' in "return 0" is a zero, not a letter 'O'.

    When you are finished, save the file and exit vi.

    You have typed a program written in C++ source code, a language easily understood by human programmers, but which cannot be understood directly by the machine. Before the program can be run, it must first be compiled, i.e. translated into machine code. Compile it by typing, at the "[username@venus hw01]$" prompt:

       g++ -Wall -s hello.cpp
    

    If you typed the program correctly, you should now see no new messages on your screen other than the next "[username@venus hw01]$" prompt. Anything else you see will mean you didn't type the program correctly, in which case you should go back into vi and carefully triple-check everything including your spelling, capitalization, and punctuation. Make whatever changes are necessary, then save and exit the file, then try to compile it again.

    Note that the compiler's error messages tell you the number of the line on which your error was detected. For example, if you misspelled "iostream" on the 3rd line from the top, you might get an error message like the following, indicating that the error was detected at line 3:

       hello.cpp:3: ioustream: No such file or directory
    

    The vi editor's Z command, which tells it to move the cursor to a particular line, will come in handy here.

    However, the error messages aren't always so clear as to exactly what your error is. If you get an error message you don't understand, don't panic; the compiler might just be thoroughly confused by something so simple as a missing or incorrect punctuation mark. Just inspect the line carefully; and inspect the lines immediately before and after it.

    Unfortunately, the compiler is not very smart, so you should not always take its error messages literally. When the compiler detects an error, it does not know what you were trying to do. It knows only that something does not make sense. Also, it is sometimes off as to where your error occurred. The line on which an error was detected is not necessarily the same line on which the error actually occurred. For example, you might commit a subtle error which looks OK to the compiler but is inconsistent with something else later in the program. The line number in the error message is the line at which the compiler notices that something does not make sense.

    Once you have compiled hello.cpp successfully, use the ls command (lowercase L, followed lowercase S) to observe the presence of a new file a.out -- the machine code file you created by compiling hello.cpp. You can now run the program by typing:

       a.out
    

    All this very simple program does is say, "Hello, world!"

    Now use the ls command to observe not just the presence of your files, but how big they are. Type:

    	ls -l
    

    (i.e. ls followed by a space, then a hyphen, and then another lowercase L). Observe that the machine code file a.out is MUCH bigger than your source code file hello.cpp. Why? Because a.out contains machine code not just for hello.cpp itself, but also for the many things named in the library header file iostream, which you included in hello.cpp.

    Earlier, you were told to compile hello.cpp by typing:

       g++ -Wall -s hello.cpp
    

    You could also have compiled it by typing simply:

       g++ hello.cpp
    

    The -s switch stands for "shrink." Without it, the resulting machine code file would be even bigger, thereby increasing your risk of running out of disk space.

    The -Wall switch stands for "Warnings all," meaning that you are given extra warnings not just for outright syntax errors (which would not allow your program to compile), but also for some things that look like blatantly bad programming practices which don't stop your program from compiling, but are likely to cause run time errors.


  8. Copying files, and more about pathnames.
  9. You will now be asked to copy some files from one of Ms. Nixon's directories to one of your own. Make sure your present working directory is your hw01 directory (inside your homework directory). Then type. at the "[username@venus hw01]$" prompt:

       cp ~nixon/cs111/hw01/* .
    

    (Be sure to include the dot ('.') and the end of the command. The dot should be preceded by a space.)

    The tilde ('~') means that what follows it is the name of someone's home directory, in this case Ms. Nixon's. The nixon directory contains a directory named cs111, which, in turn, contains a directory named hw01. The asterisk ('*') indicates ALL of the files in Ms. Nixon's hw01 directory. The asterisk is followed by a space, which in turn is followed by a dot, which indicates your present working directory (which should be your own hw01 directory). The command tells the Unix operating system to copy all the files from Ms. Nixon's hw01 directory to your present working directory (indicated by the single dot).

    Use the ls command, in your hw01 directory, to verify that you copied the correct files. They should include:

       add2int.cpp
       averageOf3.cpp
       float_types.cpp
       intDivision.cpp
       integer_types.cpp
       mult2float.cpp
       sineDemo.cpp
    

    Note that whenever you use the cp (copy) command, it must always be followed by two pathnames. In the above case, the two pathnames were ~nixon/cs111/hw01/* and the single dot.

    A pathname indicates a file or directory (or a set of files and directories) and how it can be accessed. For example, the pathname ~nixon/cs111/hw01/* indicates all files inside a directory named hw01, which in turn is inside a directory named cs111, which in turn is inside the home directory of user nixon. This pathname starts at nixon's home directory.

    There are two kinds of pathnames: absolute pathnames and relative pathnames.

    An absolute pathname starts at the root directory. For example, when you type the pwd command, the system responds with the absolute pathname of your present working directory, which should now be /usr/users/xyzqc/homework/hw01 if you are user xyzqc.  An absolute pathname always begins with a slash ('/') indicating the root directory.

    A relative pathname starts somewhere other than the root directory. For example, ~nixon/cs111/hw01/* starts at nixon's home directory. Below are some other examples of possible relative pathnames and where they start:

    Pathname What it indicates Where it starts
    ~ Your home directory. Your home directory
    ~/homework

    A directory named
    homework inside
    your home directory.
    Your home directory.

    ~/homework/hw01/hello.cpp





    A file hello.cpp,
    inside directory
    hw01, inside
    directory homework,
    inside your home
    directory.
    Your home directory.





    ./hello.cpp


    A file hello.cpp,
    inside your present
    working directory.
    Your present working
    directory.

    hello.cpp



    A file hello.cpp,
    inside your present
    working directory.
    (Same as above.)
    Your present working
    directory.


    *


    All the files inside
    your present working
    directory.
    Your present working
    directory.

    *.cpp




    All the files, in
    your present working
    directory, which
    have filenames
    ending in .cpp.
    Your present working
    directory.



    keep/my.txt




    A file named my.txt,
    inside a directory
    named keep, inside
    your present working
    directory.
    Your present working
    directory.



    ..


    The parent directory
    of your present
    working directory.
    The parent directory
    of your present
    working directory.
    ../*.txt





    All the files, in the
    parent directory
    of your present
    working directory,
    with filenames
    ending in .txt.
    The parent directory
    of your present
    working directory.



    ../..




    The parent directory
    of the parent
    directory of your
    present working
    directory.
    The parent directory
    of your present
    working directory.


    ../../mail/*






    All the files inside
    a directory named
    mail, inside the
    parent directory of
    the parent directory
    of your present
    working directory.
    The parent directory
    of your present
    working directory.




    (The examples in the above table are presented as illustrations only. You do not need to use them right now. But you should make sure you understand them, in preparation for the first quiz.)

    As mentioned earlier, the cp (copy) command must be followed by two pathnames. Of these two pathnames, the first must be the pathname of either a single file or a set of files (using the '*' in the latter case). If you are using the cp command just to copy one or more files without changing their names, then the second pathname must be the pathname of an already-existing directory into which the files will be copied. The cp command can also be used to copy a file and gove the copy a new name, in which case the second pathname should be the pathname of the new file, with the new filename, inside the target directory.


  10. Some C++ syntax basics.  The simplest possible C++ program would be the following:

       int main()
       {
         return 0;
       }
    

    This program does nothing at all, but contains a few things every C++ program must have.

    Look first at the curly braces. Every C++ program must contain at least one pair of curly braces. A pair of curly braces, usually with stuff in between, is known as a block. Most blocks also have a heading. In this case, the heading is int main().

    Blocks pertain to the ways programs are organized. Large programs MUST be organized somehow. Otherwise, they would be impossible to debug or modify without inadvertent effects on other parts of the program. Large programs are organized into parts that have as little to do with each other as possible, so that one part can be changed without messing up anything else.

    There are many different kinds of blocks. In C++, one of the most important kind of blocks is called a function. Every C++ program must contain at least one function, the main function, which must always have the heading int main or void main.

    A block usually contains one or more statements. If you use the int main heading, then the main function should always end with the statement return 0 (followed by a semicolon). To oversimplify a little, the statement return 0 at the end of the main function is a program's way of saying to the operating system (e.g. to Unix), "I'm finished, and everything is OK."

    The word int next to the word main means that the value following the word return (in the statement return 0) is an integer. You'll learn later in the course why this is necessary.

    Let's now look at another simple program. In your hw01 directory, compile add2int.cpp and run it by typing, at the "[username@venus hw01]$" prompt:

       g++ -Wall -s add2int.cpp
       a.out
    

    When you run this program, it will prompt you to enter two integers. It will then echo the numbers you entered and display their sum. For example, if you entered 4 and 5, the output will be: "4 + 5 = 9."

    Let's now look at the source code. Open the file in vi by typing:

    	vi add2int.cpp
    

    or look at a printout of add2int.cpp.

    Look now at the very first two lines of the program:

       // add2int.cpp
       // Prompts the user for 2 integers and adds them.
    

    The pair of slashes indicate that what follows them, on the rest of that line, is a comment. A comment is not really part of the program and is ignored by the compiler. It is intended to be read by human programmers only.

    Look now at the program itself. Observe the use of cin to do input and cout to do output, using endl to end lines of output. However, cin, cout, and endl are not really part of the C++ language. They are part of the C++ standard library, a collection of code already written by other programmers to make it easier for you to program in C++. By using cin and cout, you save yourself what would otherwise be a lot of complicated work involved in doing input and output.

    Because cin and cout are not part of the C++ language itself, the compiler won't know what they are unless you first tell the preprocessor to insert some information about them that the compiler needs. The following lines of the program tell the preprocessor to insert, at the top of your program, the contents of a header file containing the needed information, before the program is compiled:

       #include <iostream>
    

    In addition, some compilers need you to tell them where to look inside the header file. One way to do this is via a using directive:

       using namespace std;
    

    For more information about the compiler, the preprocessor, header files, the #include preprocessor directive, the using compiler directive, and namespaces, review your lecture notes.

    Our program inputs two integers and then adds them. The addition is done by the following assignment statement:

          sum = addend1 + addend2;
    

    where sum, addend1, and addend2 are variables with integer values, i.e. values stored in memory locations whose contents will be understood by the machine as binary representations of integers. A variable is a name given to a memory location which stores some particular type of data. The variables in our present program store integer values because they have been declared as variables of type int, on the following lines higher up in the program:

          int addend1;      // to be entered by user
          int addend2;      // to be entered by user
          int sum;          // sum of entered numbers
    

    All variables that are used in a C++ program must be declared before they are used. What a variable declaration does is (1) set aside a memory location, of an appropriate size, and give it a name, and (2) let the computer know how the data in that memory location is to be understood (e.g. as an integer, a floating-point number, or a character.)

    Observe the comments next to the variable declarations. It is considered good programming style to put comments near all variable declarations, to explain what the variables will be used for. Comments have no effect on the working of the program. They are intended merely to help you, the programmer, keep track of what you are doing, and to clarify to other human programmers what your program is supposed to do.

    Close vi without modifying add2int.cpp in any way. To quit vi without saving a file, type (in command mode):

    	:q!
    

    and press [Enter].

    Now compile and run another program, mult2float.cpp, and open it in vi. This program is similar to add2int.cpp, except that (1) it uses floating-point numbers (type float) rather than integers (type int), and (2) it multiplies rather than adds them. A variable of type float is the name of a memory location whose contents are understood by the computer in such a way as to accommodate "decimal places" (actually, binary fractional values) rather than just integers. Look at the variable declarations, and look at the assignment statement which does the multiplication. Observe the use of the asterisk ('*') rather than an 'x' as the multiplication operator.


  11. Compiler error message tutorial, and more about elementary C++ syntax.  In this exercise, you will be asked to make a series of deliberate syntax errors into add2int.cpp, to help you get accustomed to the compiler error messages and what they mean. A syntax error is an error which prevents your program from being compiled.

    Rather than mess up the file add2int.cpp itself, let's make another copy of it with a different filename, so that we can deliberately mess up the copy while keeping the original intact. In Unix, type:

    	cp add2int.cpp syntax.cpp
    

    Then open syntax.cpp in vi. The file now open in vi is the duplicate file, syntax.cpp, not the original add2int.cpp.

    You will be asked to make quite a few changes to syntax.cpp, saving and compiling (or trying to compile) after each change. Rather than enter and exit vi repeatedly, you may find it more convenient to be logged in to your venus account via two separate telnet or ssh windows, using one window for editing (via vi) and the other window for compiling and running the program. (If you are using telnet from a DOS window, this will require you to open two separate DOS windows.)

    Whether you use one window or two, always remember to SAVE your file after every change you make, before you try to compile.

    In syntax.cpp, look again at the comments next to the variable declarations. Delete the double slash from in front of one of the comments, so it is no longer invisible to the compiler. Save the program and try to compile it. Observe the resulting error message.

    Don't worry about the details of what this particular error message means, and don't take it too literally. It

    simply means that the compiler is thoroughly confused because you tried to talk to it in ordinary English instead of proper C++. Put the double slash back in, so that the comment is once again invisible to the compiler. Save and compile the file again, and make sure it compiles again (without any error messages) before introducing the next deliberate error. (Make sure you typed the two slashes together, with no space between, and make sure that they are forward slashes (//), not backslashes(\\).)

    If you are unable to restore the file so it compiles correctly, you may create a correctly-working version by saving add2int.cpp as syntax.cpp again, then saving and compiling it.

    Temporarily insert a double slash (//) to the left of the line:

       #include <iostream>
    

    to make it to make it a comment, invisible to the compiler. This is known as commenting out a line, and is often a useful way of experimenting when you aren't sure whether a particular line belongs in your program, but you don't want to outright delete it yet. Save the file and try to compile it. Write down the resulting error message in the space below:

    
    
    
    
    
    
    
    
    
    
    

    (Write the error message using a black ink pen, so you can easily photocopy this and the next few pages, as you will be asked to do when you hand it your homework.)

    This message means that the compiler doesn't know what cout, cin, and endl are, because, without the line "#include <iostream>", the compiler doesn't know where to find cout, cin and endl. Remove the double slash from in front of this line, to make it once again visible to the compiler. Save the file and compile it again. Make sure it compiles (without any error messages) before you continue.

    Look now at the curly braces. In a correctly-written C++ program, every left curly brace must be matched by a

    corresponding right curly brace, and vice versa. Try deleting the right curly brace at the bottom. Save the file and try to compile it. Write the resulting error message below:

    
    
    
    
    

    Then put the right curly brace back where it belongs, and save the program and compile it again. Make sure it compiles correctly before you continue.

    Now comment out (i.e. put a double slash to the left of) the following line:

          int sum;                   // sum of entered numbers
    

    so as to make the entire variable declaration, not just the original comment, invisible to the compiler. Save the file and try to compile it. Write the resulting error message below:

    
    
    
    
    
    
    
    
    
    
    

    The line you commented out is a variable declaration. It declares the variable sum to be of type int. Without this line, the compiler does not recognize the variable name sum when it occurs later in the program. All variables that are used in a C++ program must be declared to be of some particular data type (such int or float) or else the compiler will consider them "undefined."

    You will get a similar error message if a variable name is spelled differently in the variable declaration from the way it is spelled in subsequent statements using the variable.

    Now remove the double slash from in front of this line. Save and compile the file, and make sure it compiles correctly before you continue.

    Now try deleting the semicolon at the end of this same variable declaration you were just now working on (before the comment). Save the program and try to compile it. What error message do you get?

    
    
    
    
    

    Here, your error was on line 11, but was not noticed by the compiler until line 13.

    Almost all statements in a C++ program, including all variable declarations and all assignment statements, must end in a semicolon. Because the declaration "int sum" does not now end in a semicolon, the compiler thinks that's not the end of the statement, and that the "cout <<" on the line below is still part of the same statement. Only when the compiler reaches the first "<" of "<<" does it realize that a statement beginning with "int sum cout <<" does not make any sense, and compiler objects accordingly.

    Put the semicolon back where it belongs. Save the program and compile it again, making sure it compiles correctly before you continue.

    Although almost all lines in a C++ program, including all variable declarations and all assignment statements, must end in a semicolon, there are a few special lines that should NOT end in a semicolon, such the main function heading. Try putting a semicolon after the following line:

            int main()
    

    Save the program and try to compile it. This will result in a very long error message. Don't try to copy the whole thing; just copy the first few lines:

    
    
    
    
    
    
    

    Don't worry about the details of what this means, except to observe that the semicolon has disconnected the main function heading from its function body, which is the block of code beginning with the left curly brace on the next line, up to the first right curly brace. The compiler is now thoroughly confused because that block of code contains quite a few statements which belong inside a function, but which are now seen as not being inside a function.

    Remove the improper semicolon. Save the file and compile it again. Make sure it compiles correctly, and then make sure it runs correctly, too.

    For more information about the basics of C++ syntax, review your lecture notes.


  12. Integer vs. floating-point division .  Compile and run intDivision.cpp. Observe that it does integer division, the kind of division you learned in third grade, before you were taught about fractions. It yields an integer quotient and a remainder. The integer quotient is calculated as follows:

          int quotient = dividend / divisor;
    

    and the remainder is calculated as follows:

          int remainder = dividend % divisor;
    

    The slash ('/') operator indicates division. The percent sign ('%'), when used as an arithmetic operator, indicates the remainder. The remainder operator is also known as the modulus operator, or "mod" for short. As you will see if you continue in computer science, there are still plenty of uses for third-grade-style division in the adult world.

    The division operator ('/') can also do floating-point division, the kind of division you learned later, which may yield a quotient with a fractional part. If the division operator occurs between two values of type int or some other integer data type (char, short, or long), it will do integer division. But, if at least one of the values on either side of the division operator is of a floating-point type (float, double, or long double), then it will do floating-point division.

    In intDivision.cpp, the int variable quotient is declared as part of the same statement in which it is also assigned its first value. Likewise the variable remainder. Variable declarations may be combined with initial assignments in this manner. In all our previous examples, on the other hand, variable declarations and initial assignments were separate statements. Both kinds of variable declarations are allowed, as long as (1) each variable is declared once, and only once, and (2) the variable is declared no later than its first assignment. A variable declaration CANNOT be combined with any statement which uses the variable in any way other than to assign it its first value.

    In our previous example programs, all variables were declared at once, before any other statements in the main function. In older programming languages, such as C, it was required that all local variables (i.e. variables declared inside functions) be declared before all other statements in a function. However, in newer languages like C++ and Java, a local variable can be declared anywhere before the first time that particular variable is otherwise used.

    Some textbooks still use the older style of declaring all variables at the top. And, to this day, some programmers still prefer that style. But, these days, many others feel that it is better programming practice to declare variables as close as possible to where they are used, and no sooner than necessary, as is done in intDivision.cpp.

    If a variable is declared too far in advance of where it is used, this may result in hard-to-debug runtime errors. A variable does not exist before it is declared, and; if a variable does not yet exist at a particular point in the program, then you can't inadvertently do anything wrong with it at that point. (If you do something wrong with a variable before it is declared, you will get a compiler error, which is easier to debug than a runtime error.) Other factors being equal, it is desirable for variables to exist for as short a time as possible, to reduce the number of points in the program at which things can go wrong with them.

    Look now at the comments in intDivision.cpp. Note that, for each variable declaration, there is a relevant comment, though the comments are now above rather than to the right of the variable declarations.

    Quit vi, then compile and run another program, averageOf3.cpp. This program is supposed to average three integers. With inputs 3, 4, and 4, we would expect the result to be 3.66667. But the output is:

       This program averages three integers.
       Enter first integer: 3
       Enter second integer: 4
       Enter third integer: 4
       The average is 3.
    

    Open averageOf3.cpp in vi. The problem, of course, is that the division operator is doing integer division, because it is between two expressions of type int -- even though the result is being assigned to a variable of type float.

    There are two ways we can fix this. One way would be by changing the line:

          float average = (number1 + number2 + number3) / 3;
    

    to:

          float average = (number1 + number2 + number3) / 3.0;
    

    i.e., replacing the int literal 3 with the float literal 3.0, thereby ensuring that we have an expression of type float on at least one side of the division operator.

    Another way to fix it would be to cast the expression (number1 + number2 + number3) to type float, as follows:

          float average = (float)(number1 + number2 + number3) / 3;
    

    Note that a cast is NOT the same thing as a variable declaration. A declaration can be combined with an assignment statement only on the left-hand side of the assignment statement, whereas a cast, if it occurs in an assignment statement, can occur only on the right-hand side. On the left hand side of the above assignment statement, we are declaring the variable average to be of type float, i.e., we are setting aside a memory location, giving it the name average, and informing the computer that the contents of that memory location are to be understood as a binary representation of a floating-point number (which will be stored in a format similar to scientific notation, but using base 2 rather than base 10). On the right-hand side, we are taking the expression (number1 + number2 + number3) -- an expression (not a variable) with a value of type int -- and converting the value of that expression to a value of type float. (If the expression affected by the cast were a single variable, the cast would NOT affect the type of the variable itself, i.e. it would not affect how the contents of the memory location named by the variable are understood by the computer. However, the expression consisting of the cast and the variable would have a value -- stored temporarily in a separate register -- which would have the data type named by the cast.)

    Fix averageOf3.cpp by either one of the above two means. Then save it, compile it, and run it.

    Note the parentheses in the line you fixed. As in algebra, the parentheses are used to make sure the addition happens before the division. Without parentheses, multiplication and division always occur before addition and subtraction.

    Thus, without the parentheses, the statement you fixed would first divide number3 by 3 and then do the additions.


  13. Programming exercise.  Write a program celsiusToFahrenheit.cpp which prompts the user to enter a tempreature, in degrees Celcius and then outputs the temperature in degrees Fahrenheit. (To convert the Celsius temeprature to a Fahrenheit temperature, your program should multiply the Celsius temperature by 9/5 and then add 32.) Use meaningful variable names and user-friendly prompts and output, and use floating-point values for the temperatures.


  14. More about data types.  Different kinds of data are stored in the computer's memory in different ways. For example, an integer is stored differently from a floating-point number.

    In a C++ program, a variable is a name given to a particular memory location. Before any variable can be used, it must be declared to be of a particular data type, so that an appropriate amount of memory will be set aside for the data, and so that the contents of the memory location will be interpreted properly. For example, as explained earlier, the program add2int.cpp declares and uses three variables of type int, which stores integers, whereas the program mult2float.cpp declares and uses three variables of type float, which stores floating-point numbers.

    Absolutely everything in the computer's memory is stored in the form of sequences of 1's and 0's, also known as bits (binary digits). For different data types, the sequences of bits are interpreted in different ways. For example, integers are stored as straightforward binary representations of the numbers, whereas floating-point numbers are stored in a format similar to scientific notation, but using base 2 instead of base 10. Recall that, in scientific notation, a number is written as a mantissa (a number greater than or equal to 1 and less than 10) times a power of 10. For example, the number 1234567890 would be written as:

                        9
         1.23456789 x 10
    

    In the computer's memory, a floating-point number is stored in the form of binary representations of (1) a binary mantissa (a number greater than or equal to 1 and less than 2), (2) a base-2 exponent, and (3) bits for the signs (positive or negative) of both the mantissa and the exponent. (Actually, this is a slight oversimplification. You'll learn more details about the storage of integers and floating-point numbers in a future computer science course.)

    Data types also determine the operations that can be performed on the data. For example, as explained earlier in this tutorial, integer division is different from floating-point division.

    There are two main categories of data types: simple data types and structured data types. A variable of a simple data type stores a single, simple piece of data, such as a single number or character. Structured data types can store more than one piece of data. For example, a string stores a sequence of characters.

    The simple data types can be further categorized as built-in or programmer-defined. The primitive data types are the built-in simple types, as distinct from other simple types that can be defined by the programmer. The primitive data types include (among others) int and float. Each primitive data type can store a particular kind of data (e.g. an integer, a character, or a floating-point number) in a memory location of some particular size.

    There are two major categories of primitive data types: Integer types and floating-point types. As their names suggest, integer types store integers, whereas floating-point types store floating-point numbers. The integer types include (among others) int, long, and short. The floating-point types are float, double, and long double. Within each of these two categories, different data types differ in the sizes of their memory locations, and hence the sizes of the numbers that can be stored in them.

    Type char, which stores characters, is considered an integer type, because the characters are stored in the form of integer codes which are interpreted as characters. The most common character encoding is ASCII (American Standard Code for Information Interchange). More about this later, in section 3.1 of Skansholm.

    Unfortunately, the sizes of the memory locations allocated to each data type vary from one machine to another. For example, type int is traditionally 32 bits on a Unix machine, but 16 bits on a PC. Thus, on a Unix machine the possible int values range from -2147483648 to 2147483647, whereas on a PC they range from only -32768 to 32767.

    On venus (a Unix machine), the integer data types have the following extreme values and memory location sizes:

       Data type                Lowest value         Highest value   Bytes    Bits
    
       int                       -2147483648            2147483647     4       32
       unsigned int                        0            4294967295     4       32
       long             -9223372036854775808   9223372036854775807     8       64
       unsigned long                       0  18446744073709551615     8       64
       short                          -32768                 32767     2       16
       unsigned short                      0                 65535     2       16
       char                             -128                   127     1        8
       signed char                      -128                   127     1        8
       unsigned char                       0                   255     1        8
    

    In the table above, the sizes of the memory locations are given in both bits and bytes. (A byte is 8 bits.) The table was generated by the program integer_types.cpp, details of which will be explained in lecture. (You need not worry about them for now.)

    On venus, the floating-point data types have the following extreme values and memory location sizes. Note that the extreme values are given in e-format, which represents scientific notation. For example, 3.40282e+38 means 3.40282 times 10 to the 38th power, and 1.17549e-38 means 1.17549 times 10 to the negative 38th power.

       Sizes and extreme positive values of the floating point data types:
    
          float:           4 bytes = 32 bits
            Maximum positive value = 3.40282e+38
            Minimum positive value = 1.17549e-38
    
          double:          8 bytes = 64 bits
             Maximum positive value = 1.79769e+308
             Minimum positive value = 2.22507e-308
    
          long double:     8 bytes = 64 bits
             Maximum positive value = 1.79769e+308
             Minimum positive value = 2.22507e-308
    

    (The floating point data types also have similar negative values and zero.)

    The above table was generated by the program float_types.cpp. Note that, on some machines, type long double might have twice as many bits as type long, but such is not the case on venus, on which these two data types are identical.


  15. Library functions.  First, make sure you understand what a function is and what a header file is. Review your lecture notes.

    You will now be shown a complete program example illustrating the use of a library function. Compile sineDemo.cpp and run it. It computes the sine of an angle in radians.

    This program uses a library function, the sin function. In order for the C++ compiler to recognize what the sin function is, you must include the header file cmath, also known in earlier versions of the C++ library as math.h. In sineDemo.cpp, the sin function is called as follows:

       float sine = sin(angle);
    

    where angle is a variable, of type float, holding a value which was input by the program earlier.

    The cmath header file contains prototypes for the sin function. A prototype specifies the data types of both the argument to the function and the value returned by the function. For the example in sineDemo.cpp, the corresponding prototype in the header file looks like this:

       float sin(float x);
    

    The prototype helps the compiler understand the call to the sin function in the program itself.

    The cmath header file contains prototypes for lots of math functions, some of which have multiple versions. To see all these prototypes, let's look at some documentation for the cmath header file.

    The documentation may be found on either the Dinkum site or on cplusplus.com.

    On the Dinkum page, click on "<math.h>" (the old name of <cmath>). Note that the page you will have arrived at is NOT the header file <math.h> itself, but a page of documentation about <math.h>.

    Alas, when the Dinkum <math.h> reference page is accessed too many times in one day, it disappears temporarily and is replaced by an advertisement. So, in case that happens to you, this tutorial will include all the function prototypes you'll need to refer to for the homework. However, please do explore the Dinkum <math.h> reference page if you can, to gain the experience of looking at one of the kinds of reference material that professional programmers use.

    At the top of Dinkum's <math.h> page is a clickable index of names of functions. If you click on sin, you will be taken to a list of prototypes of different versions of the sin (sine) function and some other related functions:</p>

       double sin(double x);
       float sin(float x);  [C++ only]
       long double sin(long double x);  [C++ only]
       float sinf(float x);  [required with C99]
       long double sinl(long double x);  [required with C99]
    

    There are three different versions of the sin function. The first one takes a parameter of type double, the second one takes a parameter of type float, the third one takes a parameter of type long double. The practice of defining more than one version of a function, with the same name but different parameter types, is known as function overloading. C++ allows function overloading. But the older programming language C did NOT allow it, which is why all but one of the three versions of the sin function are marked "C++ only." The header file also contains prototypes for the functions sinf and sinl, which behave exactly the same as the corresponding versions of sin, but have different names, to be backward compatible with C.

    On cplusplus.com's reference page, click on math.h under "C standard library." From this page, you can find information about a given function by clicking on its name. Note that cplusplus.com's reference pages give function headings for only one version (usually the double version of each function, mentioning the other versions only in a note under the heading "Portability.")

    Now use the both the Dinkum and cplusplus.com library reference pages to find prototypes of all these functions: abs, sqrt, pow, exp, log cos, tan, asin, acos and atan. Most of these are on the <math.h> page, but you should also check the page of documentation for <stdlib.h> (the old name of <cstdlib>). Note the different versions of all these functions, differing in their parameter types.

    Then, on scrap paper, practice writing sample calls to these functions, in ways that you might use them in a program.

    Below are prototypes of some of the <math.h> functions that take parameters of type double. (Most of these functions have float and long double versions too.) You may need some of these functions in the homework:

       double acos(double x);           // inverse cosine of x
       double exp(double x);            // e to the x power
       double log(double x);            // natural logarithm of x
       double pow(double x, double y);  // x to the y power
       double pow(double x, int y);     // x to the y power
       double sqrt(double x);           // square root of x
    

    For examples of use of some of these functions, plus prototypes of other versions, see Some of the functions in math.h.


  16. Programming exercise with a library function.  Write a program hypotenuse.cpp which prompts the user to enter the width and height of a right triangle and then outputs the hypotenuse. Use the Pythagorean theorem, and use the library function sqrt to find the needed square root. (According to the Pythagorena theorem, the square of the hypotenuse is equal to the sum of squares of the two other sides.) Use meaningfully-named variables of type double.


Back to: