Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to C Programming Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.

Similar presentations


Presentation on theme: "Introduction to C Programming Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University."— Presentation transcript:

1 Introduction to C Programming Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

2 TRU-COMP2130 Data Representation2 Course Contents Introduction to computer systems: B&O 1 Data representations: B&O 2.1 – 2.4 Introduction to C programming: K&R 1 – 4 C: advanced topics: K&R 5.1 – 5.10, 6 – 7 Introduction to IA32 (Intel Architecture 32): B&O 3.1 – 3.8, 3.13 Compiling, linking, loading, and executing: B&O 7 (except 7.12) Dynamic memory management – Heap: B&O 9.9.1 – 9.9.2, 9.9.4 – 9.9.5, 9.11 Code optimization: B&O 5.1 – 5.6, 5.13 Memory hierarchy, locality, caching: B&O 5.12, 6.1 – 6.3, 6.4.1 – 6.4.2, 6.5, 6.6.2 – 6.6.3, 6.7 Virtual memory (if time permits): B&O 9.4 – 9.5

3 TRU-COMP2130 Data Representation3 Unit Learning Objectives Use cc (or gcc ) to compile C programs. Write a C program with the common (very similar) syntaxes with Java. Use printf() library function to print messages. Use define statements for constants. Use getchar() and putchar() for I/O. Use of integer values as Boolean values. Use a char array as a string. Use bit operators to manipulate bits in a given integer. Understand the scope of external identifiers. Distinguish signed integer types and unsigned integer types. Use register variables for indexing arrays. Use conditional inclusion statements with #if, #elif, …. …

4 TRU-COMP2130 Data Representation4 1. Introduction The C programming language was designed by Dennis Ritchie at Bell Laboratories in the early 1970s Influenced by ALGOL 60 (1960), CPL (Cambridge, 1963), BCPL (Martin Richard, 1967), B (Ken Thompson, 1970) Traditionally used for systems programming, though this may be changing in favor of C++ Traditional C: The C Programming Language, by Brian Kernighan and Dennis Ritchie, 2 nd Edition, Prentice Hall (Referred to as K&R ) Programming in C – Byron S. Gottfried (Schaum’s Outline Series)

5 Standard C Standardized in 1989 by ANSI (American National Standards Institute) known as ANSI C International standard (ISO) in 1990 which was adopted by ANSI and is known as C89 As part of the normal evolution process the standard was updated in 1995 (C95) and 1999 (C99) C++ and C C++ extends C to include support for Object Oriented Programming and other features that facilitate large software development projects C is not strictly a subset of C++, but it is possible to write “Clean C” that conforms to both the C++ and C standards. Introduction5 TRU-COMP2130

6 Elements of a C Program A C development environment includes System libraries and headers: a set of standard libraries and their header files. For example see /usr/include and glibc. Application Source: application source and header files Compiler: converts source to object code for a specific platform Linker: resolves external references and produces the executable module User program structure there must be one main function where execution begins when the program is run. This function is called main int main (void) {... }, int main (int argc, char *argv[]) {... } UNIX Systems have a 3 rd way to define main(), though it is not POSIX.1 compliant int main (int argc, char *argv[], char *envp[]) additional local and external functions and variables Introduction6 TRU-COMP2130

7 A Simple C Program Create example file: try.c Compile using gcc: gcc –o try try.c The standard C library libc is included automatically Execute program./try Note, I always specify an absolute path Normal termination: void exit(int status); calls functions registered with atexit() flush output streams close all open streams return status value and control to host environment Introduction7 /* you generally want to * include stdio.h and * stdlib.h * */ #include int main (void) { printf(“Hello World\n”); exit(0); } TRU-COMP2130

8 Getting Started C program files should end with “.c”. hello.c #include // similar to import statements in Java // stdio.h includes the information about the standard library int main() // similar to main method in Java { printf (“hello, world\n”); // printf() defined in stdio.h return 0; } How to compile? $ gcc hello.c or $ gcc hello.c-o hello If you do not have anything wrong, you will see a.out in the same working directory. How to run? $./a.out Introduction8 TRU-COMP2130

9 Source and Header files Just as in Java, place related code within the same module (i.e. file). Header files ( *.h ) export interface definitions function prototypes, data types, macros, inline functions and other common declarations Do not place source code (i.e. definitions) in the header file with a few exceptions. inline’d code class definitions const definitions C preprocessor ( cpp ) is used to insert common definitions into source files There are other cool things you can do with the preprocessor Introduction9 TRU-COMP2130

