COSC 3306 Programming Paradigms Lecture 5 Imperative Programming

  • Slides: 50
Download presentation
COSC 3306: Programming Paradigms Lecture 5: Imperative Programming with C Language Haibin Zhu, Ph.

COSC 3306: Programming Paradigms Lecture 5: Imperative Programming with C Language Haibin Zhu, Ph. D. Computer Science Nipissing University (C) 2003 1

Why C 2

Why C 2

Why C 3

Why C 3

C’s characteristics C is very famous for its duality as: – Both a high-level

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 4

Lexical Elements Reserved Words in C language. auto default float register struct void break

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

Data Types There are only a few basic data types in C: – char,

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. 6

Data Types There a number of quantifiers that can be applied to the basic

Data Types There 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. EX 7 -1. cpp 7

Constants C manipulates various kinds of values such as integerconstant, character-constant, floating-constant, and enumeration-constant.

Constants C manipulates various kinds of values such as integerconstant, 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 0 x or 0 X (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. 8

String Literals A sequence of characters enclosed in a pair of double quote marks,

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. 9

Operators and Punctuators In C, there are many special characters with particular meaning. –

Operators and Punctuators In C, there are many special characters with particular meaning. – – ++ -- y x 1; y x 1; Assignment Operators in C language. | 10

Operators and Punctuators expression 1 ? expression 2 : expression 3 ; a b

Operators and Punctuators expression 1 ? expression 2 : expression 3 ; a b ? 10 : 20; results a to be 20 if b is zero and sets a to 10 if b is not zero. 11

Relational, Equality, and Logical operators. Relational operators Equality operators Logical operators less than greater

Relational, Equality, and Logical operators. Relational operators Equality operators Logical operators less than greater than less than or equal greater than or equal to not equal to negation logical and logical or 12

Arrays int Row 1 Row 2 Row 3 grade[3]; class[3][4]; Column 1 class[0][0] class[1][0]

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

Functions Return-type function-name(parameter names) parameter declarations { Declarations and statements } Ex 7 -3.

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

Function Pointers void fp(int (*f)(int , int), int x, int y) { printf ("%d

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

Initialization Arrays can be initialized within a declaration. Initialization is a sequence of values

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. 16

Addressing and Dereferencing © 2003 Brooks/Cole Publishing / Thomson Learning™ After the assignment statements

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

© 2003 Brooks/Cole Publishing / Thomson Learning™ printf( “ pointer variable p points to

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

Structures The structure type allows to aggregate components into a single variable. Structures may

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; 19

Unions Unlike a structure, a union is a derived data type whose members share

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_number; float_number; char_number; x_number. int_number 123; } x_number; x_number. float_number 12. 5; EX 7 -5. cpp x_number. char_number ‘A’; 20

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

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

Conditional Constructs if (expression) statement 1 Statement 2 if (grade 90) printf(“Congratulation!”); printf(“Your Grade

Conditional Constructs if (expression) statement 1 Statement 2 if (grade 90) printf(“Congratulation!”); printf(“Your Grade is %d “, grade); 22

Conditional Constructs if (expression) statement 1 else statement 2 if (x y) statement 3

Conditional Constructs if (expression) statement 1 else statement 2 if (x y) statement 3 min x; else min y; printf( “Min Value %d ”, min); 23

Switch-Case switch (expression) { case v 1: statements; case v 2: statements; case v

Switch-Case switch (expression) { case v 1: statements; case v 2: statements; case v 3: statements; …… default: statements; } 24

Iterative Constructs while (expression) statement 1 statement 2 while (i 10) { sum i

Iterative Constructs while (expression) statement 1 statement 2 while (i 10) { sum i ; i; } 25

Iterative Constructs for (expr 1; expr 2; expr 3) statement 1 expr 1; (expr

Iterative Constructs for (expr 1; expr 2; expr 3) statement 1 expr 1; (expr 2) while (expr 2) statement 2 statement 1 expr 3; statement 2 for } (i 0; i 10; i) sum i; { } { EX 7 -6 -1 26

Formatting Input The input function scanf( ) has the following two properties that allow

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. 27

Formatting Input The scanf( ) reads characters from the standard input file named stdin.

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. 28

Formatting Input char a; int b; float c; char s[25]; scanf( “ %c%d%f%s ”,

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 EX 7 -7 29

Conversion specifiers for scanf. Specifier d i o u x or X E, e,

Conversion specifiers for scanf. Specifier d i o u x or X E, e, f, g or G h or l l or L c s p n % Description read a signed decimal integer. read a signed decimal, octal, or hexadecimal. read an octal integer. read an unsigned decimal integer. read a hexadecimal integer. read a floating-point value. place before any of the integer conversion specifiers to indicate that a short or long integer is to be input. place before any of the floating-point conversion specifiers to indicate that a double or long double value is to be input. read a character. read a string. read a pointer address of the same form produced when an address is output with p in a printf statement. 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. 30

Formatting Output Precise output formatting is accomplished with printf function. The printf function has

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. 31

Formatting Output In the example printf( “ she sold %d %s for $%f ”,

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 Ex 7 -7 -1 32

sprintf( ) and sscanf( ) The functions sprintf( ) and sscanf( ) are string

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. Ex 7 -8, ex 7 -9 33

 fprintf( ) and fscanf( ) A statement of the form: fscanf(file-pointer, format-control-string, argument-list);

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 format-control-string and argument-list follows the same as printf and scanf functions. EX 7 -10 34

Preprocessor Lines that begin with a # are called preprocessing directives. These lines communicate

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. 35

Preprocessor #include #define #if #else #ifdef #endif #ifndef #if DLEVEL > 5 #define SIGNAL

Preprocessor #include #define #if #else #ifdef #endif #ifndef #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 #if DLEVEL == 0 #define STACK 0 #elif DLEVEL == 1 #define STACK 100 #elif DLEVEL > 5 display( debugptr ); #else #define STACK 200 #endif 36

Preprocessor In traditional C, preprocessing directives are required to begin in column 1. In

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. 37

Preprocessor Directive #error tokens #line number #define id value #if condition Description prints an

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

Example #if !defined(xyz) #error xyz undefined. #endif EX 7 -11 #define DLEVEL 10 ……

Example #if !defined(xyz) #error xyz undefined. #endif EX 7 -11 #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 39

C’s pros and cons Close to the machine Very flexible – C is preferred

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 40

BNF What is BNF notation? – BNF is an acronym for "Backus Naur Form".

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. 41

The meta-symbols of BNF : : = – meaning "is defined as" | –

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. 42

Nonterminal A nonterminal has the form: – nonterminal : : = sequence_of_alternatives consisting of

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. 43

A real example Below is a sample BNF grammar: – – S : =

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 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. 44

Example The next step is then to replace the FN symbol with one of

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. D 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. 45

EBNF Extended BNF improves the readability and conciseness of BNF through extensions: Kleene cross

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> 46

EBNF example So in extended BNF the above grammar can be written as: –

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. 47

Uses of BNF and EBNF Most programming language standards use some variant of EBNF

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 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. ) 48

Grammar for assignment with BNF and EBNF 49

Grammar for assignment with BNF and EBNF 49

Summary Why Programming in C Data type Control structure Input/output Preprocessor Advantages and disadvantages

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