CIT 593: Intro to Computer Systems Lab #4: Intro to C Programming ...

110 downloads 1344 Views 91KB Size Report
CIT 593: Intro to Computer Systems. Lab #4: Intro to C Programming. Fall 2012. Introduction. This lab serves as a crash course into programming in C. It focuses  ...
CIT 593: Intro to Computer Systems Lab #4: Intro to C Programming Fall 2012 Introduction This lab serves as a crash course into programming in C. It focuses more on the mechanics of writing a C program (i.e., the syntax and semantics) and the UNIX tools that you'll use for subsequent homework assignments.

Tutorial As in Java, Python, etc., a C program is simply a human-readable text file that is then converted (“compiled”) into something executable. In this tutorial, you'll create, compile, and run a simple C program that asks the user to enter two numbers, adds them, and prints the result to the screen. Before typing the program, let’s take a look at it first: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

/* * Program to add two numbers. */ #include #include main() { int num1, num2, sum; printf(“Please enter a number: “); scanf(“%d”, &num1); printf(“Please enter another number: “); scanf(“%d”, &num2); // calculate the sum and print it sum = num1 + num2; printf(“The sum is %d\n“, sum); }

Here’s what’s going on in this program: • Lines 1 – 3 are a multi-line comment. This is text that is ignored by the compiler. It starts with “/*” and finishes with “*/”. It’s good practice to start your program with a comment explaining what it does. • Lines 5 and 6 are used to include other libraries (collections of code) that are used to perform common functions like reading from the keyboard or writing to the display. You will need these two lines in pretty much every C program you write. • Line 8 is the start of the main function, which is the “entry point” or “starting point” of your program. We will see different variants of this line as we go along. • Line 9 is a variable declaration. A variable is a named piece of memory that holds some value

• •

• • • •

as the program executes. When you declare a variable, you specify its name and its type. Here, the type is “int”, meaning a 32-bit signed integer. There are three variables being declared here: “num1”, “num2”, and “sum”. Note that, in C, you must declare a variable before you start using it. Line 11 is a printf statement. It displays the string (collection of characters) in the display. Line 12 is a scanf statement. It reads in a value from the keyboard. In this case, the “%d” means that we intend to read a decimal value (the “d” stands for “decimal”). The “&num1” means that the variable num1 should be set to whatever value is entered from the keyboard. Don’t forget the ampersand (“&”) in front of the variable name! We will discuss that ampersand in more detail later. Lines 14 and 15 are just copies of lines 11-12, except that now we’re getting the second value and putting it in num2. Line 17 is a single-line comment. It starts with “//” and goes to the end of the line. Line 18 is an assignment statement. It assigns the variable sum to the value of num1 + num2. Line 19 is a printf statement but it is slightly different from lines 11 and 14, as you can see. In this case, we want to include the value of the variable sum in our output. So we need to use the “%d” placeholder to hold the value, and we specify the variable sum after the string. Note here that we also use “\n” to display a “newline” character, which is the same as hitting the Enter key.

Task #1: Use emacs (or some other text editor) to create a file named add.c and type in the C program as shown above. Note that the line numbers (on the left) are not part of the program, but are only shown for purposes of the tutorial! Hint: if you start your editor from the command-line, use an ampersand after the command so that you can still use the command-line with the editor open, e.g. “emacs add.c &”. Once you’ve typed the program, be sure to save your work. The next step is to compile the program. Compilation in C is a multi-step process that we will talk about in class later on, but for now suffice it to say that the job of the compiler is to look for errors and, if there are none, to create an executable version of your program. Task #2: Use a console/terminal program to navigate to the directory containing the file add.c. Then invoke the compiler like this: cc –o add add.c You should not see any messages. If you don’t see any messages, then it compiled correctly! The C compiler is not always very friendly, so if you did make a typing mistake in creating your program, it may be a bit difficult to figure out what the compiler error really means. Feel free to ask your neighbor or a member of the instruction staff if you need help. What did we do there, by the way? The C compiler is a program named “cc”, so that’s the command we ran. The “-o add” option means “create an executable named “add”; this is the name of the program that gets created. And “add.c”, of course, is the name of the file containing the C code that you want to compile. Now it’s time to run your program. You can do so just by typing its name, though it’s best to specify

the directory containing your program, in case there are other programs with the same name somewhere else. Task #3: From the console/terminal where you compiled your program, run it using the command: ./add You should be prompted to enter two numbers, and then it should print out their sum. Note that this program should allow for negative numbers, but does not gracefully handle non-integers. That’s okay, we’ll worry about that some other time. Exercises #1 and #2 are for students who are new to C programming. If you have some C experience, you can skip to Exercise #3 and following. Exercise #1 Make a copy of the program above and call it “calculator.c”. Then modify it so that the program prints out the difference, product, quotient, and modulus of num1 and num2, using the operators as follows: operation

operator

example

subtraction

-

a = b – c;

multiplication *

a = b * c;

division

/

a = b / c;

modulo

%

a = b % c;

For the last one, the modulo operation returns the remainder when b is divided by c. For instance, 7 % 3 would return 1, because 7 divided by 3 is “2 remainder 1”. Note also that, when dividing ints as we're doing here, the result will also be an int, so if b is less than c, the result will be 0. After you modify the program, compile and run it. Ask for help if you need it! Exercise #2 Obviously, C supports other data types besides ints, too. In this exercise, you'll modify the program from Exercise #1 so that it uses floating point numbers instead of ints. Make a copy of “calculator.c” and call it “floatcalc.c”. Then modify it as follows: • change the variable declarations to use the float datatype instead of int • change “%d” to “%f” in the scanf and printf statements • comment out the part that uses the modulus function, since it cannot be used for floats Now compile and run your program. When prompted for numbers, enter floating point values (like 1.2345) instead of integers.

Exercise #3 (medium) Write a program that asks the user to enter a floating point number representing the volume of a sphere, and then calculates the radius. As a reminder, the volume of a sphere is V = (4/3)πr3 but keep in mind that you have the volume and need to work backwards to figure out the radius. Don't forget that, if you divide 4/3 you'll get 1, and 3/4 will produce 0, if you use ints; use 4.0 and 3.0 to make sure you divide using floating point numbers Because there is no standard way of representing π in C, you will need to define a constant to represent it in your program. To do this, put the line: #define PI 3.14159 at the top of your program (beneath the include statements). Note that there is no semi-colon in this case! Also, to calculate the cube root, there is a function “cbrt” that you can use if you include the “math.h” library. To do that, include the line: #include with the other include statements. Note that, because math.h is not part of the “standard” C library, when compiling your program, you will need to use the -lm flag. So, assuming your file is called sphere.c, your compile command will be: cc -o sphere -lm sphere.c Exercise #4 (hard) Write a program that asks the user to enter a monetary amount (as a floating point number) and then prints the equivalent amount as a combination of ten dollar bills, dollar bills, quarters, dimes, nickels, and pennies (these values should be integers, of course). Exercise #5 (advanced) Write a program that asks the user to enter an 8-bit unsigned binary integer and then converts it to its decimal (base-10) representation. For instance, if the user enters 01011011, the output should be 91. Your program can assume that the user input is correctly formatted. You should be able to do this without loops or strings, but just by treating the input as a decimal integer and using a combination of the arithmetic operations described above.