10 Another Example C Program Introduction10 example.c /* this is a C-style comment * You generally want to palce * all file includes at start of file * */ #include int main (int argc, char **argv) { // this is a C++-style comment // printf prototype in stdio.h printf(“Hello, Prog name = %s\n”, argv[0]); exit(0); } /* comments */ #ifndef _STDIO_H #define _STDIO_H... definitions and protoypes #endif /usr/include/stdio.h /* prevents including file * contents multiple * times */ #ifndef _STDLIB_H #define _STDLIB_H... definitions and protoypes #endif /usr/include/stdlib.h #include directs the preprocessor to “include” the contents of the file at this point in the source file. #define directs preprocessor to define macros. TRU-COMP2130

11 C Standard Header Files Standard Headers you should know about: stdio.h – file and console (also a file) IO: p error, printf, open, close, read, write, scanf, etc. stdlib.h - common utility functions: malloc, calloc, strtol, atoi, etc string.h - string and byte manipulation: strlen, strcpy, strcat, memcpy, memset, etc. ctype.h – character types: isalnum, isprint, isupport, tolower, etc. errno.h – defines errno used for reporting system errors math.h – math functions: ceil, exp, floor, sqrt, etc. signal.h – signal handling facility: raise, signal, etc stdint.h – standard integer: intN_t, uintN_t, etc time.h – time related facility: asctime, clock, time_t, etc. Introduction11 TRU-COMP2130

12 The Preprocessor The C preprocessor permits you to define simple macros that are evaluated and expanded prior to compilation. Commands begin with a ‘#’. Abbreviated list: #define : defines a macro #undef : removes a macro definition #include : insert text from file #if : conditional based on value of expression #ifdef : conditional based on whether macro defined #ifndef : conditional based on whether macro is not defined #else : alternative #elif : conditional alternative defined() : preprocessor function: 1 if name defined, else 0 #if defined(__NetBSD__) Introduction12

13 Common features For the statement printf (“hello, world\n”); “…” is a character string. This is also called a string constant. printf() is a library function to print a string to the terminal. Data types - primitive data types char, int, (short & long), float, double Introduction13

14 Operators Mathematical –Subtraction, also unary minus +Addition *Multiplication /Division %Modulus --Decrement ++Increment Relational >Greater than >=Greater than or equal <Less than <=Less than or equal = =Equal !=Not equal Introduction14

15 Operators Logical Operators: &&AND ||OR !NOT Introduction15

16 Control structures if, if-else, for, while, do-while, switch Introduction16

17 Exercise write a program to convert Fahrenheit temperature to Celsius temperature, using the given formula formula: C = 5 / 9 × (F – 32) Ask user for an option for C -> F Or F -> C Introduction17

18 18 Precedence and Associativity

19 19 Examples x =10;y = ++x; y 11 x =10;y = x++; y 10 int i = 3, j = 2, k; i++;i j = ++i;ji k = i++;k i k = (--j+3) kj 4 5 5 5 6 4 7

20 20 l = 4; n = 3; m = 2; x = l * n + m++;x After the assignment to x. m 14 3

21 21 int a,b; a = 1; b = 12; printf (“a+++b = %d/n”, a+++b); a = 1; b = 12; printf (“a++ +b = %d/n”, a++ +b); a = 1; b = 12; printf (“a+ ++b =% d/n”, a+ ++b);

22 22 Precedence and Associativity

