Simple C Programming -------------------- The simplest form of a C program, as previous discussed is: main() { program goes here } Let's look at a few new statements. The printf() Function --------------------- The printf() function is one of the most popular and useful PREWRITTEN functions in C. This is a function as denoted by the parenthesis and the name format being a legal function name. This function has already been created by someone else and is included in a library of other functions which you can use in writing your programs. This is done by finding the particular library that the printf() function is in and using a preprocessor command to include it. This is done like this: #include All preprocessor commands must come before the main() function in a C program. Here is the format of the predefined printf() function: printf(arguments) NOTE: Now, instead of nothing between the parenthesis, as in printf(), arguments may be used. These arguments are similar to those used in C shell programming. In this case, the function printf() requires only 1 argument and that happens to be a string of characters. Here is an example: printf("hi there."); This line calls the function printf() with the argument "hi there." When this line is executed, the words "hi there." are displayed on the screen. NOTE: A semicolon is required after each statement in the C language. Program 1-1 ----------- #include main() { printf("Hello there world!"); } The output is: Hello there world! This displays the message "Hello there world!" to the screen. The library that the printf() function comes from is called "stdio.h". It is referenced using a preprocessing command of the form "#include". #include is required when the function printf() is to be used. The ".h" extension is used to denote a "header" file. The term "header"is used because preprocessor commands such as "#include<>" appear only in the header portion of a C program. What is a string? A string is a sequence of characters made up of letters, digits and special characters such as ! @ $ etc... . Additional characters include carriage return (equivalent to the ENTER or RETURN key on the keyboard) and tab key, are denoted in the printf() function as follows: \n new line \t tab Here is an example: Program 1-2 ----------- #include main() { printf("Computers, computers everywhere"); printf("\n as far as I can C"); } The output is: Computers, computers everywhere as far as I can C Note: The "\n" forced the output to continue on the next line down and the first word "as" started 3 spaces in from the left margin. Remember to include the semicolons at the end of each instruction. Here is another example: #include main() { printf("What the **** is C anyway?"); printf("A language.\n\nSo there!"); } The output is: What the **** is C anyway?A language. So there! Do you see why the second output was appended to the first? A "\n" is required to go to the next line. Then two "\n"'s were used forcing the output to go down two lines. Please type in these examples - then compile and execute them. Once again, this may be done, as for the example above, as follows: 1. vi prog.c - Type in the program, save it, and exit the editor. 2. cc prog.c -o prog or gcc prog.c -o prog to complie the program 3. prog will execute the program "prog" You should get the output shown above. If not, recheck your typing and try again. To demonstrate the tab key or "\t" used in the printf() function, we will work through Problem 1a of Exercises 1.3 on Page 22 of the book. Problem 1a ---------- Use the printf() function to write a C program that prints your name on one line, your street address on a second line and your city, state and zip code on the third line. #include main() { /* We will also use the tab "\t" in this example */ /* note that comments in C are written between these */ /* slashes with an asterisk. */ printf("\tDr. Bruce McCormick\n"); printf("\t333 Park Avenue\n"); printf("\tNY, NY 10023\n"); } The output is: Dr. Bruce McCormick 333 Park Avenue NY, NY 10023 Note: The text is tab'd in. Programming Style ----------------- Style is important in programming to aid you and reader's of your source code and for debugging purposes. As you develop larger and larger programs, segments of your code will tend to grow large and can get very messy. This can make your life difficult when trying to fix an error. The use of programming "style" can help! The sample program's we have seen may be written in several different forms. For example: #include main() { printf("hi"); } May also be rewritten as: #include main ( ) { printf("hi"); } This second program will work, but it is not easy to look at and understand. There are good reasons for lining up parentheses and squiggly brackets. Look at this example: main() { if(blah) { if(blah) { if(blah) { some code here } } } } This program fragment illustrates nesting of commands. When nesting is used, there may be many matching brackets. If you don't line them up, open bracket above close brack, then you will have trouble matching them and may forget to put a needed one in. Just like "endif" statements in C shell scripting--it can be very easy to forget one. Programming style is important! It can help you finish your assignments more quickly. Here are some style guidelines for C programs: 1. C ignores all white space. 2. Line up matching brackets in the same column. 3. Indent consistently, 2 spaces recommended. 4. Put in comments to aid in reading and understanding your program. Remember that other people may need to look at your programs. Comments are placed in /* */ brackets. EX: /* this is a comment */ Note: Anything placed in comment brackets has no effect on the program execution--comments are ignored by the compiler. Comment Example --------------- /* This is a comment. /* so is this */ */ What is wrong with this example? You cannot nest comments as shown above. Once you start a comment with "/*" you can only close it with "*/". However, you can make a comment continue over more than one line: /* this is a comment. So there, you loser!!! */ Here is good use of a comment at the beginning of a program. /* program1.c written by Joe the Ripper This program shows you how to rip one. har har har */ #include main() { printf("Rip it good!\n"); } Top-Down Program Development ---------------------------- The 5 steps in the top-down development procedure are: 1. Determine the desired outputs. 2. Determine the input data. 3. Design the program: a. Select an algorithm transforming the input to the output. b. Check the chosen algorithm by hand using the input. 4. Code the algorithm into C. 5. Test the program using test input data. Example Programming Problem Using the 5 Steps Above --------------------------------------------------- Find the circumference of a circle given the radius as input. 1. The output is the circumference of the circle. 2. The input is the radius. 3a. Algorithm i. Assign some specific value to the radius. ii. Compute the circumference using C = 2 pi r iii. Output the result. 4. /* circumference.c This computes the circumference of a circle given a specificc radius. */ #include main() { float r = 3.0; float c; float pi = 3.14159; /* compute the circumference */ c = 2 * pi * r; /* output the circumference */ printf("The circumference is %f\n",c); } 5. Test the program by compiling it and executing it with test data. The output should be: The circumference is 18.849541 In this example we see a few new program statements. Refer to program 1-4, in the book on page 30, which is very similar. These examples introduce variables (you have seen them in C shell scripting), data types, and operators. Each variable needs to have a data type associated with it. These may be one of the following simple types: int integers float real numbers char characters double higher precision real numbers Examples of the simple data types: integers : 1, 3, -10, +200, -33 real numbers : +1.0, 3.14159, -9.33, 10.22334 characters : 'a', '#', 'H', ')' double : 1.2332323232323 -333.444455555666 Examples of invalid integer data types: $255.62 2,534 3. +6.0 Examples of invalid floating point and double precision numbers: 5,234.25 24 123 6,549 $10.29 Notice in both case that commas and the dollar sign are illegal. The decimal point is illegal in the case of integer values. The compile may not give you an error in all cases. It might just convert the number 24 in the case of floating point to 24.0 Examples of exponential notation: 1.33e-3 This is 0.00133 34.9e10 This is 349000000000 7.31e-4 This is 0.000731 For the data type double, precision is dependent on the machine. UNIX machines, in general, have high double precision (typically 64 bits). Examples simple data types in C: int i = 10; int j,k,blue; float a,b=4.15e-5; double f=1.23334455; char t='f'; char u; These data type declarations may go in the beginning of each C function or may be globally declared at the beginning of a C program. Look at the example program again. The first 3 lines after main() { contain variable declarations. The first line float r = 3.0; declares the variable named "r" and assigns it a value of 3.0. The second line float c; declares the variable named "c" and does not assign it a value. The third line float pi = 3.14159; declares the variable named "pi" and assigns it the value 3.14159. All of these variables are of type "float" which means they are real numbers. If we assigned 3.14159 to an integer variable, what do you think might happen? It will store only the integer part which is equal to 3 . So the following declaration for pi: int pi = 3.14159; is not good, since the value of pi will be only be 3, not 3.14159. pi needs to be assigned to a float data type. Look at the computation of the circumference. This should look familiar from C shell scripting. The line c = 2 * pi * r; simply computes the value of 2 times pi times r and assigns it to the variable called c. The circumference may be output to the screen. This is done using the printf() function. Note that there is a new usage in the command, The variable c is listed after the quoted string part. printf("The circumference is %f\n",c); The "%f" part in the quotes means print the value of the following float variable at this location in the output string. Look at another few examples: printf("The value of x is %f\n",x); If x's value is 3.45667 then the output is: The value of x is 3.45667 Here is another example: printf("The coordinate is (%d,%d)\n",x,y); In this case "%d" is used. This indicates that integer values will be output. If x = 4 and y = 8, then the output will be: The coordinate is (4,8) So in review: %f prints a float value %d prints a integer value %c printf a character value Common Programming Errors ------------------------- 1. Omitting the parentheses after main. 2. Omitting or incorrectly typing the opening brace { that signifies the start of a function. 3. Omitting or incorrectly typing the closing brace } that signifies the end of a function. 4. Misspelling the name of a pre-defined function; for example, typing print() instead of printf(). 5. Forgetting to close the printf() message string with a double quote symbol. 6. Omitting the semicolon after each statement. 7. Forgetting the "\n" to indicate a output new line. Escape Sequences ---------------- \b move back one space \f move to next page \n move to next line \r carriage return \t move to next tab setting \\ backslash character \' single quote \" double quote \nnn treat nnn as an octal number Example usage of these are: printf("Hi\nthere"); which outputs: Hi there printf("hi there\b\b\b\b\bdude.\n"); which amazingly outputs: hi dude. The "\b" works much like a typewriter backspace and goes back over what was already printed out to the screen. Arithmetic Operators -------------------- Operations Operator -------------------------------- Addition + Subtraction - Multiplication * Division / Remainder % Negation - Examples of Arithmetic Operations --------------------------------- 3 + 7 18 - 3 12.62 + 9.8 .08 * 12.2 12.6 / 2. -9 9 % 4 The examples above in order are described: the result of 3 + 7 is 10 is integer addition the result of 18 -3 is 15 is integer subtraction the result of 12.62 + 9.8 is 22.42 in floating point addition the ruselt of .08 * 12.2 is .976 in floating point multiplication the result of 12.6 / 2. is 6.3 in floating point division the result od -9 is -9 in negation the result of 9 % 4 is 1 in integer division remainder (9/4=2 rem=1) Rules for Arithmetic -------------------- 1. If all operands are integers, the result is an integer. 2. If any operand is a floating point or double precision value, the result is a double precision number. Operator Precedence and Associativity ------------------------------------- 0. () left to right 1. negation (unary -) right to left 2. * / % left to right 3. + - left to right Example of Precedence --------------------- 8 + 5 * 7 % 2 * 4 Step 0. No ()'s. Step 1. No negation. Step 2. Left to Right either * or / or % 8 + 35 % 2 * 4 Step 2. Left to Right either * or / or % 8 + 1 * 4 Step 2. Left to Right either * or / or % 8 + 4 Step 3. Left to Right either + or - 12 Refer to page 46 in the book.