c progra amming a modern approach
play

C Progra amming A Modern Approach K. N. King, C Progra C P - PowerPoint PPT Presentation

C Progra amming A Modern Approach K. N. King, C Progra C P ramming i Approach , A Modern W. W. Norton & C Company, 1996. Original Notes by Raj Sunderraman Converted to present p ation and updated by p y Michael Weeks Note


  1. C Progra amming A Modern Approach K. N. King, C Progra C P ramming i Approach , A Modern W. W. Norton & C Company, 1996. Original Notes by Raj Sunderraman Converted to present p ation and updated by p y Michael Weeks

  2. Note About Note About t Coverage t Coverage � This class has only par Thi l h l rt of the semester t f th t dedicated to C � You already know Java a, which has similar syntax syntax � You should be able to r read the book quickly

  3. Similarities o Similarities o of C to Java of C to Java � /* Comments */ /* C t */ � Variable declarations a ab e dec a at o s � If / else statements � For loops � While loops While loops � Function definitions (lik ke methods) � Main function starts pro ogram

  4. Differences betw Differences betw ween C and Java ween C and Java � C does not have object C d t h bj t ts − There are “struct”ures − But data are not tied to methods � C is a functional progra C i f ti l amming language i l � C allows pointer manip p p ulation � Input / Output with C − Output with printf functio on − Input with scanf function p n

  5. Variable e Type C has the following simple data types: In C: char ch; h h ch = ‘a’; ch = ‘A’; ch A; ch = ‘0’; ch = ‘ ‘; Java has the following simple data types s: char ch; Primitive type Size Minimum Ma ximum Wrapper type int I; boolean boolean 1 bit 1-bit – – Boolean Boolean i = ‘a’ i ‘ ’ icode 2 16 - 1 ch = 65; char 16-bit Unicode 0 Uni Character ch = ch + 1; byte 8-bit -128 +12 27 Byte [1] ch++; ch++; 5 – 1 -2 15 2 15 +2 1 +2 1 5 short short 16-bit 16 bit 1 Short 1 Short 1 31 – 1 -2 31 +2 3 int 32-bit Integer if (‘a’<=ch && 63 – 1 long 64-bit -2 63 +2 6 Long ch<=‘z’) ) float float 32-bit 32 bit IEEE754 IEEE754 IEE IEE EE754 EE754 Float Float ch=ch-’a’+’A’ double 64-bit IEEE754 IEE EE754 Double void – – – Void 1

  6. Data T Data T Types Types char, int, float, double h i t fl t d bl � long int (long), short in o g t ( o g), s o t nt (short), long double t (s o t), o g doub e � signed char, signed in nt � unsigned char, unsign ned int � − 1234L is long integer, 1234L is long integer − 1234 is integer, − 12.34 is float, − 12.34L is long float g

  7. Data T Data T Types Types � 'a', '\t', '\n', '\0', etc. are ' ' '\t' '\ ' '\0' t character constants h t t t � strings: character array st gs c a acte a ay ys ys − (see <string.h> for strin g functions) − "I am a string" − always null terminated. − 'x' is different from "x"

  8. Type Con Type Con nversions nversions � narrower types are t int atoi(char s[]) { converted into wider typ pes int i, n=0; for (i 0; s[i] for (i=0; s[i] >= '0' 0 && s[i] <= '9'; i++) − f + i int i converted to fl oat n = 10*n + (s[i]-'0'); � characters <---> intege � characters <---> intege rs rs return n; t } � <ctype.h> library conta ins conversion functions, e e.g.: − tolower(c) tolower(c) isdigit(c) et isdigit(c) et tc tc. � Boolean values: − true : >= 1 false: 0

  9. Pointers a Pointers a and Arrays and Arrays � Pointer variable contain � Pointer variable contain ns the address of another ns the address of another variable − unary operator & applied d to variables gives the address of variable − unary operator * applied d to pointer accesses the variable pointer points to o � char c; p = &c; − address of c is assigned dd f i i d d t d to variable p i bl

  10. Pointers a Pointers a and Arrays and Arrays int x=1, y=2, z[10]; int *p; /* p points to an integer r */ p = &x; /* Set p to x's address s */ y = *p; /* Get value of p, store e in y */ *p = 0; /* Set p's value to 0 * */ p = &z[0]; /* Set p to z[0]'s add dress */

  11. Pointer E Pointer E Example Example $ cat ptr example.c p _ p #include <stdio.h> int main() { int x=1; int x=1; int *p; /* p points to an integer */ p = &x; /* Set p to x's address */ printf(" x is %d\n", x); *p = 0; /* Set p's value to 0 */ printf( x now is %d\n , x); printf(" x now is %d\n" x); return 0; } $ gcc ptr_example.c -o ptr_example $ ./ptr_example x is 1 x is 1 x now is 0

  12. Using pointers to achieve Call-By- Referenc ce effect � Pass the address of a v P th dd f variable i bl � Alter the value te t e a ue void swap (int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; py p } int a=10,b=20; , ; swap(&a,&b);

  13. Pointers a Pointers a and Arrays and Arrays int a[10], *pa, x; int a[10], pa, x; pa = &a[0]; x = *pa; x pa; x = *(pa+1); x = *(pa+5); pa = a; /* same as pa = &a[0]; pa = a; / same as pa = &a[0];

  14. Main difference be etween arrays and poin nters � Even though both conta E th h b th t ain addresses: i dd � Array name is not a var ay a e s ot a a riable; so ab e; so pa = a; pa++ O OK � a = pa; a++; N NOT OK � � When an array name is When an array name is s passed as a parameter s passed as a parameter to a function: − Actually the address of the first element is passed − Arrays are always pass Arrays are always pass ed as pointers ed as pointers

  15. Finding the len Finding the len ngth of a String ngth of a String int strlen(char *s) { /* One way */ int n; f for (n=0; *s!='\0'; s++) ( 0 * ! '\0' ) n++; return n; return n; } int strlen(char s[]) { /* Another possibility y */ int n; for (n=0; s[n]!='\0';n++); return n; }

  16. Stri Stri ngs ngs � Array of characters A f h t � Example: string copy a p e st g copy void strcpy(char *s, char *t) { int i 0; int i=0; while ((s[i]= t[i]) != '\0') i++; } /* OR: */ while ((*s = *t) != '\0') { s++; t++; s ; t ; }

  17. Scope Scope Rules Rules � Automatic/Local Variab A t ti /L l V i b bles bl − Declared at the beginni g ng of functions g − Scope is the function bo ody � External/Global Variabl E t l/Gl b l V i bl les − Declared outside functio ons − Scope is from the point where they are declared u until end of file (unless p e d o e (u ess p prefixed by extern) p e ed by e e )

  18. Scope Scope Rules Rules � Static Variables: use st St ti V i bl tatic prefix on functions t t ti fi f ti and variable declaratio ns to limit scope − static prefix on external variables will limit scope to the rest of the source fil le (not accessible in other ( files) − static prefix on functions static prefix on functions s will make them invisible to s will make them invisible to other files − static prefix on internal v static prefix on internal v variables will create variables will create permanent private stora age; retained even upon function exit function exit

  19. Scope Scope Rules Rules � Variables can be decla V i bl b d l red within blocks too d ithi bl k t − scope is until end of the p e block

  20. Bitwise O Bitwise O Operations Operations � Applied to char, int, sho A li d t h i t h ort, long t l − And & − Or | − Exclusive Or ^ Exclusive Or ^ − Left-shift << − Right-shift >> − one's complement ~ one s complement

  21. Example: Example: Bit Count Bit Count /* count the 1 bits in a number e.g. bitcount(0x45) (01000101 bina ary) returns 3 */ int bitcount (unsigned int x) { int b; for (b=0; x != 0; x = x >> 1) if (x & 01) /* octal 1 = 0000000 001 */ b++; b++; return b; }

  22. Conditional E Conditional E Expressions Expressions � Conditional expression C diti l i s expr1? expr2:expr3 e p e p e p 3 3; 3; � � if expr1 is true then exp pr2 else expr3 for (i=0; i<n; i++) printf("%6d %c",a[i],(i%10==9||i==(n- -1))?'\n':' ');

  23. Contro Contro ol Flow ol Flow � blocks: { ... } bl k { } � if expr stmt; � if expr stmt1 else stmt2; � switch expr {case ... defa s itch e pr {case defa ault } a lt } � while expr stmt; � for (expr1;expr2;expr3) s stmt; � do stmt while expr; do stmt while expr; � break; continue (only for r loops); � goto label;

  24. Hello, Hello World World #include <stdio.h> /* Standard I/O library */ /* Function main with no a arguments */ int main () { /* call to printf function */ printf("Hello, World!\n"); /* return SUCCESS = 1 * */ return 1; } % gcc -o hello hello.c % ./hello % /hello Hello, World! %

  25. Celsius vs Fa hrenheit table (in steps s of 20F) � C = (5/9)*(F-32); $ ./CelsiusFahrenheitTable 0 -17 20 -6 #include <stdio.h> 40 4 int main() { 60 15 int fahr, celsius, lower, upper, step; 80 26 lo er lower = 0; 0 100 37 100 37 upper = 300; 120 48 step = 20; 140 60 fahr = lower; fahr = lower; 160 160 71 71 180 82 while (fahr <= upper) { 200 93 celsius = 5 * (fahr - 32) / 9; 220 104 printf("%d\t%d\n",fahr, celsius); printf( %d\t%d\n ,fahr, celsius); 240 115 fahr += step; 260 126 } 280 137 return 1; 300 300 148 148 }

Recommend


More recommend