0% found this document useful (0 votes)
3 views58 pages

CENG460 Lecture 3 C Tutorial

The document provides an overview of the C programming language, detailing its history, advantages, and disadvantages. It covers fundamental elements such as functions, variables, identifiers, comments, and operators, as well as type conversions and arithmetic functions. The document serves as a comprehensive guide for understanding the structure and syntax of C programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views58 pages

CENG460 Lecture 3 C Tutorial

The document provides an overview of the C programming language, detailing its history, advantages, and disadvantages. It covers fundamental elements such as functions, variables, identifiers, comments, and operators, as well as type conversions and arithmetic functions. The document serves as a comprehensive guide for understanding the structure and syntax of C programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

FUNDAMENTAL

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:

efficient C programming requires a lot of experience


without comments or explanations, programs can become
incomprehensible and therefore unusable

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

C programs are essentially composed of functions and


variables. For practice, it is therefore essential to become
familiar with the basic characteristics of these elements.
8
FUNCTIONS
In C, the main
program and
subroutines are main function
defined as functions.
The main function is
the main function of
programs in C: It is
mandatory in all
programs.
Running a program
automatically causes
the main function to printf function
be called.

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.

The set of usable symbols is: {0,1,2, ..., 9, A, B, ..., Z, _, a, b, ..., z}


The first character must be a letter (or the symbol '_')
C distinguishes upper and lower case letters, as follows:
Variable_name is different from variable_name
The length of the identifiers is not limited, but C distinguishes 'only'
the first 31 characters.
12
IDENTIFIERS
EXAMPLES
Correct identifiers Incorrect identifiers
name1 1name
name_2 name.2
_name_3 -name-3
Variable_name Variable name
Deuxieme_choix Deuxième_choix

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.

The first line of the


program:
#include <stdio.h>
instructs the compiler
to include the header
file 'STDIO.H' in the printf function
program text.
17
BASIC TYPES,
OPERATORS AND
EXPRESSIONS 18
INTEGER TYPES
Before we can use a variable, we need to look at two
characteristics of its numeric type:
(1) the range of allowable values
(2) the number of bytes that is reserved for a variable

19
INTEGER TYPES
The following table summarizes the characteristics of the integer
numeric types of C:

Definition Description Min value Max value Nb of


bytes
char character -128 127 1
short short integer -32768 32767 2
Int / long integer -2147483648 2147483647 4
long long long integer - 922337203685477580 8
92233720368547758 7
08

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:

<+|-> <mantissa> * 10<exponent>


<+|-> is the positive or negative sign of the number
<mantissa> is a positive decimal with a single digit before the
comma
<exponent>
is a relative integer
22
RATIONAL TYPES
In C, we have the choice between three types of rationals: float,
double and long
Definition Numberdouble.
of In value
Min the tableMax
below,
valueyouNb
willoffind their
bytes
characteristics:
significant
digits of
the
mantissa
float 6 3.4 * 10-38 3.4 * 1038 4
double 15 1.7 * 10-308 1.7 * 10308 8
long double 19 3.4 * 10-4932 1.1 * 104932 10

min and max values represent the minimum and


maximum positive values. Negative values may
vary in the same range.
23
THE DECLARATION OF
SIMPLE VARIABLES
Variable declaration in C
<Type> <NameVar1>, <NameVar2>, ..., <NameVarN>;

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.

Logical operations in C always return results 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.

Constant characters can appear in arithmetic or logical operations,


but in general they are used to be compared to variables.

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;

Using the const attribute, we can indicate that the value of a


variable does not change during a program:
const int MAX = 767;
const double e = 2.71828182845905;
const char NEWLINE = '\n';

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.

These implicit manipulations generally convert 'smaller' types to


'wider' types; in this way we do not lose precision.

During an assignment, the data to the right of the equality sign is


converted to the type to the left of the equality sign. In this case,
there may be a loss of precision if the type of the destination is
lower than that of the source.

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.

In this chapter we will discuss the most important ones:


1.printf() for formatted data writing
2.scanf() for formatted reading of data
3.putchar() for writing a character
4.getchar() for reading a character

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

printf ("<format>", <Expr1>, <Expr2>, ...)

"< format >": format of representation

<Expr1> ...: variables and expressions whose values are to be


represented

44
FORMATTED DATA WRITING
printf ("<format>", <Expr1>, <Expr2>, ...)

The "<format>" part is actually a string that can contain:


* text
* escape sequences
* format specifiers
* Format specifiers indicate how the values of expressions <Expr1..N> are printed.
* The "<format>" part contains exactly one format specifier for each <Expr1..N>
expression.
* Format specifiers always start with the % symbol and end with one or two
characters that indicate the print format.
* Format specifiers involve converting a number to a string. They are still called
conversion symbols.

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

%b integer expressed in hexadecimal int*


%c character char*
%s string of characters char*
rational in decimal or exponential
%f ou %e float*
notation (scientific)

The symbol * indicates that the argument is not a


variable, but the address of a variable of this type
51
REMARKS
4. Indication of the maximum width
For all specifiers, we can specify the maximum width of the field to be
evaluated for a given datum. Numbers that pass beyond the
defined field are assigned to the next variable that will be
read!
Example
Here are the instructions:
int A, B;
scanf ("%4d %2d", &A, &B);
If we enter the number 1234567, we will get the following assignments:
A = 1234
B = 56
the number 7 will be kept for the next reading instruction.
52
REMARKS
5. Signs of spacing
When entering data, a sequence of spacing characters (spaces, tabs,
line feeds) is evaluated as a single space. In the format string, the
symbols \t, \n, \r have the same effect as a single space.
Example
For the continuation of instructions
int DAY, MONTH, YEAR;
scanf ("%i %i %i", &DAY, &MONTH, &YEAR);
the following entries are correct and equivalent:
12 4 1980
or
12 004 1980
or
12
4
1980 53
WRITING A CHARACTER
The command, putchar('a'); transfers the character a to the
standard stdout output file. The arguments of the putchar function
are either characters (that is, integers between 0 and 255).

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

and many more to discover later on


58

You might also like