Lecture 2

advertisement
Chapter 2
Basic Elements of the C
Programming Language
C
Programming for Scientists &
Engineers with Applications
by Reddy & Ziegler
Introduction to C
C is a structured programming
language.
C has 3 basic control structures of
sequence
selection
repetition
The function is the 4th control
structure in C.
Procedural Language
Any complex logic modules resulting from the modular
design process can be implemented as separate
procedures. In C, these procedures are called
functions.
The main function starts with the function name main
and a statement block as shown.
int main()
{
statement block
return 0;
}
main function
There must always be a main function on C.
Program execution starts at the beginning of the
main function and stops at the end.
Every function must be both declared and
defined.
A function declaration is a prototype consisting of the
return type, the function name,
and the parameter type list.
For example,
int round(float);
implementation of the
function named round
int round(float x)
x is declared to be the name of the parameter
{
int y;
y is declared to be the name of the result
y = (int)(x+0.5);
return(y);
}
Statically Typed language
In C, the data types of variables and functions
must be declared.
The basic or built-in data types are
integer (int),
floating-point (float),
double precision (double), and
character (char).
Constants & Variables
Constants are values that are not usually named.
Variables are similar to variables in algebraic
expressions and mathematical formulas.
Variables have names and can have different
values at different times.
When names are used for constants and variables,
the programmer must assign values to these
constant and variable names before they are
used in calculations or as output.
Constants & Variables
A constant or a variable is undefined until a
value is assigned.
A variable with a given name can have one value
assigned at a time.
A name declared as a constant must not have its
value changed.
Both names and assigned values must be written
according to the rules of the C Language.
Character Set
The C language has a finite set of
symbols called the character set.
Alphabetic Characters
Numeric Characters
Some Special Characters
Alphabetic Characters
These are the 26 uppercase and 26
lowercase letters of the English
alphabet:
ABCDEFGHIJKLMNOPQRESTUVWXYZ
abcdefghijklmnopqrstuvwxyz
Numeric Characters
These are the numeric digits of the
decimal number system:
0123456789
Some Special characters
arithmetic operators
relational operators
assignment operator
grouping symbols
punctuation symbols
blank space
underscore
logic operators
+-*/%
< > == <= >=
=
() {} []
, . ' "" : ;
represented as for
blank
_
&& || !
Identifiers
Identifiers are the symbolic names that
represent various quantities.
 An identifier must consist of 1 to 31
characters with no embedded blank
spaces.
 The fist character must be either an
alphabetic character or an underscore.
 The other characters can be alphabetic or
numeric or the underscore.
Identifiers



No special characters are allowed in
the identifier names.
The uppercase letters are
distinguished from the lowercase
letters.
C has many reserved words,
which must NOT be used as identifiers
VALID
IDENTIFIERS
INVALID
IDENTIFIERS
COMMENT
5identity
first character can
not be a digit
velocity
axcl dig
blank space not
allowed
balance
con*st
illegal character
stress
maximum_value any,value
illegal character
total_count
while
reserved word
xal1245c20
struct
reserved word
Declaration of Variables
and Constants
all variables and named constants in C
must appear in declaration statements.
– allocate storage for the variable or constant
– associate the name of the variable or
constant with the allocate storage
In C, the storage associated with a variable
or constant is called a storage cell.
Built-in Data Types
int
float
double
char
Data Types
int
Integers are numbers having one or more digits
and possibly a sign, but no comma or decimal
point.
short int or short
long int or long
int count, value, item;
int count;
int valuel
int item;
const int G = 32; /* gravity in ft/sec^2 */
Table 2.1 constants defined
by limits.h for an IBM PC
Constant
Type
Storage
Value on IBM PC
CHAR_MAIN char
1 byte
-128
CHAR_MAX
char
1 byte
127
SHRT_MIN
short int
2 bytes
-32768
SHRT_MAX
short int
2 bytes
32767
INT_MIN
int
4 bytes
-2147483648
INT_MAX
int
4 bytes
214748367
LONG_MIN
long int
4 bytes
-2147483648
LONG_MAX
long int
4 bytes
214748367
Data Types
float
is a data type for real numbers (4
bytes).
Ex.
Float
5.0
-0.017
3.7E15
-6.2E-8
+0.23E+1
Data Types
float
float load;
float area;
float stress;
const float PI = 3.141593; /* seven
significant digits*/
float load, area, stress;
Data Types
double
When engineering and science applications
require higher precision, data type double
must be used (8 bytes).
Data type double is required by some library
functions.
Double atmomic_number, planets_distance;
Const double PI = 3.141592653742; /*thirteen
significant digits */
Data Types
char
char is allocated one byte of storage. A
single byte can hold one character.
char ch1, ch2, ch3;
const char comma = ‘,’;
Character code in ASCII
In computer memory a character is
stored internally in code form as a
decimal integer.
Ex. ‘A’ is ‘65’ in ASCII.
char var1, var2;
var1 = 'x';
var2 = '7';
Special Character Codes
ASCII & EBCDIC codes for special characters
Character
‘\a’
‘\b’
‘\f’
‘\n’
‘\t’
‘\0’
‘\\’
‘\’’
Interpretation
bell
back space
form feed
new line
tab
null character
\(backslash)
‘(single quote)
ASCII
7
8
12
10
9
0
92
39
Initialization of Variables
int count = 0, sum = 0;
float time = 0.0, velocity =2175.36;
Derived Data Types

