1 / 119

The C Programming Language

The C Programming Language. Currently one of the most commonly-used programming languages “High-level assembly” Small but powerful Very portable:compiler exists for virtually every processor. Hello World in C. Include a header file that lets you use I/O related C functions

tavita
Download Presentation

The C Programming Language

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. The C Programming Language • Currently one of the most commonly-used programming languages • “High-level assembly” • Small but powerful • Very portable:compiler exists for virtually every processor

  2. Hello World in C Include a header file that lets you use I/O related C functions Similar to Java’s import #include <stdio.h> int main() { printf(“Hello, world!\n”); return 0; }

  3. Why is C Dangerous • C’s small feature set is an advantage and disadvantage • The price of C’s flexibility • C does not, in general, try to protect a programmer from his/her mistakes

  4. Commonly used header files • stdio.h • Standard C library for I/O • stdlib.h • General purpose standard C library • string.h • math.h • sqrt, pow, sin, cos • ctype.h • a bunch of very useful character functions: isdigit,isalpha, isalnum, isspace, islower, isupper, tolower/toupper • time.h

  5. Hello World in C Program mostly a collection of functions “main” function special: the entry point “int” qualifier indicates function returns an integer #include <stdio.h> int main() { printf(“Hello, world!\n”); return 0; } I/O performed by a library function

  6. C is Function-oriented • C came before OO concept • C program resemble java programs with a single giant class • C is procedural • Program organization and modularization is achieved through function design • Carefully plan your function return type and parameter list • Write small functions!

  7. Functions • Function: Unit of operation • A series of statements grouped together • Must have the main function • C functions are stand-alone • Most programs contain multiple function definitions • Must be declared/defined before being used

  8. Functions int menuChoice() { int choice; printf( "1. Yes\n" "0. No\n" "Enter the number corresponding to your choice: "); scanf("%d", &choice); return choice; } int main() { int choice; printf("=== Expert System ===\n"); printf("Question1: ...\n"); choice = menuChoice(); if (choice == 1) { /* yes */ printf("Question 2: ...\n"); choice = menuChoice(); /* skipped */

  9. Function parameters void km_mile_conv(int choice) { int input; printf("Enter a %s value: ", choice==1?"mile":"km"); scanf("%lf", &input); if (choice == 1) printf("%f mile(s) = %f km(s)\n", input, input*1.6); else printf("%f km(s) = %f mile(s)\n", input, input/1.6); } int main() { int choice; scanf("%d", &choice); switch (choice) { case 1: km_mile_conv(choice); break; caea 2: km_mile_conv(choice); break; /* more cases */ } }

  10. Function Return and Parameters • The syntax for C functions is the same as Java methods • void keyword can be omitted void km_to_mile(void) { } mile_to_km() { } int main() { int choice; }

  11. /* function prototypes */ double km2mile(double); double mile2km(double); int main() { } /* actual function definitions */ double km2mile(double k) { } double mile2km(double m) { } Function Prototype • A prototype is a function declaration which includes the returntype and a list ofparameters • A way to move function definitions after main • Need not name formal parameters

  12. Function name overloading • Does not exist in C • Exists in C++

  13. Local/Global Variables • Variables declared inside a function are local • Function arguments are local to the function passed to • A global variable is a variable declared outside of any function. • In a name conflict, the local variable takes precedence • When local variable shadows function parameter? int x = 0; int f(int x) { int x = 1; return x; } int main() { int x; x = f(2); }

  14. Scope of Global Variables • The scope of a global variable starts at the point of its definition. • Globals should be used with caution • If using globals at all, declare them at the top. int x; int f() { } int y; int g(){ } int main() { }

  15. Keep main Uncluttered • Your main function should consist mainly of function calls • One main input loop or conditional is okay • Write your main and choose your function name in such a way so that • the main algorithm and program structure is clearly represented • the reader can get an idea how your program works simply by glancing at your main

  16. Program Organization • #include and #define first • Globals if any • Function prototypes, unless included with header file already • int main()– putting your main before all other functions makes it easier to read • The rest of your function definitions

  17. Data Types • Integer types: • different number of bits-different ranges • char:ASCII character, typically 8 bits=1 byte • range –127 to 128 • short: typically 16 bits • int: 32 bits • range ±2 billion • long: typically 32 bits • long long: (some compilers support) 64-bits • Integer types can be preceded by unsigned which disables representing negative numbers • e.g. unsigned char • range 0-255

  18. Data Types Floating-point types • float 4 bytes • double 8 bytes • long double 12 bytes • Floating point constants default to double unless suffixed by f or l • Examples: 0.67f, 123.45f, 1.2E-6f, 0.67, 123.45

  19. Boolean • C does not have type boolean—use int • False is represented by 0 • Any expression evaluates to non-zero is considered true • True is typically represented by 1 however

  20. Constants • Integer • const int year = 2002; • Floating point number • const double pi = 3.14159265; • Constants are variables whose initial value can not be changed. • Comparable to static final

  21. #define • Often used to define constants • #define TRUE 1 #define FALSE 0 • #define PI 3.14 • #define SIZE 20 • Anywhere PI occurs compiler replaces with 3.14 • Offers easy one-touch change of scale/size • #define vs const • The preprocessor directive uses no memory

  22. Types and Casting • Choose types carefully • An arithmetic operation requires that the two values are of the same type • For an expression that involves two different types, the compiler will cast the smaller type to the larger type • Example: 4 * 1.5 = 6.0

  23. Mixing Data Types • int values only  int • 4 / 2  2 • 3 / 2  1 • int x = 3, y = 2; x / y  1 • Involving a double value  double • 3.0 / 2  1.5

  24. sizeof and Type Conversions • sizeof(type) • The sizeof operator returns the number of bytes required to store the given type Implicit conversions • arithmetic • assignment • function parameters • function return type Explicit conversions • casting int x; x = (int) 4.0;

  25. Use of char (character) • Basic operations • Declaration: char c; • Assignment: c = 'a'; • Reference: c = c + 1; • Constants • Single-quoted character (only one) • Some special characters: '\n‘ (newline), '\t' (tab), '\"' (double quote), '\'' (single quote), '\\' (backslash)

  26. Characters are Integers • A char type represents an integer value • A single quoted character is called a “character constant”. • C characters use ASCII representation: • 'A' = 65 … 'Z' = 'A' + 25 = 90 • 'a' = 97 … 'z' = 'a' + 25 = 122 • '0'!= 0 (48),'9' - '0' = 9 • Never make assumptions of char values • Always write 'A' instead of 65

  27. ASCII Table American Standard Code for Information Interchange A standard way of representing the alphabet, numbers, and symbols (in computers)

  28. Output: Value = 100 Output Functions • Output characters printf("Text message\n"); • Output an integer int x = 100; printf("Value = %d\n", x); \n for new line

  29. Output: x = 100, y = 1.230000 Variations • Output a floating-point number double y = 1.23; printf("Value = %f\n", y); • Output multiple numbers int x = 100; double y = 1.23; printf("x = %d, y = %f\n", x, y); 15 digits below decimal (excluding trailing 0’s)

  30. printf Summary printf(" ", ); • Text containing special symbols • %d for an integer • %f for a floating-point number • \n for a newline • List of variables (or expressions) • In the order correspoding to the % sequence

  31. % Specification • (most commonly used ones) • %c convert an int to an unsigned char and print as a character • %iint, char(printas a signed decimal number) • %d same as above (d for decimal) • %ffloat,double(floating-point) • %efloat,double(exponential, e.g., 1.5e3) • %sstring pointed by a char*

  32. Formatting • Precision %.#f • Width %#f, %#d • Note: Entire width • Various combinations of the above and other options available Replace # with digit(s)

  33. Formatting Example %f with 1.23456789 >1.234568< %.10f with 1.23456789 >1.2345678900< %.2f with 1.23456789 >1.23< %d with 12345 >12345< %10d with 12345 > 12345< %2d with 12345 >12345< %f with 1.23456789 >1.234568< %8.2f with 1.23456789 > 1.23<

  34. char Input/Output • Input • char getchar() receives/returns a character • Built-in function • Output • printf with %c specification • putchar() int main() { char c; c = getchar(); printf("Character >%c< has the value %d.\n", c, c); return 0; }

  35. scanf Function scanf(" ", ); • Format string containing special symbols • %d for int • %f for float • %lf for double • %c for char • \n for a newline • List of variables (or expressions) • In the order correspoding to the % sequence

  36. scanf Function • The function scanf is the input analog of printf • Each variable in the list MUST be prefixed with an &. • Ignores white spaces unless format string contains %c

  37. scanf Function int main() { int x; printf("Enter a value:\n"); scanf("%d", &x); printf("The value is %d.\n", x); return 0; }

  38. scanf with multiple variables int main() { int x; char c; printf("Enter an int and a char:"); scanf("%d %c", &x, &c); printf("The values are %d, %c.\n", x, c); return 0; }

  39. Control Structures • Conditionals • if-else • switch • Loops • while • for • do-while • SAME syntax as in Java

  40. Assignment as Expression • Assignment • Assignments are expressions • Evaluates to value being assigned • Example int x = 1, y = 2, z = 3; x = (y = z); 3 3 3 evaluates to 3 (true) if (x = 3) { ... } evaluates to 3

  41. Complex Data Types • Pointers • Arrays • Strings • Structures

  42. Memory 0 1 2 3 4 5 6 7 8 9 30 31 70 31 4 6 30 1 10 4 6 95 201 12 address value Variable and Address • Variable = Storage in computer memory • Contains some value • Must reside at a specific location called address • Basic unit – byte • Imagine memory as a one-dimensional array with addresses as byte indices • A variable consists of one or more bytes, depending on its type (size) char int

  43. Pointer – Reference • A pointer (pointer variable) is a variable that stores an address (like Java reference) • Recall in Java, when one declares variables of a class type, these are automatically references. • In C, pointers have special syntax and much greater flexibility.

  44. Address Operations in C • Declaration of pointer variables • The pointer declarator ‘*’ • Use of pointers • The address of operator ‘&’ • The indirection operator ‘*’ – also known as de-referencing a pointer

  45. ptr1 ptr2 Pointer Declaration • Syntax • destinationType*varName; • Must be declared with its associated type. • Examples • int *ptr1; A pointer to an int variable • char *ptr2; A pointer to a char variable will contain addresses

  46. Pointers are NOT integers • Although memory addresses are essentially very large integers, pointers and integers are not interchangeable. • Pointers are not of the same type • A pointer’s type depends on what it points to • int *p1; • char *p2;

  47. Address of operator 0012FF88 8 ip i (@0012FF88) int i = 8; int *ip; ip = &i;

  48. 1 x 567 567 p q 1 p q x Pointer Assignment • A pointer ppointsto x if x’s address is stored in p • Example • int x = 1; int *p, *q; p = &x; q = p; Interpreted as: address = 567

  49. 2 1 y x p q Pointer Assignment • Example • int x=1, y=2, *p, *q; p = &x; q = &y; q = p; address = 567 address = 988 567 567 988

  50. 1 x p Indirection Operator Note: ‘*’ in a declaration and ‘*’ in an expression are different. int *p; int * p; int* p; • Syntax • *pointerVar • Allows access to value of memory being pointed to • Also called dereferencing • Example • int x = 1, *p; p = &x; printf("%d\n", *p); *p refers to x; thus prints 1

More Related