1 / 50

COSC3306: Programming Paradigms Lecture 5: Imperative Programming with C Language

COSC3306: Programming Paradigms Lecture 5: Imperative Programming with C Language. Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003. Why C. Why C. C’s characteristics. C is very famous for its duality as: Both a high-level and low level

gavrilla
Download Presentation

COSC3306: Programming Paradigms Lecture 5: Imperative Programming with C 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. COSC3306:Programming ParadigmsLecture 5: ImperativeProgramming with C Language Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003

  2. Why C

  3. Why C

  4. C’s characteristics • C is very famous for its duality as: • Both a high-level and low level • Both a special and general purpose. • In C there are six kinds of tokens: • Identifiers • Keywords • Constants • String Literals • Operators • Punctuators

  5. Lexical Elements • Reserved Words in C language. • auto break case char const continue • default do double else enum extern • float for goto if int long • register return short signed sizeof static • struct switch typedef union unsigned • void volatile while

  6. Data Types • There are only a few basic data types in C: • char, a single byte, capable of holding one character. • int, an integer, reflecting the size of integers on the machine. • float, a single precision floating point. • double, a double precision floating point.

  7. Data Types • There are a number of quantifiers that can be applied to the basic data types: • short int, reflecting 16-bits as the size of the integer number. • long int, reflecting 32-bits as the size of the integer number. • long double, reflecting extended precision floating point number. EX7-1.cpp

  8. Constants • C manipulates various kinds of values such as integer-constant, character-constant, floating-constant, and enumeration-constant. • Whole numbers like 0 and 17 are examples of integer constants. • Octal constants begin with 0 (digit zero), and do not contain the digits 8 or 9. • A sequence of digits preceded by 0x or 0X (digit zero) is taken to be a hexadecimal integer, and digits include a or A through f or F with values 10 through 15. Fractional numbers like 1.0 and 7.14159 are example of floating constants. • Also, character constants are written between single quotes; examples are ‘a’, ‘b’, and ‘+’. Identifiers declared as enumerators are constants of type integer.

  9. String Literals • A sequence of characters enclosed in a pair of double quote marks, such as “abc” is a string constant, or a string. • String constants are always treated differently from character constants. For example, “a” and ‘a’ are not the same.

  10. Operators and Punctuators • In C, there are many special characters with particular meaning. •  ++ -- • y  x  1; • y  x  1; • Assignment Operators in C language. • |

  11. Operators and Punctuators • expression1 ? expression2 : expression3; • a  b ? 10 : 20; • results a to be 20 if b is zero and sets a to 10 if b is not zero.

  12. Relational, Equality, and Logical operators. • Relational operators less than  • greater than  • less than or equal  • greater than or equal  • Equality operators equal to  • not equal to  • Logical operators negation  • logical and  • logical or 

  13. Arrays • int grade[3]; • int class[3][4]; Column 1 Column 2 Column 3 Column 4 Row 1 class[0][0] class[0][1] class[0][2] class[0][3] Row 2 class[1][0] class[1][1] class[1][2] class[1][3] Row 3 class[2][0] class[2][1] class[2][2] class[2][3] EX7-2.cpp

  14. Functions • Return-type function-name(parameter names) • parameter declarations • { • Declarations and statements • } Ex7-3.cpp

  15. Function Pointers • void fp(int (*f)(int , int), int x, int y) • { • printf ("%d \n", f(x,y)); • } Ex7-4.cpp

  16. Initialization • Arrays can be initialized within a declaration. Initialization is a sequence of values written as a brace enclosed comma separated list. An example is • float x[3]  {1.1, 0.2, 22.0}; • when this initializes x[0] to 1.1, x[1] to 0.2, and x[2] to 22.0.

  17. © 2003 Brooks/Cole Publishing / Thomson Learning™ Addressing and Dereferencing • After the assignment statements • a  b  7; • p  &a; • It becomes the next slide.

  18. © 2003 Brooks/Cole Publishing / Thomson Learning™ printf( “ pointer variable p points to the value %d ”, p);

  19. Structures • The structure type allows to aggregate components into a single variable. • Structures may contain variables of different data types; in contrast to arrays that contain only elements of the same data type. • A structure has components that are individually named; called members. Consider the following structure definition: • struct class { • char grade; • int total_points; • float gpa; • }; class.grade  ‘A’; class.total_points  97; class.gpa  7.87;

  20. Unions • Unlike a structure, a union is a derived data type whose members share the same storage space. In other words, a union is a variable that may hold (at different times) objects of different types and sizes. In this case, the compiler keeps track of size and alignment requirements. In C unions are given directly and are undiscriminated. As an example, suppose that a constant may be an integer, a float, or a character. This can be the purpose of a union; a single variable that can legitimately hold any one these types. In the following: • union number { • int int_number; • float float_number; • char char_number; • } x_number; x_number.int_number  123; x_number.float_number  12.5; x_number.char_number  ‘A’; EX7-5.cpp

  21. To be continued • Control Structures • Input and output • Preprocessor • C’s pros and cons

  22. Conditional Constructs • if (expression) • statement1 • Statement2 • if (grade  90) • printf(“Congratulation!”); • printf(“Your Grade is %d “, grade);

  23. Conditional Constructs • if (expression) • statement1 • else • statement2 • statement3 if (x  y) min  x; else min  y; printf( “Min Value  %d ”, min);

  24. Switch-Case • switch (expression) • { • case v1: statements; • case v2: statements; • case v3: statements; • …… • default: statements; • }

  25. Iterative Constructs • while (expression) • statement1 • statement2 while (i  10) { sum  i ;  i; }

  26. Iterative Constructs • for (expr1; expr2; expr3) statement1 • (expr2) • statement2 expr1; while (expr2) { statement1 expr3; } statement2 for (i0; i  10;  i) { sum  i; } EX7-6 EX7-6-1

  27. Formatting Input • The input function scanf( ) has the following two properties that allow it flexibility at a high level. • A list of arguments of arbitrary length can be scanned. • The input is controlled by simple conversion specifications or formats.

  28. Formatting Input • The scanf( ) reads characters from the standard input file named stdin. The scanf function is written in the following form: • scanf(format-control-string, argument-list); • The format-control-string describes the format of the input, and the argument-list is pointers to variables in which the input is stored. The argument-list consists of a comma separated list of pointer expressions, or addresses.

  29. Formatting Input • char a; • int b; • float c; • char s[25]; • scanf( “ %c%d%f%s ”, &a, &b, &c, s); • we have • format-control-string: “ %c%d%f%s ” • argument-list: &a, &b, &c, s EX7-7

  30. Conversion specifiers for scanf. Specifier Description d read a signed decimal integer. i read a signed decimal, octal, or hexadecimal. o read an octal integer. u read an unsigned decimal integer. x or X read a hexadecimal integer. E, e, f, g or G read a floating-point value. h or l place before any of the integer conversion specifiers to indicate that a short or long integer is to be input. l or L place before any of the floating-point conversion specifiers to indicate that a double or long double value is to be input. c read a character. s read a string. p read a pointer address of the same form produced when an address is output with p in a printf statement. n store the number of characters input so far in this scanf. The corresponding argument is a pointer to integer. % skip a percent sign (%) in the input.

  31. Formatting Output • Precise output formatting is accomplished with printf function. The printf function has the following form: • printf(format-control-string, argument-list); • The format-control-string describes the output format, and the argument-list which is optional correspond to each conversion specification in the format-control-string.

  32. Formatting Output • In the example • printf( “ she sold %d %s for $%f ”, 99, “ books ”, 12.57); • we have • format-control-string: “ she sold %d %s for $%f ” • argument-list: 99, “ books ”, 12.57 Ex7-7-1

  33. sprintf( ) and sscanf( ) • The functions sprintf( ) and sscanf( ) are string versions of the functions printf( ) and scanf( ), respectively. They are formed as the following: • sscanf(string, format-control-string, argument-list); • sprintf(string, format-control-string, argument-list); • in which sscanf reads from the character array string, and sprintf writes to the character array string. In addition, the functions fprintf( ) and fscanf( ) are the file versions of the printf and scanf functions, respectively. Ex7-8, ex7-9

  34. fprintf( ) and fscanf( ) • A statement of the form: • fscanf(file-pointer, format-control-string, argument-list); • reads from the file pointed to by file-pointer. In a similar fashion, a statement of the form • fprintf(file-pointer, format-control-string, argument-list); • writes to the file pointed to by file-pointer. The conventions for format-control-string and argument-list follows the same as printf and scanf functions. EX7-10

  35. Preprocessor • Lines that begin with a # are called preprocessing directives. These lines communicate with the preprocessor. Preprocessing occurs before a program is compiled. Some possible actions are: inclusion of other files in the file being compiled, definition of symbolic constants and macros, conditional compilation of program code, and conditional execution of preprocessor directives.

  36. #if DLEVEL > 5 #define SIGNAL 1 #if STACKUSE == 1 #define STACK 200 #else #define STACK 100 #endif #else #define SIGNAL 0 #if STACKUSE == 1 #define STACK 100 #else #define STACK 50 #endif #endif #if DLEVEL == 0 #define STACK 0 #elif DLEVEL == 1 #define STACK 100 #elif DLEVEL > 5 display( debugptr ); #else #define STACK 200 #endif Preprocessor • #include • #define • #if • #else • #ifdef • #endif • #ifndef

  37. Preprocessor • In traditional C, preprocessing directives are required to begin in column 1. In ANSI C this restriction is not imposed. Some examples of preprocessing directives are • #include stdio.h • #define PI 7.14159 • #include “ filename ” • The last one causes the preprocessor to replace the line with a copy of the contents of the named file. First a search for the file is made in the current directory and then in other system dependent places. With a preprocessing directive of the form • #include filename • the preprocessor looks for the file only in the other places and not in the current directory.

  38. Preprocessor • Directive Description • #error tokens prints an implementation- dependent message including the tokens • specified in the directive. • #line number starts line numbering from number beginning with the next source code line. • #define id value causes all subsequent occurrences of id will be replaced by value. • #if condition causes a conditional checking based on the condition.

  39. Example #define DLEVEL 10 …… #if DLEVEL > 5 #define SIGNAL 1 #if STACKUSE == 1 #define STACK 200 #else #define STACK 100 #endif #else #define SIGNAL 0 #if STACKUSE == 1 #define STACK 100 #else #define STACK 50 #endif #endif #if !defined(xyz) #error xyz undefined. #endif EX7-11

  40. C’s pros and cons • Close to the machine • Very flexible • C is preferred in embedded applications • Difficult in debugging • C is not preferred in business applications

  41. BNF • What is BNF notation? • BNF is an acronym for "Backus Naur Form". John Backus and Peter Naur introduced for the first time a formal notation to describe the syntax of a given language (This was for the description of the ALGOL 60 programming language, see [Naur 60]). To be precise, most of BNF was introduced by Backus in a report presented at an earlier UNESCO conference on ALGOL 58. • BNF is not only important to describe syntax rules in books, but it is very commonly used (with variants) by syntactic tools. See for example any book on LEX and YACC, the standard UNIX parser generators. If you have access to any Unix machine, you will probably find a chapter of the documentation on these tools.

  42. The meta-symbols of BNF • ::= • meaning "is defined as" • | • meaning "or" • < > • angle brackets used to surround category names. • The angle brackets distinguish syntax rules names (also called non-terminal symbols) from terminal symbols which are written exactly as they are to be represented.

  43. Nonterminal • A nonterminal has the form: • nonterminal ::= sequence_of_alternatives consisting of strings of terminals or nonterminals separated by the meta-symbol | • For example, the BNF production for a mini-language is: • <program> ::= program <declaration_sequence> Begin <statements_sequence> end ; • This shows that a mini-language program consists of the keyword "program" followed by the declaration sequence, then the keyword "begin" and the statements sequence, finally the keyword "end" and a semicolon.

  44. A real example • Below is a sample BNF grammar: • S := - FN | FN • FN := DL | DL . DL • DL := D | D DL • D := 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 • The different symbols here are all abbreviations: S is the start symbol, FN produces a fractional number, DL is a digit list, while D is a digit. • Valid sentences in the language described by this grammar are all numbers, possibly fractional, and possibly negative. To produce a number, start with the start symbol S: • S • Then replace the S symbol with one of its productions. In this case we choose not to put a '-' in front of the number, so we use the plain FN production and replace S by FN: • FN • The next step is then to replace the FN symbol with one of its productions.

  45. Example • The next step is then to replace the FN symbol with one of its productions. We want a fractional number, so we choose the production that creates two decimal lists with a '.' between them, and after that we keep choosing replacing a symbol with one of its productions once per line in the example below: • DL . DL • D . DL • 3 . DL • 3 . D DL • 3 . D D • 3 . 1 D • 3 . 1 4 • Here we've produced the fractional number 3.14. How to produce the number -5 is left as an exercise for the reader. • To make sure you understand this you should also study the grammar until you understand why the string 3..14 cannot be produced with these production rules.

  46. EBNF • Extended BNF improves the readability and conciseness of BNF through extensions: • Kleene cross -- a sequence of one or more elements of the class marked. • <unsigned integer> ::= <digit>+ • Kleene star -- a sequence of zero or more elements of the class marked. • <identifier> ::= <letter><alphanumeric>* • Braces can be used to represent a sequence of zero or more instances of elements: • <identifier> ::= <letter>{<letter>|<digit>} • or a group of elements <identifier> ::= <letter>{<letter>|<digit>}* • Square brackets may be used to indicate optional elements (i.e., zero or one occurrence of the enclosed elements). • <integer> ::= [ + | - ]<unsigned integer>

  47. EBNF example • So in extended BNF the above grammar can be written as: • S := - D+ {. D+} | D+ {. D+} • D := 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 • EBNF is not more powerful than BNF in terms of what languages it can define, just more convenient. Any EBNF production can be translated into an equivalent set of BNF productions.

  48. Uses of BNF and EBNF • Most programming language standards use some variant of EBNF to define the grammar of the language. This has two advantages: there can be no disagreement on what the syntax of the language is, and it makes it much easier to make compilers, because the parser for the compiler can be generated automatically with a compiler-compiler like YACC. • EBNF is also used in many other standards, such as definitions of protocol formats, data formats and markup languages such as XML and SGML. (HTML is not defined with a grammar, instead it is defined with an SGML DTD, which is sort of a higher-level grammar.)

  49. Grammar for assignment with BNF and EBNF

  50. Summary • Why Programming in C • Data type • Control structure • Input/output • Preprocessor • Advantages and disadvantages • BNF and EBNF

More Related