Array (homogeneous data type)
– Vectors
int loc[] = {1, 2, 3};
– matrices
char digits[] =
{‘0’,‘1’ ,‘2’ ,‘3’ ,‘4’ ,‘5’ ,‘6’ ,
‘7’ ,‘8’ ,‘9’ ,‘\0’};


String
Structure (heterogeneous data type)
Arithmetic Operations
and Expressions








Arithmetic Operators & Operations
Arithmetic Expressions
Assignment Statement
Order of Evaluations
Use of Parentheses
Special Operators
Accuracy of Computation
C Libraries & Functions
Arithmetic Operators &
Operations
addition
+
subtraction
-
multiplication
*
division
/
remainder
%
Programming Warning: Division of an integer by an integer produces an
integer.
Exponentiation Operation
a
b pow((double) a, (double) b)
Expression Operation
pow((double) 5, (double) 2)
25.0
pow((double) -5, (double) 2)
25.0
5
pow((double) 2, (double)(.5))
1.414
0 .5
pow((double) 2, (double)(-0.5))
0.707
2
5
2
(5)
2
2
Value
Table 2.3 Data type of
mixed mode arithmetic
operand2
int
operand1 float
int
float
double
int
float
double
float
float
double
double
double
double double
Mode of Arithmetic
Results
Expression
16 + 2.0
15 – 2.5
15 / 3.5
15.0 /2
Result
18.0
2.5
4.285728
7.5
Programming Warning: When doing mixed-node arithmetic, be careful about
the integer division operation. Make sure to cast one of the operands in such
an operation to data type float or double or the decimal digits will be
lost.
Arithmetic Expressions
int
Float
a, b, c, d;
x, y, z, w;
C Expression
Result
5+6*8/2
integer constant
3.0+5*2.5+6.0/2
floating-point constant
a+b*c-d/c
integer value
x-y*z+w/2
floating-point value
a*x-b/y+w/c
floating-point value
Assignment Statement
area = (3.141593 * d * d) / 4.0;
Means calculate
result to area.
d 2
and assign the
4
float a = 10;
a = a +5.2;
a
Before
After
10.00 a
15.20
Each assignment statement
is carried out 3 steps
1.
The computer evaluates the expression on
the right side of the equal sign.
2.
If the result is not of the same data type
as the variable on the left side, it is
converted to the data type of that variable.
3.
The computer assigns the resulting value
to the variable to the variable on the left
side. In effect, the value is stored in the
memory cell allocate to that variable.
Order of Evaluations
highest
()
+ - unary
pow()
* and / and % left to right
lowest
+ and -
Use of Parentheses
Algebraic Expression
C Expression
(w+x)/(a+b)
x
( a  b)
w+x/(a+b)
( w  x)
b
a
(w+x)/a+b
w
w
x
b
a
w+x/a+b
Programming Hint: Use extra parentheses when there is any doubt as to how
the expression will be evaluated.
Special Operators


Assignment with Arithmetic Operators
Unary Increment ++ and Decrement
-- Operator
–
–
–
–