23 23 Both are lower in precedence than the arithmetic operators. 10 > 1 + 12 10 > (1 + 12) FALSE 0 Associativity: left to right. int x; x = 100; printf(''%d", x>10); __?

24 24 !A is false (0) if A’s value is: __. is true (1) if A’s value is: __. !!5 ! (!5)! (0) 1 5 && 3 ? Examples

25 Example See Introduction25

26 Answer Introduction26

27 Comma operator l Lowest precedence of all the operators. l Causes a sequence of operations, “do this and this and this…”. l Is a binary operator. expression_1, expression_2 l Associates left to right. expression_1 is evaluated first expression_2 is evaluated second Introduction27

28 28 l The Comma Expression as a whole has the value and type of expression_2. Comma operator – Ex.

29 Conditional Operator (Ternary) A powerful and convenient operator that replaces certain statements of the if-then-else form. Exp1 ? Exp2: Exp3 Introduction29

30 Example It is also possible to nest ternary Introduction30

31 Expressions Vs Statements An expression in C is any valid combination of operators, constants, functions and variables. A statement is a valid expression followed by a semicolon. Func1(); A function call as a statement. Y = X + Y; An assignment statement. B + Func1(); Valid? Introduction31

32 Think Idea c = (c > =‘a’ && c < = ‘z’) ? c - (‘z’ - ‘Z’):c; Introduction32

33 TRU-COMP2130 C Programming33 Example ‘C’ code #include... /* print Fahrenheit-Celsius table for fahr = 0, 20, 40,..., 300, using a loop */ main() { int fahr, celsius; int lower, upper, step; lower = 0;/* lower limit of temperature scale */ upper = 300;// upper limit step = 20;// step size fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr-32) / 9;// integer value? printf("%d\t%d\n", fahr, celsius); fahr = fahr + step; } }

34 TRU-COMP2130 C Programming34 printf("%d\t%d\n", fahr, celsius); %d specifies an integer argument (d: decimal). Output 1-17 20-6 404... Can we print better? Like 1 -17 20 -6 40 4... printf("%3d\t%6d\n", fahr, celsius);

35 TRU-COMP2130 C Programming35 1 -17 20 -6 40 4... Is there any problem in the above output? The Celsius temperatures in the previous out are not accurate. For example 0 o F is -17.8 o C. Then? We can use float data type for fahr and celsius instead of int. float fahr, celsius; Then how to print real numbers using printf() ? celsius = 5 * (fahr-32) / 9;// okay? printf("%3.0f\t%6.1f\n", fahr, celsius); %f specifies a floating point argument (f: floating point). 6.1 means 1 decimal out of 6 digits.

36 TRU-COMP2130 C Programming36 Some easy errors: printf("%d\t%6.1f\n", fahr, celsius); printf("%3.0f\t%6.1f\n", fahr); printf("%6.1f\n", fahr, celsius);

37 TRU-COMP2130 C Programming37 Summary of printf() format specifiers %dprint as decimal integer %6dprint as decimal integer, at least 6 characters wide %fprint as floating point %6fprint as floating point, at least 6 characters wide %.2fprint as floating point, 2 characters after decimal point %6.2fprint as floating point, at least 6 characters wide and 2 after decimal point Other format specifiers %ofor octal %xfor hexadecimal %cfor character %sfor character string %% itself

38 TRU-COMP2130 C Programming38 Symbolic Constants #define name replacement_list #include #define LOWER 0// similar to final variable in Java #define UPPER 300 #define STEP 20 main() { float fahr, celsius; for (fahr = LOWER ; fahr <= UPPER ; fahr = fahr + STEP) { celsius = 5 * (fahr-32) / 9; printf("%3.0f\t%6.1f\n", fahr, celsius); }

39 TRU-COMP2130 C Programming39 Symbolic Constants #define name replacement_list #include #define LOWER 0// similar to final variable in Java #define UPPER 300 #define STEP 20 main() { float fahr, celsius; for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP) { celsius = 5 * (fahr-32) / 9; printf("%3.0f\t%6.1f\n", fahr, celsius); }

40 TRU-COMP2130 C Programming40 Character Input and Output #include /* copy input to output; 1st version */ main() { int c; c = getchar();// in order to read a character while (c != EOF) {// EOF is defined in stdio.h. // EOF means End of File, ^D. putchar(c);// in order to print a character c = getchar(); } } Where did getchar(), EOF, and putchar() come from? Let’s run this program to understand I/O better.

41 TRU-COMP2130 C Programming41 #include /* copy input to output; 2nd version */ main() { int c; while ((c = getchar()) != EOF)// okay? putchar(c); } What if we use the follow code instead? while (c = getchar() != EOF) The above code is equivalent to while (c = (getchar() != EOF)) This is because the precedence of != is higher than =.

42 TRU-COMP2130 C Programming42 Operator precedence rules () [] ->. ! ~ - ( unary ) + ( unary ) * & sizeof ++ -- * / % + - > >= == != & ^ | && || = += -= *= /= %= &= |= ^= >=

43 TRU-COMP2130 C Programming43 Boolean values in ‘C’ Syntax error? while (c = getchar() != EOF) Let’s assume getchar() returns ‘A’. Then getchar() != EOF becomes TRUE. The data type of c is int. Is there a boolean data type in C? No 0 is FALSE and non-zero value is considered as TRUE in C. Hence getchar() != EOF becomes 1, and c has 1. while(c) -> while(1). So, the loop repeats.

44 TRU-COMP2130 C Programming44 Arrays #include /* count digits, white space, others */ main() { int c, i, nwhite, nother, ndigit[10]; // very similar to Java nwhite = nother = 0; // really necessary? for (i = 0; i < 10; ++i) ndigit[i] = 0; while ((c = getchar()) != EOF) if (c >= '0' && c <= '9') ndigit[c-'0']++; else if (c == ' ' || c == '\n' || c == '\t') ++nwhite; else nother++; printf("digits ="); for (i = 0; i < 10; i++) printf(" %d", ndigit[i]); printf(", white space = %d, other = %d\n", nwhite, nother); }

45 TRU-COMP2130 C Programming45 A character, e.g., ‘3’, is an integer value. int c = ‘3’; is valid. ASCII table

46 TRU-COMP2130 C Programming46 Functions #include int power(int m, int n); // function declaration // What if it is not declared before //main()? main() { int i; for (i = 0; i < 10; i++) printf("%d %d %d %d\n", i, power(2, i), power(-3, i), i); return 0; } /* power: raise base to n-th power; n >= 0 */ int power(int base, int n) { int i, p;...// How to implement?

47 TRU-COMP2130 C Programming47... for (i = 0; i < 10; i++) printf("%d %d %d %d\n", i, power(2,i), power(-3,i), i); return 0; } /* power: raise base to n-th power; n >= 0 */ int power(int base, int n) { int i, p; p = 1; for (i = 1; i <= n; i++) p = p * base; return p; }

