470 likes | 559 Views
C Language Preliminaries. Chapter 7. CS1101C Textbook. C: How To Program by H.M. Deitel and P.J. Deitel Prentice Hall, 2nd Edition ISBN 0-13-288333-3. 1972 by Dennis Ritchie at Bell Lab. ALGOL60 CPL BCPL B C ANSI C: standardised. C is a high-level language.
E N D
C Language Preliminaries Chapter 7 Chapter 7: C Language Preliminaries
CS1101C Textbook C: How To Program by H.M. Deitel and P.J. Deitel Prentice Hall, 2nd Edition ISBN 0-13-288333-3 CS1101C Textbook
1972 by Dennis Ritchie at Bell Lab. ALGOL60 CPL BCPL B C ANSI C: standardised. C is a high-level language. C is a procedural language. C is baffling to look at, easy to mess up, and tricky to learn. Introduction Introduction
Some articles (more in CS1101C web site, under ‘CA Activities/Readings & Preparation’): The Ten Commandments for C Programmers The Top 10 Ways to get screwed by the C programming language Introduction Introduction
Understanding the problem Writing an algorithm Verifying the algorithm Converting to code Algorithmic Problem Solving Algorithmic Problem Solving
Conversion from inches to centimetres. Step 1: Understanding the problem. What is the the data (input)? Length in inches. Let’s call it inches. What is the unknown (output)? Length in centimetres. Let’s call it cm. From Problem to Algorithm From Problem to Algorithm
Step 2: Devising a plan. First draft of plan (algorithm): Get length in inches Compute length in centimetres Report length in centimetres What is the relationship between the data and the unknown? 1 inch = 2.54 centimetres From Problem to Algorithm From Problem to Algorithm
Step 2: Devising a plan. (continue…) Do I know how to compute the length in cm? Yes. Length in cm is: 2.54 times length in inches Complete plan (algorithm): Get length in inches Compute length in centimetres, using 2.54 * length in inches Report length in centimetres From Problem to Algorithm From Problem to Algorithm
Step 2: Devising a plan. (continue…) Is the plan correct? Walk through the plan. Work out on some examples: 1 inch, 2 inches, 3.5 inches, 0 inch, etc. From Problem to Algorithm From Problem to Algorithm
Step 3: Carrying out the plan. Convert algorithm to program. Compile and run. Step 4: Looking back. Check the output. Is the output correct? In general, an algorithm may need to go through a few rounds of refinements. From Problem to Algorithm From Problem to Algorithm
inch2cm.c From Algorithm to Program From Algorithm to Program
Sample Runs Sample Runs
C system = C language + preprocessor + libraries Preprocessor modifies program before it is compiled. Common directives: #include and #define # must be first non-blank character on the line. Preprocessor Directives Preprocessor Directives
#include <stdio.h> Includes header file stdio.h from /usr/include directory into program. stdio.h contains functions prototypes of scanf(), printf() and others, so that inch2cm.c can use these functions. #include "file" assumes file in current directory. Preprocessor Directives Preprocessor Directives
#define CM_PER_INCH 2.54 Defines constant macro (or symbolic constant) CM_PER_INCH as 2.54 Preprocessor replaces each occurrence of CM_PER_INCH in the rest of program to 2.54. cm = CM_PER_INCH * inches; cm = 2.54 * inches; Purpose? Preprocessor Directives Preprocessor Directives
/* this is a line of comments */ Comments are text enclosed in /* and */. Some compilers accept //. Comments provide documentation for program readability. Every program should have its author and date written documented. Every program and function should have a statement to describe its purpose. Comments Comments
Right dosage is important. Too much: i++; /* increment i by 1 */ sum += num; /* add num to sum */ /* multiply CM_PER_INCH by inches */ /* and store result in cm */ cm = CM_PER_INCH * inches; Comments Comments
Comments add values to readers. Should describe what the steps do and explain difficult logic, instead of translating C statements into English. Comments explain the purpose; program statements show the logic. Self-explanatory codes do not need much comments. Name variables appropriately. Examples: ‘width’ instead of ‘w’. Comments Comments
Do not fill in comments as an after-thought. Documentation should begin at design, and follows through every phase. Spot the error: float inches, /* length in inches cm; length in centimetres */ Comments Comments
C program consists of functions. At least one function must be present: main(). Execution of the program starts at this function. Example: int main (void) { /* body of function */ } The main() Function The main() Function
Function consists of header and body. Function header: The type of the function -- eg: int. The name of the function -- eg: main The parameter list enclosed in parentheses -- eg: void The main() Function The main() Function
Function type: the type of value this function produces. If function type is not ‘void’, then there should be a return statement to return the result of the function. Example: return 0; Execution of the function ends when the return statement is executed, or when the last statement is executed. Where is the result returned to? The main() Function The main() Function
A function returns its result (and control) to its caller. The caller for the main() function is the operating system. Zero is usually returned to UNIX to signal the successful completion of the program. The main() Function The main() Function
A function parameter lists the arguments which the function takes from its caller. For example: printf ("Enter a length in inches: "); scanf ("%f", &inches); "Enter a length in inches: " is an argument to the printf() function. "%f" and &inches are arguments to the scanf() function. A void parameter indicates no argument. The main() Function The main() Function
Function body: Declarations Executable statements Example: int main (void) { int a, b, c; b = 5; c = 3; a = b + c; return 0; } declarations statements The main() Function The main() Function
Declarations are statements that declare local variables used in the function. Compiler allocate memory space for all variables. The main() Function The main() Function
Keywords are reserved words in C language with special meanings, and cannot be redefined. Keywords Keywords
Identifiers are names given to objects (variables and functions). Two types of identifiers: standard and user-defined. Standard identifiers are predefined names, like printf and scanf. They may be redefined, but preferably not. User-defined identifiers are created by programmers to name variables and functions. Identifiers Identifiers
Syntax for an identifier: consists of letters, digits and underscore (_), but may not begin with digit. Avoid naming an identifier starting with underscore (_). Choose appropriate identifiers for variable names and function names. Compare these identifiers for a particular variable: sum_of_list_of_numbers s sum Identifiers Identifiers
Identifiers are case sensitive. By convention, identifiers for constant macros (symbolic constants) are usually in upper-case letters. Example: CM_PER_INCH Identifiers Identifiers
Constants are often used in programs for values that do not change. Examples: perimeter = 2 * (length + breadth); rem = count % 7; printf ("Hello\n"); Types of constants: numeric constants, character constants, and string constants. Constants Constants
Numeric contants: integers (decimal, octal, and hexadecimal) and floating-point numbers. Examples: 123, -345, +12 0123, 05 0x2A, 0x88 1.234, -0.00987, 1.2e-4, -3.5E3 Constants Constants
Character contants: a single character enclosed in single quotes. Examples: 'A', 'b', '^', '9', '+' String contants: a sequence of characters enclosed in double quotes. Examples: "Hello\n", "ABC", "34.56" A null character, \0, is appended at the end of the string. 'K' and "K" are different. Constants Constants
Variables must be declared before they can be used. Variables are declared in the declaration statements in a function. The declaration of a variable consists of its name and its type of value. float inches; float cm; or float inches, cm; Variable Declarations Variable Declarations
A data type defines a set of values and a set of operations permissible on those values. Basic data types: int, float, double, char. int: integer data type. Example of values of this type: 123, -900, 987654321, +31. An integer occupies a fixed number of bytes, so there is a range of values that can be represented. Data Types Data Types
float: floating-point data type. Example of values of this type: 4.3, -123.00, +0.02, 1.2e4, -86e3, 3.9e-12. A floating-point representation consists of mantissa (fraction part) and exponent, with an assumed base. double: double-precision floating-point data type. It uses twice the number of bits in the mantissa, hence it may represent more precise values. Data Types Data Types
char: character data type. Example of values of this type: 'a', 'P', '3', '#', ' '. Data Types Data Types
Indentation: to showthe hierarchy of logic. if (x < y) { printf ("x is smaller than y\n"); if (y < z) printf ("y is smaller than z\n"); else printf ("y is larger than or equal to z\n"); } else printf ("x is larger than or equal to y\n"); Programming Style Programming Style
Blank lines: to separate functions, or logical blocks. Naming of identifiers. Programming Style Programming Style
Examine this run: Should -2 be accepted? Data validation: to validate input data and take necessary actions. A rugged program should not terminate abruptly under all circumstances -- ultimate aim. Data Validation Data Validation
But this is too ambitious. An easy way out is to make assumptions, and document them in the program as pre-conditions. Compromise: include simple data validation checks, whenever possible. Data Validation Data Validation
A variable has name, type and value. Each variable is allocated some memory location(s) to hold its value. Such allocation occurs at the variable declaration statements. Every memory location has an address. However, programmer only needs to refer to the variable by its name, and leaves it to the system to work out the address. Variables and Memory Variables and Memory
Example: float inches, cm; Memory Address 1000 1001 1002 : : Program inch2cm 1500 inches 1508 cm Variables and Memory Variables and Memory
Initially, the value of a variable is undefined. A variable must be initilialised before its value is used. 3 ways to assign a value into a variable Initialising the variable at declaration Use the assignment statement Use the input function Variables and Memory Variables and Memory
Initialisation at declaration: float inches = 3.2; Using assignment statement: inches = 3.2; Using an input function: scanf ("%f", &inches); 1500 (inches) 1500 (inches) User enters 3.2 ? 3.2 before after Variables and Memory Variables and Memory
Destructive write, non-destructive read. int a, b; a = 40; b = 50; b = a + b; before after 2340 (a) 2340 (a) ? 40 2344 (b) 2344 (b) ? 50 2340 (a) 2340 (a) 40 40 2344 (b) 2344 (b) 50 90 Variables and Memory Variables and Memory
Try exercises behind chapter 7. Homework Homework