1. Introduction Physics 306 Computing Lab 1: Hello, World! In today s lab, you will learn how to write simple programs, to compile them, and to run them. You will learn about input and output, variables, and loops. If you have done computing before, the first couple weeks of the computer lab may be very simple for you. That s fine. In each of sections 3 through 7 below, you will work with variants of a single computer program. As you work each section, print out enough from the program (such as its original code and a copy of its output) to prove that you have done it, or talk to your instructor while in the lab so that he can mark down the fact that you did that part of the experiment. This week, work as far as you can in the writeup in two hours. If you get through it all in less than two hours, you can leave early. We will adjust the content of next week s lab depending on how far people get this week. Working computers can be both incredibly gratifying and incredibly frustrating. The main source of frustration is that a minor error (for example, a missing semi-colon) can cause a program to utterly fail to work, and the computer system will often not give you a clear explanation as to why it is failing. If you find yourself stuck on a point, get help talk to your friends in the class or to your instructor. 2. Setting up the computer We want to jump right in and start writing programs. But first, you need to have a place on the computer to store your work. Check your machine s desktop. If there is not a Physics306 folder, please make one. Make sure there are no spaces in the folder name (i.e., no space between Physics and 306. ) Within the Physics306 folder, make a folder for yourself (e.g., use the name part of your Bryn Mawr or Haverford E-mail address.) Again, make sure there are no spaces in the folder name. To make new folders in the MacOS finder, use shift- -N. 1
3. Hello, world! Start Microsoft Word. Create a new document. Select Tools AutoCorrect..., click on AutoCorrect, and de-select everything. This prevents Word from automatically capitalizing things as you type. Enter the following. It is important to get everything exactly right. #include <stdio.h> int main() { printf("hello, world!\n"); } Select File Save As..., and save the file using name hello.c and format Text Only with Line Breaks. When you specify the format (in the pull-down menu), Word might try to give the file name a.txt extension. Change it back to.c if necessary, so that the file name is hello.c. Save the file in the folder with your name. If Word is not displaying directories, click on the little arrow to the right of the file name in the Save as window, and a directory display will open up. After you click save, Word will give you a warning that formatting information will be lost. Click yes to continue saving the document. Next, start the Terminal program by clicking on the Terminal icon on the dock. It looks like this:. If you don t see this icon, you can run the Terminal program from the Finder. Type shift- -U to go to the Utilities folder, and click on Terminal there. (Note: if you are familiar with the X11 window system, feel free to use xterms with X11 instead of the MacOS Terminal program.) When the terminal pops up, it will display a message similar to this: mathphysics-dhcp174:~/ student$ This is called the prompt. The computer is waiting for you to type something. The prompt lists the computer name ( mathphysics-dhcp174 in this example). Although not yet obvious, the prompt also tells you which folder you are working in. Type cd Desktop/Physics306/myname, replacing myname with the name of the folder you created earlier. Whenever you type something like this, press return when you are done. You are now working within the folder you made on the desktop. We will usually use the word directory instead of folder, but they mean the same thing. Notice that the prompt has changed to reflect the new directory name. You can type pwd to see which directory you are working in. Type ls to list the files in the directory. There should be just a single file, hello.c, which you created a few minutes ago. 2
You are now ready to compile and run this program. Type gcc -o hello hello.c. If the computer prints error messages, then there is something wrong with your hello.c program. Double-check that it looks exactly like the listing above. If you can t find any problems, but you continue to get error messages, talk to your instructor. Type ls again. Now, in addition to hello.c, there is a second file, called hello. This file contains the actual computer instructions needed to execute the commands listed in hello.c. In other words, it is a computer program which you can run. Type./hello. (Notice the sequence: period, slash, hello.) The hello program will run and print out a message. If it does not do so, double check your program again. If you can t get it to work, ask for help. There are a number of lines in your short hello.c program which probably just look like gibberish, but it should be clear which part of the program is responsible for writing out the hello message. We ll talk about the rest of the gibberish on some other day. Modify the code to print out your name or the name of your pet fish or the name of your favorite math theorem. What s that \n thing in the program? Try leaving out the \n. What happens? What happens if you put an extra \n into the program, for example, hello\n, world!\n? Try it! There are other things you might try: \t, \b, \a. Instead of having the program s output be written to the terminal screen, you can have it saved in a file. Run./hello > a.txt. Nothing is displayed on the screen when you run this. Type ls and you will see that there is a new file, a.txt, in the directory. You could look at this file with a standard text editor like Word or TextEdit. Or, you can write it to the screen by typing cat a.txt. In fact, you can write any file to the screen. Try typing cat hello.c. To print any of these files, you can open them in Word or TextEdit and use the print ( -P) command. Or, in terminal, you can type, for example, lpr xyz.txt where xyz.txt is the name of the file. At the moment, it seems that the computers are set up to print to the printer in the computer lab, but sometimes they request the wrong paper tray. You may have to walk over to the printer and hit the checkmark button on the printer to get it to behave. 3
4. Arithmetic Time for another program. Use Word to enter the following. Give it a new name, such as multiply.c. If you would rather use a different editor (like MacOS s TextEdit, or the Unix editors vi or emacs), that s great. If you are going to do a lot of programming, you should learn to use vi or emacs. But please leave that for another day and get back to typing the following code into the computer. #include <stdio.h> int main() { int a, b, c; printf("type two numbers separated by a space:\n"); scanf("%d %d",&a,&b); c = a * b; } printf("the product of %d and %d is %d\n",a,b,c); Compile this and run it in the same way as you ran the hello program. When you type gcc -o multiply multiply.c, what you are doing is telling the computer to compile your program (i.e., to turn it into something the computer can run). The original file, that you wrote, is called the source code, and the runnable program produced by the compiler is called the executable or the binary file. The gcc command tells the compiler to put the executable into a new file called multiply. You can call the executable anything you wish; just change what is after the -o in the gcc command. You can also leave out the -o part entirely, and just write gcc multiply.c. What is the executable called in this case? Try it and see. By the way, the computer language you are using is called C. Our use of C is a somewhat arbitrary choice. Many computer languages would be capable of doing the work we want to do. What you learn using C you can easily apply to other languages. The C complier is, confusingly, called gcc. In MacOS (and many other systems), you can type cc instead of gcc, and the computer will run the same compiler. Different computers have different C compilers. The gcc compiler is very commonly used on MacOS, Linux, and other Unix-based computer systems. When you put.c at the end of a file name, that tells the compiler that it is a C program. Getting back to your program, once you ve convinced yourself that it works, change it to divide a by b instead of multiplying them together. Compile the program and try it out. What happens if you try to divide 10 by 3? Hmmm, looks like the program 4
only understands integers. Could that word int in the program have something to do with this? Try changing int a, b, c; to float a, b, c;, and change the characters %d to %f (in four separate places ). What happens? The process of defining a variable to be int or float or something else is called declaring the variable. Every variable you use must be declared before you use it. By now you will have noticed that every statement (that is, every command within a program) ends with a semi-colon. The only exception is the first line, which starts with a pound sign, #. The use of semi-colons to separate one statement from the next is a feature of many (but by no means all) computer languages. Ends of lines have no significance in C. You can put a single statement on multiple lines, for example: c = a * b; And you can put multiple commands on a single line: printf("type two numbers:\n"); scanf("%d %d",&a,&b); c=a*b; What s going on in the printf and scanf lines? Technically, these are both C functions. Among other things, this means that, in a program, they are always followed by something in parenthesis. In fact, it is common to call these functions printf() and scanf(). The parentheses are included in the names, even in casual conversation. (How do you pronounce punctuation marks? Look up Victor Borge phonetic punctuation on YouTube. But wait until after lab to do that.) So, what does printf() do? As you have gathered by now, printf() prints things out, that is, it writes them to the screen. Writing a bunch of letters to the screen is straightforward: printf("salut le Monde!\n"); The thing inside the quotation marks is called a format string. If you want to print an integer variable, put the characters %d in the format string, and list the variable name after the string: int a; a = 7; printf("my favorite number is %d.\n", a); If you want to print out more than one variable, put more than one %d in the format string: int a, b; a = 7; b = 3; printf("my favorite number is %d, but I also like %d.\n", a, b); You can print the same variable more than once: 5
int a; a = 7; printf("i love %d! %d is my favorite! %d! %d! %d!\n",a,a,a,a,a); To print a floating point number, use %f instead of %d : float a; a = 7.543; printf("personally, I prefer %f. I love decimals.\n",a); Printing both integers and floats is no problem: printf() function call: float a; int b; a = 7.543; b = 7; printf("the best is %f, but %d is also pretty good.\n",a,b); There are many, many other features of printf(). We ll talk about the some other time. The scanf() function is more-or-less the opposite of the printf() function. It takes one line of input from the keyboard and stores whatever is typed there into one or more variables: int a, b; float c; printf("type two integers separated by a space:\n"); scanf("%d %d",&a,&b); printf("now type in a floating point number:\n"); scanf("%f",&c); Note the peculiarity that you need to put & before the variable name in a scanf() function call. We ll talk about why that is at some later date. Are you tired of typing./ every time you run a command? In your terminal, type the following: echo $PATH. If you run a program like multiply without specifying which directory it is in, the computer will search all the directories listed in $PATH. The directory in which you are currently working is not on that list, so you have to specify it manually. That s what the./ is all about. The period means the current working directory. To add it to the path, do the following: PATH=.:$PATH. Now you can simply type multiply without the period and slash. You ll probably want to make this change to $PATH every time you start a terminal. 6
5. Going for a loop Now try this: #include <stdio.h> int main() { int i; float pi; float a; pi = 3.14159265; } for (i=0; i<10; i++) { a = i*pi; printf ("%d times pi is approximately %f\n",i,a); } Compile and run this program. The program executes the same statements ten times, each time with a different value of i, starting at 0 and going as high as 9. This sort of thing is called a loop. In this program, i starts off at 0 (i=0), it is incremented by one each time the loop is run (i++), and it runs as long as i is less than 10 (i<10). The ten passes through the loop are called iterations of the loop, and i is called the loop index. The code that is run ten times is enclosed by brackets after the for command. 6. A variable-length loop Modify the above program so that it asks the user how many iterations he or she wants, and sets the upper limit of i to that value. You will need to add a new variable to the program to do this. If have trouble figuring out how to do this, ask someone for help. If you do something wrong and your program looks like it will run forever, type ctrl-c to stop it. 7. Factorial; how big can an integer be? You know that the a factorial, often written a!, is the product of the integers from 1 thorough a. So, for instance, 5! = 1 2 3 4 5 = 120. 7
Write a program which uses a loop to calculate the factorial of some number (we ll call it n). Do this by declaring a variable n, initially setting it to 1, and then multiplying it by the loop index in each iteration through the loop. Do everything with integers. Once you ve gotten that working, see how high a number you can calculate before problems start arising. There is a maximum value which integer numbers in this implementation of C are allowed to have. If you try to make a larger integer, strange things can happen. Explore! That s enough for today!.... Note: The idea of starting programming by writing a Hello, world program was popularized in the classic text The C Programming Language by Brian Kerninghan and Dennis Richie. It has become the de facto standard first program to write when learning any computer language. For more about this program, check out the Hello world program entry in Wikipedia. 8