48 TRU-COMP2130 C Programming48 Arguments /* power: raise base to n-th power; n >= 0; version 2 */ int power(int base, int n) { int p; for (p = 1; n > 0; n--) p = p * base; return p; } base, n and p are local variables that are used only in power(). When the function is called (or also called invoked), the values will be copied (oac passed) into base and n. Even if those variables are updated with other values, the new values will not be passed back to the caller function. How is this implemented in main memory? This type of function calling is called call by value.

49 Character Arrays #include #define MAXLINE 1000 int getline(char line[], int maxline); void copy(char to[], char from[]); main() { int len; /* current line length */ int max; /* maximum length seen so far */ char line[MAXLINE]; /* current input line */ char longest[MAXLINE]; // longest line saved max = 0; while ((len = getline(line, MAXLINE)) > 0) if (len > max) { max = len; copy(longest, line); } if (max > 0) printf("%s", longest); return 0; }... int getline(char s[], int lim) { int c, i; for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) s[i] = c; if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; // “...’\0’” return i; } void copy(char to[], char from[]) { int i; i = 0; while ((to[i] = from[i]) != '\0') ++i; } In the same file

50 TRU-COMP2130 C Programming50 In main(), while ((len = getline(line, MAXLINE)) > 0) The data type of line[] is an array. getline() can change the contents in line [], and the change in line[] can be used in main(). Very similar to Java. This type of function calling is called call by reference. How is this implemented in main memory? line represents MAXLINE variables - line[0], line[1],..., line[MAXLINE-1]. How? Address should be passed. line contains the address of the first byte of line[0]. line[i] is the memory area pointed by the address line + sizeof(char) * i. addrvaluevar ……… defabcline ……… abc‘C’line[0] abc+1‘O’line[1] ……… Main memory

51 TRU-COMP2130 C Programming51 In getline(), int getline(char s[], int lim) The data type of the first parameter is an array. The address stored in line in main() is passed into s. Therefore s[i] will become equal to line[i]. Any change in this variable will be preserved so that the caller can use the change. This type of function calling is called call by reference. s[i] = '\0'; After all the characters are stored in s[] till EOF or ‘\n’, ‘\0’ is stored to mark the end of the character string. That is, a string is a list of characters with the end of ‘\0’, and a char array is usually used to keep a string. This is very important.

52 TRU-COMP2130 C Programming52 In main(), if (max > 0) printf("%s", longest); %s is used to print a character string. The argument is a char array, not longest[], nor longest[0], and … What is the data type of longest ? char longest[MAXLINE]; What value is stored in longest ? The address of the first byte of longest[0] to represent all longest[0], longest[1], …. Can a char array be a character string? Yes. printf() with %s will try to print characters pointed by longest (, i.e., longest[0], longest[1], …,) until the character becomes ‘\0’.

53 TRU-COMP2130 C Programming53 char name[256], tmp[256]; name[0] = ‘C’; name[1] = ‘O’; name[2] = ‘M’; name[3] = ‘P’; name[4] = ‘\0’;// it is very important. printf(“course number = %s\n”, name); name[5] = ‘ ’; name[6] = ‘2’; printf(“course number = %s\n”, name); name[7] = ‘1’; name[8] = ‘3’; name[9] = ‘0’; name[10] = ‘\0’; // it is very important. printf(“course number = %s\n”, name); What is the output?

