1 / 60

An Overview of C

An Overview of C. Kernighan/Ritchie: Kelley/Pohl:. Chapter 1 Chapter 1. Lecture Overview. Writing and compiling C programs Variables and expressions The C preprocessor Input and output Flow of control Functions Arrays, strings and pointers Files. A First C Program.

carol-york
Télécharger la présentation

An Overview of 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. An Overview of C Kernighan/Ritchie: Kelley/Pohl: Chapter 1 Chapter 1

  2. Lecture Overview • Writing and compiling C programs • Variables and expressions • The C preprocessor • Input and output • Flow of control • Functions • Arrays, strings and pointers • Files

  3. A First C Program • As always, the first program that we will write in C prints 'Hello, world!': • This program should be in a file with a '.c' extension, such as 'hello.c' #include <stdio.h> main() { printf ("Hello, world!\n"); }

  4. Compiling C Programs • To compile the previous program, you should pass it as a parameter to a C compiler, such as cc or gcc • This will create an executable file called 'a.out', which can then be run: gcc hello.c a.out Hello, world!

  5. Compiling C Programs • By convention, the executable should have the same name as the C file, but withoutthe '.c' extension • The executable for 'hello.c' should be called 'hello' • We can specify the name of the generated executable using the compiler's '-o' option: gcc –o hello hello.c

  6. Compiling C Programs • Normally, the compiler will only issue errors, but not warnings • However, warnings can be very useful for improving the quality of your code • The '-Wall' option will generate all possible warnings: gcc –Wall –o hello hello.c

  7. Lecture Overview • Writing and compiling C programs • Variables and expressions • The C preprocessor • Input and output • Flow of control • Functions • Arrays, strings and pointers • Files

  8. Variables and Expressions • In C, all variables must be declared at the beginning of a program or a block • A variable name (identifier) consists of a sequence of letters, digits, underscore, but may not start with a digit int miles, yards, pacific_sea; float kilometers; char c1, c2, c3; char 1c, 2c, 3c; /* wrong */

  9. Variables and Expressions • The evaluation of expressions can involve conversion rules: • The 2 in the second expression is automatically converted to a double, and thus the value of the complete expression is also a double 7 / 2 /* the int value 3 */ 7.0 / 2 /* the value 3.5 */

  10. Variables and Expressions /* The distance of a marathon in kilometers. */ #include <stdio.h> int main() { int miles, yards; float kilometers; miles = 26; yards = 385; kilometers = 1.609 * (miles + yards / 1760.0); printf ("\nA marathon is %f kilometers.\n\n", kilometers); return 0; }

  11. Lecture Overview • Writing and compiling C programs • Variables and expressions • The C preprocessor • Input and output • Flow of control • Functions • Arrays, strings and pointers • Files

  12. The C Preprocessor –#define • The C compiler has a built-in preprocessor • Lines that begin with a '#' are called preprocessing directives: • A '#define' directive can appear anywhere in the program • It affects only lines that come after it #define LIMIT 100 #define PI 3.14159

  13. The C Preprocessor –#define • The contents of quoted strings are never changed by the preprocessor: • The second PI will be replaced, the first one will not • Constants in C programs are normally declared using '#define' statements printf ("PI = %f\n", PI);

  14. The C Preprocessor –#include • Another important preprocessor directive is the '#include' directive • It is used to insert a file into another file during compilation • This is used mostly to include header files– files containing declarations and definitions used by the program

  15. The C Preprocessor –#include • The contents of 'util.h': • The contents of 'my_prog.c': • After preprocessing: extern int a; #include <util.h> main() { ... extern int a; main() { ...

  16. The C Preprocessor –#include • The C system provides a number of standard header files, that define the interface with functions in the C library • Some common header files: Header File stdio.h math.h string.h stdlib.h Use Standard input and output Math functions String manipulation functions Miscellaneous functions

  17. Lecture Overview • Writing and compiling C programs • Variables and expressions • The C preprocessor • Input and output • Flow of control • Functions • Arrays, strings and pointers • Files

  18. Input and Output • Program output is printed using the function printf() • Returns the number of characters printed • Similarly, input is read into the program using the function scanf() • Returns the number of values read • To use either of these functions, the header file 'stdio.h' should be included

  19. Input and Output • Both functions accept a variable number of arguments • The first (mandatory) argument is the control string • The number of additional arguments required is defined by the contents of the control string

  20. Conversion Specifiers • The control string contains plain characters, plus conversion specifiers, which begin with the symbol '%' • For example, to print the letters 'abc', we could use any of the following statements: printf ("abc"); printf ("%s", "abc"); printf ("%c%c%c", 'a', 'b', 'c') ;

  21. Conversion Specifiers • Some common conversion specifiers: Character %c %d %e %f %s Corresponding argument Character Decimal integer Floating point – scientific notation Floating point String

  22. Defining Field Width • With printf(), it is possible to define the field width for each of the printed arguments • This is done by adding a number before the conversion specification: printf ("Chars:%3c%3c%3c\n", 'a', 'b', 'c') ; printf ("Twelve:%6d\n", 12); printf ("Two thirds:%6.3f\n", (2.0 / 3)); Chars: a b c Twelve: 12 Two thirds: 0.667

  23. Defining Field Width • Add a '-' before the field width for left aligned printing, or a '0' for zero padded printing: int a = 5, b = 12; printf ("%d,%d\n", a, b); printf ("%4d,%4d\n", a, b); printf ("%-4d,%-4d\n", a, b); printf ("%04d,%04d\n", a, b); 5,12 5, 12 5 ,12 0005,0012

  24. Reading Input • The function scanf() is analogous to printf() but is used for input • The symbol '&' is the address operator • The '%d' tells scanf() to try to read an integer from the standard input • The '&x' tells it to store the integer in x scanf ("%d", &x);

  25. Input and Output – Example #include <stdio.h> int main() { char c1, c2; int i; float x; printf ("Input two characters, " "an int, and a float:\n"); scanf ("%c%c%d%f", &c1, &c2, &i, &x); printf ("\nThe data that you typed in:\n"); printf ("%3c%3c%5d%17e\n", c1, c2, i, x); return 0; }

  26. Input and Output – Example • scanf() will skip white space when reading in numbers, but not when reading characters Input two characters, an int, and a float: Db 45 2.9858 The data that you typed in: D b 45 2.985800e+00

  27. Getting Help on C Functions • For a full list of field width and conversion specifiers, and for additional options: • The second parameter (3) tells man tolook in section 3 of the manual pages, which contains help on C library functions man 3 printf

  28. Lecture Overview • Writing and compiling C programs • Variables and expressions • The C preprocessor • Input and output • Flow of control • Functions • Arrays, strings and pointers • Files

  29. Flow of Control • Logical expressions have an integer value of either 0 (false) or 1 (true) • The result of any expression can be treated as a Boolean value: • 0 means false • Any non-zero value means true

  30. Flow of Control • C supports the familiar control flowstructures – if, while and for: if (condition) statement1; else statement2; while (condition) statement; for (initialization; condition; increment) statement;

  31. Flow of Control – Examples #include <stdio.h> int main() { int i = 1, sum = 0; while (i <= 5) { sum += i; i++; } printf ("sum = %d\n", sum); return 0; } sum = 15

  32. Flow of Control – Examples #include <stdio.h> int main() { int i = 3; while (i--) printf ("%d ", i); printf ("\n"); if (0.0) printf ("0.0 is true\n"); else printf ("0.0 is false\n"); } 2 1 0 0.0 is false

  33. Lecture Overview • Writing and compiling C programs • Variables and expressions • The C preprocessor • Input and output • Flow of control • Functions • Arrays, strings and pointers • Files

  34. Functions • A C program consists of one or more functions in one or more files • Every C program must contain exactly one main() function • Other functions are called from main(),or from within each other

  35. Function Prototypes • Functions should always be declared before they are used: • function declarations of this type are called function prototypes • A prototype defines the parameter types and the return type of the function float maximum (float x, float y); void print_info();

  36. Function Prototypes #include <stdio.h> void print_num (int); int main() { print_num (5); return 0; } void print_num (int a) { printf ("The number is: %d\n", a); } The number is: 5

  37. Function Prototypes • A function does not need a prototype if it is only used after it's definition #include <stdio.h> void print_num (int a) { printf ("The number is: %d\n", a); } int main() { print_num (5); return 0; }

  38. Passing Parameters by Value • In C, arguments to functions are always passed by value • When an expression is passed as an argument, it is first evaluated, and onlythe result is passed to the function • The variables passed as arguments are not changed in the calling environment

  39. Passing Parameters by Value – Example #include <stdio.h> int main() { int a = 1; void try_to_change_it (int); printf ("%d\n", a); /* 1 is printed */ try_to_change_it (a); printf ("%d\n", a); /* 1 is printed again */ return 0; } void try_to_change_it (int a) { a = 777; }

  40. Lecture Overview • Writing and compiling C programs • Variables and expressions • The C preprocessor • Input and output • Flow of control • Functions • Arrays, strings and pointers • Files

  41. Arrays • Arrays are used when many variables, all of the same type, are desired. For example: • This allocates space for 3 integers • Each element of the array is of type int, and is accessed as: a[0], a[1], a[2] • Arrays are zero based (indexes start at 0) int a[3];

  42. Arrays – Example #include <stdio.h> #define CLASS_SIZE 5 int main() { int i, j, sum = 0, tmp; int score[CLASS_SIZE]; printf ("Input %d scores: ", CLASS_SIZE); for (i = 0; i < CLASS_SIZE; i++) { scanf ("%d", &score[i]); sum += score[i]; } ...

  43. Arrays – Example ... for (i = 0; i < CLASS_SIZE - 1; i++) for (j = CLASS_SIZE - 1; j > i; j--) if (score[j-1] < score[j]) { tmp = score[j-1]; score[j-1] = score[j]; score[j] = tmp; } printf ("\nOrdered scores:\n\n"); for (i = 0; i < CLASS_SIZE; i++) printf (" score[%d] = %d\n", i, score[i]); printf ("\n%d%s\n%.1f%s\n\n", sum, " is the sum of all the scores", (double)sum / CLASS_SIZE, " is the average"); return 0; }

  44. Arrays – Example • The program stores 5 integers in an array, and then sorts them using bubble sort Input 5 scores: 63 88 97 53 77 Ordered scores: score[0] = 97 score[1] = 88 score[2] = 77 score[3] = 63 score[4] = 53 378 is the sum of all the scores 75.6 is the average

  45. Using Pipes for Program Input • When writing or debugging the previous program, all input numbers need to bere-typed every time the program is run • Instead, we can use a pipe: • The program 09_arrays will accept the 5 input numbers as if they were typed in echo 63 88 97 53 77 | 09_arrays

  46. Pointers • Pointers are variables that contain the address of a variable • The above assigns the address of c to the variable p, and p is said to "point to" c • The dereferencing operation uses '*': char *p; char c = 'A'; p = &c; char d = *p;

  47. Arrays and Pointers • Pointers and arrays are closely related • An array variable is simply a pointer to the first element of the array • Unlike a pointer, an array variable can not be modified • In many cases, array and pointer notations are interchangeable

  48. Strings, Arrays and Pointers • In C, a string is an array of characters • Arrays of characters are not different from arrays of any other type • String elements may be accessed directly as variables of type char • Pointers can be used to manipulate strings

  49. Strings, Arrays and Pointers – Example #include <stdio.h> int main() { char *p = "pointer to char"; char str[] = "string array"; printf ("%s\n%s\n", p, str); p = str; *str = 'S'; str[1] = 'T'; *(p + 2) = 'R'; p[3] = 'I'; printf ("%s\n", p); return 0; }

  50. Strings, Arrays and Pointers – Example • Both p and str refer to strings • Although defined differently, each one can be used either as an array, or as a pointer • Characters can be accessed as array elements, or through pointer dereferencing • Program output: pointer to char string array STRIng array

More Related