1 / 99

Introduction to C

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

kevlyn
Télécharger la présentation

Introduction to C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to C Doug Sondak SCV sondak@bu.edu

  2. Outline • Goals • Introduction • Emacs • C History • Basic syntax • makefiles • Additional syntax

  3. 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

  4. 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

  5. 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

  6. 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

  7. 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 .

  8. 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

  9. 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

  10. 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.

  11. 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.

  12. 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

  13. 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

  14. 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

  15. 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

  16. 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

  17. 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

  18. 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

  19. 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++

  20. 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

  21. 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 }

  22. C Syntax (4) • Style note: some people like to arrange the brackets like int main() { function statements } • Either way is fine • Be consistent!

  23. 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 ;

  24. 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’

  25. 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

  26. 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

  27. 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

  28. 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

  29. 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

  30. 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

  31. Declarations (cont’d) • Examples: inti, j, k; float xval, time; char name, date; • A “char” variable represents a single character

  32. 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

  33. 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;

  34. 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 );

  35. 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

  36. 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

  37. 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

  38. 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;

  39. Pointers (4) float x, *p; p = &x; 1056 32 p 1052 16 16 1048 8 1040 0 address address

  40. 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

  41. 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;

  42. 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;

  43. 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;

  44. 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

  45. 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)

  46. 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

  47. 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

  48. 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

  49. 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);

  50. 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

More Related