chapter 7: c language preliminaries 1 chapter 7 c language preliminaries
TRANSCRIPT
Chapter 2 Chapter 7: C Language Preliminaries
1
Chapter 7
C Language Preliminaries
Chapter 7 CS1101C Textbook 2
CS1101C Textbook
C: How To Program
by H.M. Deitel and P.J. Deitel
Prentice Hall, 2nd Edition
ISBN 0-13-288333-3
Chapter 7 Introduction 3
Introduction
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.
Chapter 7 Introduction 4
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
Chapter 7 Algorithmic Problem Solving 5
Algorithmic Problem Solving
Understanding the problem
Writing an algorithm
Converting to code
Verifying the algorithm
Chapter 7 From Problem to Algorithm 6
From Problem to Algorithm
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.
Chapter 7 From Problem to Algorithm 7
From Problem to Algorithm
Step 2: Devising a plan.
First draft of plan (algorithm):
Get length in inchesCompute length in centimetresReport length in centimetres
What is the relationship between the data and the unknown?
1 inch = 2.54 centimetres
Chapter 7 From Problem to Algorithm 8
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 inchesCompute length in centimetres, using
2.54 * length in inchesReport length in centimetres
Chapter 7 From Problem to Algorithm 9
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.
Chapter 7 From Problem to Algorithm 10
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.
Chapter 7 From Algorithm to Program 11
From Algorithm to Program
inch2cm.c
/* * Converts length from inches to centimetres * Author: Garfield Date: 25 July 1997 * Note: This program contains a hard-to-spot error! */
#include <stdio.h> /* printf, scanf definitions */#define CM_PER_INCH 2.54 /* conversion constant */
int main (void){ float inches, /* length in inches cm; length in centimetres */
/* get the length in inches */ printf ("Enter a length in inches: "); scanf ("%f", &inches);
/* convert to length in centimetres */ cm = CM_PER_INCH * inches;
/* display the length in centimetres */ printf ("That equals %.2f centimetres.\n\n", cm);
return 0; /* indicate program ends successfully */}
Chapter 7 Sample Runs 12
Sample Runsgarfield@decunx:~/c[xx]: cc -o inch2cm inch2cm.cgarfield@decunx:~/c[xx]: inch2cmEnter a length in inches: 2That equals 5.08 centimetres.
garfield@decunx:~/c[xx]: inch2cmEnter a length in inches: 5.9That equals 14.99 centimetres.
garfield@decunx:~/c[xx]: inch2cmEnter a length in inches: 0That equals 0.00 centimetres.
garfield@decunx:~/c[xx]: inch2cmEnter a length in inches: –2That equals –5.08 centimetres.
garfield@decunx:~/c[xx]: inch2cmEnter a length in inches: 1.2e4That equals 30480.00 centimetres.
Chapter 7 Preprocessor Directives 13
Preprocessor Directives
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.
Chapter 7 Preprocessor Directives 14
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.
Chapter 7 Preprocessor Directives 15
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?
Chapter 7 Comments 16
Comments
/* 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.
Chapter 7 Comments 17
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;
Chapter 7 Comments 18
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’.
Chapter 7 Comments 19
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 */
Chapter 7 The main() Function 20
The main() Function
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 */ }
Chapter 7 The main() Function 21
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
Chapter 7 The main() Function 22
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?
Chapter 7 The main() Function 23
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.
Chapter 7 The main() Function 24
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.
Chapter 7 The main() Function 25
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
Chapter 7 The main() Function 26
The main() Function
Declarations are statements that declare local variables used in the function.
Compiler allocate memory space for all variables.
Chapter 7 Keywords 27
Keywords
Keywords are reserved words in C language with special meanings, and cannot be redefined.
auto default float long sizeof unionbreak do for register static unsignedcase double goto return struct voidchar else if short switch volatileconst enum int signed typedef whilecontinue exterm
Chapter 7 Identifiers 28
Identifiers
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.
Chapter 7 Identifiers 29
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_numbersssum
Chapter 7 Identifiers 30
Identifiers
Identifiers are case sensitive.
By convention, identifiers for constant macros (symbolic constants) are usually in upper-case letters. Example: CM_PER_INCH
Chapter 7 Constants 31
Constants
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.
Chapter 7 Constants 32
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
Chapter 7 Constants 33
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.
Chapter 7 Variable Declarations 34
Variable Declarations
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;
orfloat inches, cm;
Chapter 7 Data Types 35
Data Types
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.
Chapter 7 Data Types 36
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.
Chapter 7 Data Types 37
Data Types
char: character data type. Example of values of this type: 'a', 'P', '3', '#', ' '.
Chapter 7 Programming Style 38
Programming Style
Indentation: to show the 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");
Chapter 7 Programming Style 39
Programming Style
Blank lines: to separate functions, or logical blocks.
Naming of identifiers.int main (void){ float inches, /* length in inches cm; length in centimetres */
/* get the length in inches */ printf ("Enter a length in inches: "); scanf ("%f", &inches);
/* convert to length in centimetres */ cm = CM_PER_INCH * inches;
/* display the length in centimetres */ printf ("That equals %.2f centimetres.\n\n", cm);
return 0; /* indicate program ends successfully */}
Chapter 7 Data Validation 40
Data Validation
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.
garfield@decunx:~/c[xx]: inch2cmEnter a length in inches: –2That equals –5.08 centimetres.
Chapter 7 Data Validation 41
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.
Chapter 7 Variables and Memory 42
Variables and Memory
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.
Chapter 7 Variables and Memory 43
Variables and Memory
Example: float inches, cm;
Program inch2cm
Memory
Address1000
10011002
::
1500 inches
1508 cm
Chapter 7 Variables and Memory 44
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
Chapter 7 Variables and Memory 45
Variables and Memory
Initialisation at declaration:
float inches = 3.2;
Using assignment statement:
inches = 3.2;
Using an input function:
scanf ("%f", &inches);
before
? 3.2
1500 (inches)
1500 (inches)User
enters3.2
after
Chapter 7 Variables and Memory 46
Variables and Memory
Destructive write, non-destructive read.
int a, b;
a = 40;
b = 50;
b = a + b;
before
after
? 40
? 50
40
50
40
90
2340 (a)
2340 (a)
2344 (b)
2344 (b)
2340 (a)
2340 (a)
2344 (b)
2344 (b)
Chapter 7 Homework 47
Homework
Try exercises behind chapter 7.