990 likes | 1.08k Views
Introduction to C. Doug Sondak SCV sondak@bu.edu. Outline. Goals Introduction Emacs C History Basic syntax makefiles Additional syntax . Goals. To be able to write simple C programs To be able to understand and modify existing C code
E N D
Introduction to C Doug Sondak SCV sondak@bu.edu
Outline • Goals • Introduction • Emacs • C History • Basic syntax • makefiles • Additional syntax
Goals • To be able to write simple C programs • To be able to understand and modify existing C code • To be able to manage program projects using an editor and makefile
Introduction • Matlab is great! Why do I need to learn a new language?! • All codes must be translated to machine language • Interpreted language • Matlab, Python, Java • Translation is performed incrementally at run time • Compiled language • Fortran, C, C++ • Translation is performed once, then executable is run
Introduction (cont’d) • Compiled languages run faster • I translated a program from Matlab to C for a user, and it ran 7 times as fast • Large-scale computing is usually done with compiled language • Some convenient features of interpreted languages result in performance and/or memory penalties
Emacs • On Unix systems, one typically uses an editor to write/modify code • Emacs and vi are most popular • We will talk about emacs • If you want to use vi, that’s fine
Emacs (cont’d) • Emacs is a wonder tool! • We will just scratch the surface • Commands can be executed via menus or using the underlying character sequences • Although I like the latter, we’ll use the menus here • Copy the file “junk” from /scratch/sondak • This will be our example file for editing cp /scratch/sondak/junk .
Emacs Exercise • Type “emacs” • An emacs window will appear • To read an existing file File -> Open File… • You will be prompted for file name at bottom of window • Type “junk” and hit return
Emacs Exercise (cont’d) • You should now see file contents in window • can navigate using arrow keys • You can also navigate by clicking on the desired location • Click on the 0 in 0.282
Emacs Exercise (3) • To delete a character use Delete button • Hit Delete 3 times to delete 0.2 • Type 1.3 • You’ve now changed 0.282 to 1.382 • Highlight 0.288 with the mouse • Don’t include spaces before or after • Edit -> Cut will delete the highlighted characters • Oh no, we made a mistake! Edit -> Undo undoes the previous command. Try it; 0.288 should reappear.
Emacs Exercise (4) • The point is the location on the left side of the cursor; i.e., between the character on which the cursor resides and the character to its left. • The mark is similar to the point, but it’s location is set (i.e., doesn’t move with cursor). • Suppose we want to delete all the characters between (inclusively) 0.288 and 0.407.
Emacs Exercise (5) • Set the cursor on the 0 in 0.288. • To set the mark, CTL-spacebar • The note “Mark set” will appear at the bottom of the screen. • Move the cursor to the right of 0.407 • We place it to the right of the 7 rather than on it because the point is always to the left of the cursor
Emacs Exercise (6) • Edit -> Cut will delete all characters between the mark and the point • For now, let’s put the characters back in by using Edit -> Undo • Move the cursor to the start of the current line using CTL-a • (CTL-e moves to end of current line) • Delete (“kill”) the line with CTL-k • Another CTL-k deletes the newline character
Emacs Exercise (7) • “Meta” key is the Esc key • We will use M here to indicate the Meta key • The Meta key is hit prior to the subsequent key(s), not simultaneously as with CTL • Place the cursor at the top of the file • M-> will move the cursor to the bottom of the file • M-< will move it back to the top
Emacs Exercise (8) • Whatever we deleted last is available in a buffer • Move the cursor to the beginning of the “M1rel” line • CTL-y “yanks” the current buffer
Emacs Exercise (9) • To save the modified file, File -> Save (current buffer) • A note will appear at the bottom of the window saying the file has been saved • To save it under a new name, File -> Save Buffer As… • You’ll be prompted for the name at the bottom of the screen • Note that when you get these kinds of prompts, you can edit them using emacs commands • Type a file name and then move back and forth with CTL-b and CTL-f • File -> Exit Emacsto quit • Previous version will appear with ~ suffix
Emacs Exercise (10) • A built-in tutorial is available • Type CTL-h t • We won’t do anything with the tutorial here, but it’s a good resource
C History • Developed by Dennis Ritchie at Bell Labs in 1972 • Originally designed for system software • Impetus was porting of Unix to a DEC PDP-11 • PDP-11 had 24kB main memory! • 1978 book “The C Programming Language” by Kernighan & Ritchie served as standard • Official ANSI standard published in 1989 • Updated in 1999
C Syntax • Source lines end with semicolons (as in Matlab) • Case-sensitive • Spaces don’t matter except within literal character strings • I use them liberally to make code easy to read • Comments are enclosed by /* */ • Many compilers also accept // at beginning of comment as in C++
C Syntax (cont’d) • Declarations – must declare each variable as being integer, floating-point, character, etc. • Required because different types are represented differently internally • Since integers have no decimal places, integer arithmetic will truncate result • If i=3 and k=2, i/k=1, k/i=0 • Program blocks are enclosed within { } • Source file suffix is usually .c
C Syntax (3) • Simple programs consist of functions and header files • Main program is a function called main (surprise!) • Functions have return types (int, float, etc.) • Main function is defined by the return type, the word main followed by any arguments within parenthesis, followed by the function statements within {} int main(){ function statements }
C Syntax (4) • Style note: some people like to arrange the brackets like int main() { function statements } • Either way is fine • Be consistent!
C Syntax (5) • Header files contain re-usable code elements • Function definitions, variable declarations, etc. • Sometimes use system header files • Sometimes you write them yourself • Usually have a .h suffix #include <header_file_name.h> • Included before function definition • Note that the #include statement does not end with a ;
C Syntax (6) • A character string is enclosed by double quotes • Characters within the quotes will be taken literally “This is my character string.” • Special character \n produces new line (carriage return & line feed) • Often used in character strings “This is my character string.\n” • Single character is enclosed in single quotes ‘h’
C Syntax (7) • Functions are executed by statements that consist of the function name, any required arguments within (), and the ending ; myfunc(arg1, arg2); • The function printf can take a character string as an argument and print the string to the screen printf(“mystring\n”); • Definition of printf is in the include file stdio.h
Exercise 1 • Write a “hello world” program in an editor • Program should print a character string • General structure of code: • include stdio.h • define main function • call printf function • Save it to a file name with a .c suffix (e.g., hello.c) • solution
Compilation • A compiler is a program that reads source code and converts it to a form usable by the computer • Code compiled for a given type of processor will not generally run on other types • AMD and Intel are compatible • On katana we have Portland Group compilers (pgcc) and GNU compilers (gcc) • We’ll use gcc, since it’s free and ubiquitous
Compilation (cont’d) • Compilers have huge numbers of options • See gcc compiler documentation at http://gcc.gnu.org/onlinedocs/ • Katana presently has version 4.1.1 • For now, we will simply use the –o option, which allows you to specify the name of the resulting executable • In a Unix window: gcc –o hello hello.c
Compilation (3) • Compile your code • If it simply returns a Unix prompt it worked • If you get error messages, read them carefully and see if you can fix the source code and re-compile • Once it compiles correctly, type the executable name at the Unix prompt, and it will print your string
Declarations • Lists of variables with their associated types • Placed in source code at beginning of function • Basic types: • int • Usually 4 bytes • float • Usually 4 bytes • double • Usually 8 bytes • char • Single character • One byte
Declarations (cont’d) • Examples: inti, j, k; float xval, time; char name, date; • A “char” variable represents a single character
Arithmetic • +, -, *, / • No power operator (see next bullet) • Math functions in math.h • pow(x,y) raises x to the y power • sin, acos, tanh, exp, sqrt, etc. • add –lm flag to compile command to access math library • Exponential notation indicated by letter “e” 4.2e3 • Goodpractice to use decimal points with floats, e.g., x = 1.0 rather than x = 1
Arithmetic (cont’d) • ++ and -- operators • these are equivalent: i = i+1; i++; • always increment/decrement by 1 • Can convert types with cast operator float xval; inti; xval = (float) i;
Printing Values • printf will print values as well as character strings • Must provide format for each value int num; float x; printf(“num = %d x = %f \n”, num, x); • %d is integer conversion specification (format) • %f is float conversion specification • Formats correspond to variable list • I sometimes line them up for clarity: printf(“num = %d x = %f \n”, num, x );
Exercise 2 • Write program to convert a Celcius temperature to Fahrenheit and print the result. • Hard-wire the Celcius value to 100.0 • We’ll make it an input value in a subsequent exercise • Don’t forget to declare all variables F = (9/5)C + 32 • solution
Pointers • Memory is organized in units of words • Word size is architecture-dependent • Pentium 4 bytes • Xeon, Itanium 8 bytes • Each word has a numerical address 32 16 8 0
Pointers (cont’d) • When you declare a variable, a location of appropriate size is reserved in memory • When you set its value, the value is placed in that memory location 32 float x; 3.2 x = 3.2; 16 8 0 address
Pointers (3) • A pointer is a variable containing a memory address • Declared using * prefix float *p; • Address operator & • Address of specified variable float x, *p; p = &x;
Pointers (4) float x, *p; p = &x; 1056 32 p 1052 16 16 1048 8 1040 0 address address
Pointers (5) • Depending on context, * can also be the dereferencing operator • Value stored in memory location pointed to by specified pointer *p = 3.2; • Common newbie error float *p; *p = 3.2; float x, *p; p = &x; *p = 3.2; Wrong! – p doesn’t have value yet correct
Arrays • Can declare arrays using [ ] float x[100]; char a[25]; • Array indices start at zero • Declaration of x above creates locations for x[0] through x[99] • Array name is actually a pointer to the memory location of the first element • These are equivalent: x[0] = 4.53; *x = 4.53;
Arrays (cont’d) • If p is a pointer and n is an integer, the syntax p+nmeans to advance the pointer by n memory locations • These are therefore equivalent: x[4] = 4.53; *(x+4) = 4.53;
Arrays (3) • Multiple-dimension arrays are declared as follows: int a[10][20]; • Values are stored in memory with last index varying most rapidly • Opposite of Matlab and Fortran • The statements in each box are equivalent: a[0][17] = 1; a[1][0] = 5; *(a+17) = 1; *(a+20) = 5;
Arrays (4) • Character strings (char arrays) always end with the character \0 • You usually don’t have to worry about it as long as you dimension the string 1 larger than the length of the required string char name[5]; name = “Fred”; char name[4]; name = “Fred”; works doesn’t work
sizeof • Some C functions require size of something in bytes • A useful function – sizeof(arg) • The argument arg can be a variable, an array name, a type • Returns no. bytes in arg float x, y[5]; sizeof(x) ( 4) sizeof(y) (20) sizeof(float) ( 4)
Input from Keyboard • fgets reads a character string (character array) char line[100]; fgets(line, sizeof(line), stdin); • 2nd argument is no. bytes to read • lives in stdio.h • sscanf“decodes” a character string according to specified format inti, j; sscanf(line, “%d %d”, &i, &j); • 2nd argument is character string, so it’s in quotes • last arguments are addresses • lives in stdio.h
Exercise 3 • Modify Celcius program to read value from keyboard • Declare character array and floats • Read character array from keyboard • Decode character array into float • Calculate temperature • Print temperature • solution
Dynamic Allocation • Suppose you need to allocate an array, but you don’t know how big it needs to be until run time? • Use malloc function malloc(n) • n is no. bytes to be allocated • Returns pointer to allocated space • lives in stdlib.h
Dynamic Allocation (cont’d) • Declare pointer of required type float *myarray; • Suppose we need 101 elements in array • malloc requires no. bytes, cast as appropriate pointer myarray = (float *) malloc(101*sizeof(float)); • free releases space when it’s no longer needed: free(myarray);
For Loop • for loop repeats calculation over range of indices for(i=0; i<n; i++){ a[i] = sqrt( b[i]**2 + c[i]**2 ) } • for statement has 3 parts: • initialization • completion condition • what to do after each iteration