54 External Variables and Scope #include #define MAXLINE 1000 int max; // similar to instance in Java char line[MAXLINE]; char longest[MAXLINE]; int getline(void); void copy(void); main() { int len; extern int max, extern char longest[]; max = 0; while ((len = getline()) > 0) if (len > max) { max = len; copy(); } if (max > 0) /* there was a line */ printf("%s", longest); return 0; } int getline(void) { int c, i; // extern char line[]; // no need to declare for (i = 0; i < MAXLINE – 1 && (c=getchar)) != EOF && c != '\n'; ++i) line[i] = c; if (c == '\n') { line[i] = c; ++i; } line[i] = '\0'; return i; } void copy(void) { int i; // extern char line[], longest[]; i = 0; while ((longest[i] = line[i]) != '\0') ++i; } In the same file

55 TRU-COMP2130 C Programming55 #include … … #define … … // declaration of global variables … // declaration (i.e., definitions) of functions … // implementation of functions { … } Any identifier declared early is visible in the same block or sub-blocks. Visible to every function in the file

56 TRU-COMP2130 C Programming56 Data Types and Sizes Primitive data types CJavaSize char, unsigned charbyte1B char in Java uses 2Bs. short, unsigned shortshort2Bs int, unsigned intint4Bs long, unsigned longlong8Bs // there is no unsigned in Java floatfloat4Bs doubledouble8Bs // boolean?TRUE: any non-zero value, boolean in Java FALSE: zero // string?“...”: with ‘\0’ at the end String in Java sizeof(data_type) or sizeof(variable) gives the number of bytes used.

57 TRU-COMP2130 C Programming57 Goto and Labels for (i = 0; i < n; i++) for (j = 0; j < m; j++) if (a[i] == b[j]) goto found; /* didn't find any common element */... found: /* got one: a[i] == b[j] */... Better not use goto statements Can you convert the above code so that you would not use goto ?

58 TRU-COMP2130 C Programming58 4. Functions and Program Structure Function in C is the same as method in Java. return-type function-name(argument declarations) Various parts may be absent.

59 TRU-COMP2130 C Programming59 External Variables If a large number of variables must be shared among functions, external variables (or also called global variables) are more convenient and efficient than long argument lists. External variables are declared outside of any function, usually with initial values. Automatic variables (local variables and parameters) are internal to a function; they come into existence when the function is entered, and disappear when it is left. External variables, on the other hand, are permanent, so they can retain values from one function invocation to the next. Thus if two functions must share some data, yet neither calls the other, it is often most convenient if the shared data is kept in external variables rather than being passed in and out via arguments.

60 TRU-COMP2130 C Programming60 Scope Rules The scope of a name is the part of the program within which the name can be used. The scope of an external variable or a function lasts from the point at which it is declared to the end of the file being compiled. main() {... } int sp = 0; double val[MAXVAL]; void push(double f) {... } double pop(void) {... } Is sp visible in push() ? Can sp and pop() be used in main() ?

61 TRU-COMP2130 C Programming61 Can we make external variables declared in file1 be used in file2? in file1: extern int sp; extern double val[]; void push(double f) {... } double pop(void) {... } in file2: int sp = 0; double val[MAXVAL];

62 TRU-COMP2130 C Programming62 Static Variables The static declaration, applied to an external variable or function, limits the scope of that object to the rest of the source file being compiled. External static thus provides a way to hide names from other files. static char buf[BUFSIZE]; // only in this file static int bufp = 0; // only in this file int getch(void) {... } void ungetch(int c) {... } Static in Java has a bit different meaning.

63 TRU-COMP2130 C Programming63 Register Variables A register declaration advises the compiler that the variable in question will be heavily used. The idea is that register variables are to be placed in machine registers, which may result in smaller and faster programs. But compilers are free to ignore the advice. register int x; register char c; f(register unsigned m, register long n) { register int i;... } Usually for index variables used in loop structures

64 TRU-COMP2130 C Programming64 Initialization Very similar to Java In the absence of explicit initialization, external and static variables are guaranteed to be initialized to zero; but automatic and register variables have undefined (i.e., garbage) initial values.

65 TRU-COMP2130 C Programming65 The C Preprocessor File inclusion #include “filename” // from the working dir or #include // from the standard dir Macro substitution #define name replacement_text #define max(A, B) ((A) > (B) ? (A) : (B)) Conditional inclusion #if !defined(HDR) // or #ifndef HDR #define HDR /* contents of hdr.h go here */ #endif

66 TRU-COMP2130 C Programming66 #if SYSTEM == SYSV #define HDR "sysv.h" #elif SYSTEM == BSD #define HDR "bsd.h" #elif SYSTEM == MSDOS #define HDR "msdos.h" #else #define HDR "default.h" #endif #include HDR


Download ppt "Introduction to C Programming Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University."

Similar presentations


Ads by Google