CENG460 Lecture 3 C Tutorial
CENG460 Lecture 3 C Tutorial
ELEMENTS OF A C
PROGRAM 1
2
HISTORY
The C language originated in 1972 at Bell Laboratories: To develop a portable
version of the UNIX operating system, Dennis M. Ritchie designed this structured
programming language, but very close to the machine.
In 1978, the Brian W. Kernighan / Dennis M. Ritchie duo published the classic
definition of the C language (known as the K & R-C standard) in a book called 'The C
Programming Language'.
The success of the years that followed and the development of C compilers by other
houses made it necessary to define an updated and more precise standard. In 1983,
the American National Standards Institute (ANSI) commissioned a commission to
develop an explicit and independent machine definition for the C language, which
should still retain the spirit of language. The result was the ANSI-C standard. The
second edition of 'The C Programming Language', published in 1988, fully complies
with the ANSI-C standard and later became the 'bible' of C programmers.
3
ADVANTAGES
Universal: It is not oriented towards a special application domain, for
example FORTRAN (scientific and technical applications) or COBOL
(commercial applications or processing large amounts of data).
Compact: It is based on a core of functions and limited operators, which
allows the formulation of simple but effective expressions.
Modern: It is a structured, declarative and recursive language; it offers
control and reporting structures comparable to those of other major
languages of that time (FORTRAN, ALGOL68, PASCAL).
Near the machine: Since C was first developed for programming the
UNIX operating system, it offers operators that are very close to those of
the machine language and functions that allow simple and direct access
to the internal functions of the computer (p. eg memory management).
4
ADVANTAGES
Fast: as C allows to use expressions and operators that are very
close to the machine language, it is possible to develop efficient
and fast programs.
Independent of the machine: although C is a language close to the
machine, it can be used on any system in possession of a C
compiler.
Portable: By respecting the ANSI-C standard, it is possible to use
the same program on any other system (other hardware, other
operating system), simply by recompiling it.
Expandable: C does not consist only of standard functions, one can
write his own functions.
5
DISADVANTAGES
Efficiency and comprehensibility:
6
Main program
Header files
math.h #include…
#include…
#include<math.h>
stdio.h
#include<stdio.h>
main() Compiler
{
…
}
Compile code
of the main function
math.lib
Linker
stdio.lib .exe
Executable program7
FUNDAMENTAL ELEMENTS
OF A C PROGRAM
9
INSTRUCTIONS
In C, any simple instruction is terminated by a semicolon; (even if it
is in the last position in a block of instructions). instruction
10
VARIABLES
Variables contain the values that are used during program
execution.
The variable names are any identifiers.
The different types of simple variables and the eligible operators
are discussed later.
11
IDENTIFIERS
The names of functions and variables in C are composed of a series of
letters and numbers.
The first character must be a letter.
The symbol '_' is also considered a letter.
13
COMMENTS
A comment on one or multiple lines always starts with the two
Comment
symbols /* and ends with the symbols */. It is forbidden to use
nested comments.
14
COMMENTS
A comment on one line always starts with the two symbols //.
Comment
15
EXAMPLES
16
PRINTF AND THE <STDIO.H>
LIBRARY
The printf function is
part of the standard
<stdio.h> function main function
library that handles
data inputs and
outputs.
19
INTEGER TYPES
The following table summarizes the characteristics of the integer
numeric types of C:
20
INTEGER TYPES
The signed / unsigned modifiers:
If we add the unsigned prefix to the definition of a type of integer
variables, the variable domains are modified as follows:
Definition Description Min value Max value Nb of
bytes
unsigned char character 0 255 1
unsigned short short integer 0 65535 2
unsigned int integer 0 4294967295 4
unsigned long long integer 0 4294967295 4
21
RATIONAL TYPES
In computing, rationals are often called 'floats'. This term comes
from 'floating point' and finds its root in the traditional notation of
rationals:
Examples
int counter, X, Y;
float height, width;
double atomic_mass;
char key;
24
REMARKS
Here are some general rules concerning how to choose a variable type:
integer: We have the choice between all integer types (including char) in
their signed or unsigned forms. If the numbers become too big for unsigned
long, you must use a rational type (eg: double)
Real: We can choose between the three rational types by observing not only
the maximum magnitude of the exponent, but even more the number of
significant digits of the mantissa.
character: Any variable of type char can contain one (only) character. In C,
one must always be aware that this 'character' is nothing other than a
number corresponding to a code (here: ASCII code). This number can be
integrated in any kind of algebraic or logical operations ...
string: In C there is no special type for strings. The means of handling
character strings will be described later.
25
REMARKS
Boolean: In C there is no special type for Boolean variables. All
types of numeric variables can be used to express logical
operations:
false logical value zero as numerical value
true logical value any value other than zero
Advice
If the use of a Boolean variable is essential, the
most natural will be to use a variable of type int.
0 for false
1 for true
26
CHARACTER CONSTANTS
Constants that designate a (single) character are always indicated
between single quotes: for example, 'x'. The value of a constant
character is the internal code of this character. This code (here: the
ASCII code) is machine dependent.
27
INITIALIZATION OF THE
VARIABLES
In C, it is possible to initialize the variables when they are declared:
int MAX = 1023;
char TAB = '\t';
float X = 1.05e-4;
28
STANDARD OPERATORS
C assignment
<VariableName> = <Expression>;
Examples of assignments with constant values
LONG = 141;
PI = 3.1415926;
NATION = 'L';
Examples of assignments with variable values
VALUE = X1A;
LETTER = MAIL;
pow(R,2) calculates R2
Examples of assignments with expression values
AREA= PI*pow(R,2);
AVERAGE= (A+B)/2; the test of equality in C is
UN=pow(sin(X),2)+pow(cos(X),2); formulated with two signs of
RES = 45+5*X; equality ==, the assignment with
BIGGER= (X>Y); only one =.
CORRECT = ('a' == 'a'); 29
KNOWN OPERATORS
Arithmetic operators
+ addition
- substraction
* multiplication
/ division (whole and rational!)
% modulo (rest of a whole div)
30
KNOWN OPERATORS
Logical operators
&& and logic (and)
|| or logical (or)
! logical negation (not)
31
KNOWN OPERATORS
Comparison Operators
== equal to
!= different from
<, <=,>,> = smaller than, ...
32
KNOWN OPERATORS
Logical operations
The results of comparison operations and logical operators are of type
int:
- the value 1 corresponds to the true Boolean value
- the value 0 corresponds to the false Boolean value
Logical operators consider any value other than zero as true and
zero as false:
32 && 2.3 gives 1
!65.34 gives 0
0||!(32 > 12) gives 0
33
THE PARTICULAR
OPERATORS OF C
The assignment operators
Increment and Decrement Operators
34
THE PARTICULAR OPERATORS OF C
THE ASSIGNMENT OPERATORS
In practice, we often find assignments like: i = i + 2
In C, we will use rather the more compact formulation: i += 2
The += operator is an assignment operator.
For most expressions of the form: expr1 = (expr1) op (expr2)
there is an equivalent formulation that uses an assignment operator:
expr1 op= expr2
+= add to
-= decrease
*= multiply by
/= divide by
%= modulo
35
THE PARTICULAR OPERATORS OF C
INCREMENT AND DECREMENT
OPERATORS
The most frequent assignments are of the type: I = I + 1 and I = I -
1
In C, we have two unusual operators for these assignments:
I++ or ++I
I-- or --I
The operators ++ and - are used in the following cases:
increment / decrement a variable (eg in a loop). In this case there is no difference
between the prefix notation (++I --I) and the postfix notation (I++ I--).
increment / decrement a variable and at the same time assign its value to another
variable. In this case, we must choose between prefix and postfix notation:
X = I++ first passes the value from I to X and increments I after
X = I-- first passes the value from I to X and decrements I after
X = ++I first increments and passes the incremented value of I to X
X = --I decrement first and pass the decremented value of I to X
36
STANDARD ARITHMETIC FUNCTIONS
The following functions are predefined in the standard <math>
library. To be able to use them, the program must contain the line:
#include <math.h>
Arguments and results of arithmetic functions are of the double type.
37
STANDARD ARITHMETIC
FUNCTIONS
C command Explanation
exp(X) Exponential function
log(X) Natural logarithmic
log10(X) Logarithm based 10
pow(X,Y) X exponent Y
sqrt(X) square root of X
fabs(X) absolute value of X
floor(X) round in less
ceil(X) round up
fmod(X,Y) rational remainder of X / Y (same sign as X)
sin(X) cos(X) tan(X) sine, cosine, tangent of X
asin(X) acos(X) atan(X) arcsin(X), arccos(X), arctan(X)
hyperbolic sine, hyperbolic cosine, hyperbolic tangent
sinh(X) cosh(X) tanh(X)
of X
38
TYPE CONVERSIONS
The great flexibility of the C language makes it possible to mix data
of different types in an expression.
Before you can calculate, the data must be converted into the
same type.
Most of these conversions happen automatically, without the
intervention of the programmer, who must still predict their effect.
Sometimes it is necessary to convert a datum into a different type
from the one chosen by the automatic conversion; in this case, we
must force the conversion using a special operator ("cast").
39
AUTOMATIC TYPE
CONVERSIONS
CALCULATIONS AND
ASSIGNMENTS
If an operator has operands of different types, the values of the
operands are automatically converted into a common type.
40
FORCED TYPE CONVERSIONS
(CASTING)
It is possible to explicitly convert a value to any type by forcing the transformation
using the syntax:
(<Type>) <Expression>
Example: We divide two variables of the integer type. To be more precise, we want
to have a rational type result. To do this, we convert one of the two operands to
float. Automatically C will convert the other operand into a float and perform a
rational division:
char A = 3;
int B = 4;
float C;
C = (float) A / B;
The value of A is explicitly converted to a float. The value of B is automatically
converted to float (rule 2). The result of the division (rational type, value 0.75) is
assigned to C.
Result: C = 0.75
The contents of A and B remain unchanged; only the values used in the
calculations are converted! 41
READ AND WRITE
DATA
42
INTRODUCTION
The standard <stdio.h> library contains a set of functions that
ensure the communication of the machine with the outside world.
43
FORMATTED DATA WRITING
The printf function is used to transfer text, variable values, or
expression results to the stdout standard output file (by default the
screen).
44
FORMATTED DATA WRITING
printf ("<format>", <Expr1>, <Expr2>, ...)
45
EXAMPLE 1
The following instructions:
int A = 1234;
int B = 567;
printf("%i times %i is %li\n", A, B, (long)A*B);
will display on the screen:
1234 times 567 is 699678 • The first specifier (%i) indicates that the
value of A will be printed as a relative
Printf's arguments are: integer ==> 1234
the format part "%i times %i is %li" • The 2nd specifier (%i) indicates that the
the variable A value of B will be printed as a relative
integer ==> 567
the variable B • The third specifier (%li) indicates that the
expression (long) A * B value of (long) A * B will be printed as long
relative integer ==> 699678
46
EXAMPLE 2
The following instructions:
char B = 'A';
printf("The character %c has the code %i!\ n", B,
B);
will display on the screen:
The character A has the code 65!
The value of B is therefore displayed in two different formats:
%c as character: A
%i as relative integer: 65
47
FORMAT SPECIFIERS FOR
PRINTF
SYMBOL TYPE PRINTING AS
%d or %i int relative integer
%u int natural integer (unsigned)
%o int integer expressed in octal
%x int integer expressed in hexadecimal
%c int character
%f double rational in decimal notation
%e double rational in scientific notation
%s char* string of characters
48
FORMATTED READING OF
DATA
The function scanf is the symmetrical function to printf; it offers us almost the
same conversions as printf, but in reverse.
scanf ("<format>", <AdrVar1>, <AdrVar2>, ...)
"<format>": format for reading data
<AdrVar1>, ...: addresses of the variables to which the data will be assigned
* The scanf function receives its data from the stdin standard input file (by
default the keyboard).
* The format string determines how the received data should be interpreted.
* The correctly received data are memorized successively at the addresses
indicated by <AdrVar1>, ....
* The address of a variable is indicated by the name of the variable preceded by
the & sign.
49
EXAMPLE
The following instructions:
int DAY, MONTH, YEAR;
scanf ("%i %i %i", &DAY, &MONTH, &YEAR);
reads three relative integers, separated by spaces, tabs, or lines.
Values are assigned to the three variables DAY, MONTH, and YEAR,
respectively.
* scanf returns as result the number of correctly received data
(type int).
50
FORMAT SPECIFIERS FOR
SCANF
SYMBOL Reading of TYPE
%d ou %i relative integer int*
%u natural integer (unsigned) int*
integer expressed in octal int*
%o
The putchar arguments are by definition of the type int and all the
values processed by putchar (even those of the char type) are first
converted to int.
54
EXAMPLES
55
READING A CHARACTER
A function more often used than putchar is the getchar function,
which reads the next character of the stdin standard input file.
The values returned by getchar are either characters (0 - 255). The
result type of getchar is int. In general, getchar is used in an
assignment:
int C;
C = getchar ();
getchar reads the data from the stdin buffer and provides the data
only after confirmation with 'Enter'.
The <conio.h> library contains a function of the getch name that
immediately provides the next character entered on the keyboard.
56
IMPORTANT
COMMANDS TO USE
IN LINUX
ENVIRONMENT 57
IMPORTANT CLI COMMANDS
pwd
man
cd
ls
mkdir
rmdir
rm /rm –r
gedit / touch / nano
gcc / gcc –o
./executable