Preincrement
Postincrement
Predecrement
Postdecrement
Cast Operator
sizeof Operator
Assignment with
Arithmetic Operators
sum = 0; to initialize the sum
sum = sum+x; within a loop with new
values of x
Summation Operation
sum = 0;
for each x
sum += x;
end for
/*calculates Σx*/
Preincrement
Before
After
x=10;
x uuuuuu
x 10
y=++x;
x 10
x 11
y uuuuuu
y 11
Postincrement
Before
After
x=10;
x uuuuuu
x 10
y=x++;
y uuuuuu
y 10
x 10
x 11
Predecrement
Before
After
x=10;
x uuuuuu
x 10
y=--x;
x 10
x 9
y uuuuuu
y 9
Postdecrement
Before
After
x=10;
x uuuuuu
x 10
y=x--;
y uuuuuu
y 10
x uuuuuu
x 9
Cast Operator
int var1;
float var2;
(float) var1; Changes the int data type vale
fetched from the storage of var1 to
the float data type without changing
the data type of var1 or the value
stored in var1
(int) var2; Changes the float data type value
fetched from the storage of var2 to
the int data type without changing
the data type of var2 or the value
stored in var2
sizeof Operator

To determine the default number of
bytes allocated for an int variable on a
computer.
int var, varsize;
varsize = sizeof(int);
or
varsize = siezeof(var);
Accuracy of Computation

Errors
– No significant digits in the computer form
of input data
– Inexactness of computer representation
of real numbers
– Adjustment of computational results to fit
computer storage
example
(1.0/3.0) * 3.0
= 0.3333333*3.0
= 0.9999999
≠ 1.0
(1.0/10.0)*10.0, which is not 1.0
The inaccuracy that arises
with integer calculation.
(1/2)*2 is 0, and
1 / 2 * 2 is 0,
But
2 * 1 / 2 is 1.
C Libraries & Functions







input/output functions
Mathematical functions
String manipulation functions
Memory allocation functions
Standard library functions
Other miscellaneous functions
The programmer must include the appropriate
header file to use these functions.
Ex, #include <stdio.h>
Overview of
Implementation





Since C is a procedural language, the basic
units of a program are the functions.
The execution of a C program always starts
and ends with the main function.
The main function may call other functions
and any other function may call another
function or functions.
No function can call the main function.
Every function to be called must be declared.
This is called the function prototype.
Overview of
Implementation


Every function must be defined as well
as prototyped.
The data type of the arguments of a
function call must match the data
types of the function prototype
parameters, as must the data types of
the parameters in the function header.
Formatting of Statements

Comment Statement
– The non-executable statements are the
comment statements which are strictly
used for documentation of the main
function and other functions, and only
sparingly inside the program code.
– Comment statements start with /* and
end with */

Program Statement
Comment Statement
Single line comment statement: /* This is a C program */
Multiple line comment statement: /* this is a wonderful
statement to document my
program so that it is easy to
read what the program does */
Program Statements
or
a = b + c – d * e / f;
a=b+c
- d * e / f;
Programming Warning: Do not spilt any variable name
when a statement is spilt into two lines.
Formatting of a Program


A well designed program has separate
sections for documentation,
declarations, definitions, and program
statements.
There must be external names for the
program file and the data file that are
known to the operating system.
Every C program has the
following general form:
documentation describing the entire program
preprocessor directives
define directives /*optional, to be explained later*/
global variables /*not recommended, to be explained
later*/
function prototypes
int main( )
{
declaration of named constants and variables
. . .
executable statements
. . .
return 0;
}
function implementations
The structure of a
subordinate function is as
follows:
documentation describing the function
External variables /*not recommend, to
be explained later*/
return type function name (parameters
list)
{
declaration of variables
. . . . . . .
executable statements
. . . . . . .
return;
}
Sample C Program
2.5.1 sample code
/*******************************************************/
/*
*/
/* THIS IS THE FIRST COMPLETE C PROGRAM
*/
/*
*/
/*******************************************************/
1. #include <stdio.h>
2. int main()
3. {
4.
int x, y, sum;
5.
x = 5;
6.
y = 6;
7.
sum = x + y;
8.
printf("x = %d y = %d sum = %d\n", x, y, sum);
9.
return 0;
10.}
Download