Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views187 pages

C Programing

The document provides an introduction to computer basics, including examples of applications, data coding in binary, and how a computer operates with components like the processor and memory. It also covers the fundamentals of programming in C language, detailing how to read input, perform calculations, and display output. Additionally, it includes sample programs and exercises to practice C programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views187 pages

C Programing

The document provides an introduction to computer basics, including examples of applications, data coding in binary, and how a computer operates with components like the processor and memory. It also covers the fundamentals of programming in C language, detailing how to read input, perform calculations, and display output. Additionally, it includes sample programs and exercises to practice C programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 187

Part 1

C language basics

www.biblio-scientifique.net
www.biblio-scientifique.net
WHAT IS A
COMPUTER ?
1
1.1 E XAMPLES OF IT
APPLICATIONS
Here are a few examples of computer use:

- Office automation The computer stores data entered by a secretary or other


person (texts, figures, customer files, etc.) or data from archives, and formats them
to enable them to be understood, displayed or communicated.

- Video games The computer combines data entered by the game designer (data on
the universe) with events created by the game user (mouse clicks, etc.) to generate
images, sound, etc.

- Weather forecast Using data from all the weather stations in a geographical area,
the computer calculates a future situation and generates maps of atmospheric
temperatures and pressures.

- Multimedia applications on the Internet The computer downloads data stored


on a remote server and displays it on the user's computer. Eventually, the user's
actions can influence the data displayed (these are known as interactive
applications).

In all these examples, the computer processes data, and produces a result, either
communicated to the user (sound, images, text), or displayed on a screen, or stored
on a disk, or whatever.
Dunod. Unauthorized photocopying is an offence.

1.2 D ATA CODING


Computer data is always ultimately coded in binary, i.e. represented by sequences of
0's and 1's. Binary data is easier to store on physical media (tapes, disks, etc.).
For example, if we want to store an integer on a computer's hard disk, we
generally code this number in base 2, rather than base 10 as we're naturally used to.

www.biblio-scientifique.net
Chapter 1 - What is a computer?

Thus the number 12 (in base 10) will be encoded in base 2 by the binary sequence
00001100, which means that :
12 = 0 + 0 + 0 + 0 + 8 + 4 + 0 + 0
= 0 × 27 + 0 × 26 + 0 × 25 + 0 × 24 + 1 × 23 + 1 × 22 + 0 × 21 + 0 × 20
Data equal to either 0 or 1 is called a bit. A sequence of 8 consecutive bits is called
a byte. The amount of memory stored in computers is measured in :
• Bytes: 1 byte = 8 bits ;
• Kilobytes (abbreviated as Kb): one Kb is worth 1024 bytes.
• Megabytes (abbreviated Mo or Mb): one MB is worth 1,048,576 bytes
• Giga-bytes (abbreviated Go or Gb): one GB is worth 1,073,741,824 bytes
The appearance of the numbers 1024, 1,048,576 and 1,073,741,824 may seem
surprising, but these are powers of 2. It's generally accepted that a KB is about a
thousand bytes, a MB about a million, and a GB about a billion.

1.3 H OW A COMPUTER WORKS


1.3.1 Operating system
A computer program must receive data to process it, and produce other data. For the
program to function, it needs hardware (electronic components), and an intermediate
software layer with the hardware, called the operating system. The system ensures
communication between the computer program and the hardware, and enables the
program to act on the hardware.

1.3.2 Processor
The processor performs operations (e.g. arithmetic operations such as addition or
multiplication). These operations are hard-wired into the processor, i.e. they are
performed by electronic circuits to ensure efficiency. Over time, more and more
complex operations are wired into the processor, increasing efficiency. The speed of
a processor, roughly the number of operations per second, known as clock speed, is
measured in hertz (Hz), kilohertz (1kHz = 1000Hz) , megahertz (1MHz = 106 Hz, and
gigahertz (1GHz = 109 Hz). On recent architectures, the chip contains several cores,
each core being the equivalent of a processor, and the cores communicating with
each other very rapidly via data buses. For C programmers, the configuration and
structure of the chip is transparent, i.e. you don't have to worry about it (except for
optimization in very advanced programming).

www.biblio-scientifique.net
1.3. Computer operation

1.3.3 Main memory


As the program runs, it uses data - either the data supplied as input, or intermediate
data that the program uses to operate. This data is stored in variables. Physically,
variables are binary data stored in main memory (also known as RAM). The main
memory communicates rapidly with the processor. When the processor performs a
calculation, the programmer can indicate that the result of this cal- cul is to be stored
in a variable (in RAM). The processor can later access the contents of this variable to
perform further calculations or produce an output result. The amount of RAM
memory is measured in bytes (or megabytes or gigabytes). Data in main memory is
retained only while the program is running, and disappears when the program ends
(e.g. when the computer is switched off).

1.3.4 Peripherals
The program receives data from peripheral devices as input, and communicates its
results as output to peripheral devices. A (non-exhaustive) list of common peripherals
is :
• the keyboard, which allows the user to enter text;
- the mouse, which allows the user to select, activate or create graphical objects by
hand;
• the screen that allows programs to display data graphically;
• the printer for outputting data on paper;
- hard disks and USB sticks for permanent data storage. Data saved on such a disk is
preserved even after the program has ended or the computer has been switched off,
unlike data stored in main memory, which disappears when the program ends.
Input devices (such as keyboard and mouse) transmit data in one direction only,
from the device to main memory. Output devices (such as the monitor or printer)
Dunod. Unauthorized photocopying is an offence.

receive data in one direction only, from main memory (or video memory) to the
peripheral. Input-output peripherals (such as the hard disk, USB port or network
card) enable two-way communication between main memory and the peripheral.

www.biblio-scientifique.net
Chapter 1 - What is a computer?

Central unit

The processor La m'emoire centrale


access
performs +, -, ∗,/ operations stores data used by programs
(variables)
evaluates logical tests <, >, ==
assignmen provides quick access to
t
repeats them data
s'equences d'instructions

Data flow

p'eriph'eriques p'eriph'eriques p'eriph'eriques


d'entr'ee d'entr'ee-sortie output

keybo hard disk screen


ard
mous memory printer
e stick

DVD player r'eseau card sound


card
etc. etc. etc.

Figure 1.1- Computer architecture diagram.

www.biblio-scientifique.net
PROGRAMS
FIRST
2
2.1 W HAT IS A PROGRAM ?
A computer program generally does three things:

- It reads input data. The program needs to know what it's working with. For
example, to use a calculator, you need to give it numbers and tell it what
operations to perform. A keyboard is often used for this, but the program can also
draw data from a hard disk or another computer via a network or other means.

- It performs calculations. Based on the input data, the program automatically


applies methods to process the data and produce a result. The methods that
computers are capable of performing are called algo- rithms. For example, a
calculator will apply an addition or multiplication algorithm.

- It writes data to the output. When the program has obtained a result, it must
write this result somewhere so that it can be used. For example, a calculator will
display a result on the screen or store the result in memory.

A programmer's job is to create computer programs. To do this, the programmer


has to explain to the computer, in a certain language called a programming language,
what the data is and what methods need to be applied to process it. In this chapter,
we'll take a look at the first examples of C-language programming:
1. read data from the keyboard using the scanf function;
2. perform the simplest calculations on numbers and store the result in a variable ;
Dunod. Unauthorized photocopying is an offence.

3. display text or numbers on the screen using the printf function.


In the process, we'll see the structure of a very simple C program and a few
notions about the language's syntax. The concepts covered in these examples will be
developed in subsequent chapters. Once the programmer has written his or her
program, which is text in C language, he or she must compile the program to create
an executable file so that a user of the program can use it. The compilation process is
described in the appendix.

www.biblio-scientifique.net
Chapter 2 - First programs

2.2 DISPLAY A WORD


Here's a C program that writes a welcome message: the word "Hello".

#include <stdio.h> /* to be able to read and write */

int main(void) /* main program */


{
printf("Hello!"); /* writing on screen */
return 0;
}

Sentences between / and / are ∗ comments.


∗ They have no influence on the flow
of the program. (Good) programmers use comments to clarify their code, which is
crucial when working in a team. The first line is an instruction #include < stdio.h >
which allows functions from the stdio.h library to be used in the program. In
particular, this library contains the printf screen display and keyboard read functions
scanf.
Next comes the line declaring the start of the main function, the prin- cipal
program. The main program is the sequence of instructions that will be executed. In
this case, there's just one instruction: a printf screen display. The
\n allows you to jump to the next line after the word "Bonjour" is displayed.

2.3 READ A NUMBER


Here's a program that lets the user type a number on the keyboard. This number is
read by the program and stored in a variable x, which is a real number (float data
type). The variable x is then re-displayed by printf.

#include <stdio.h> /* to be able to read and write */

int main(void) /* main program */


{
float x; /* declaration o f a variable x (real number) */

printf("Please enter a real number using the keyboard");


scanf("%f", &x); /* read the value of x from the keyboard */
/* display x : */
printf("You've typed %f, congratulations!", x);
return 0;
}

www.biblio-scientifique.net
2.4. Perform a calculation and memorize the result

The display and read format %f corresponds to real numbers (float type). In
printf, %f is replaced by the value of x when displayed. For example, if the user
enters the value 15.6 on the keyboard, the program displays the following
sentence:
You typed 15.600000, congratulations Ị

Don't forget the & in scanf! This would cause a memory error (or segmentation error)
during program execution, and the program would be abruptly interrupted.

2.4 P ERFORM A CALCULATION AND


MEMORIZE THE RESULT
The following program stores the double of x in a variable y, by means of an
assignment. An assignment (symbol =) is used to store the result of a calculation in a
variable.

#include <stdio.h> /* to be able to read and write */

int main(void) /* main program */


{
float x, y; /* declaration of two variables x and y */

printf("Please enter a real number on the keyboard");


scanf("%f", &x); /* read the value of x from the keyboard */ y
= 2*x; /* put the double of the content of x into y */ printf("The
double of the number typed is %f", y);
return 0;
}

The = symbol in assignment has a completely different meaning to mathematical


equality. Assignment means that a variable takes on the value of the result of a
calculation. It corresponds to an operation for copying data.
Dunod. Unauthorized photocopying is an offence.

Supplements

,
Syntax must be strictly adhered to. Forgetting a semicolon, for example, or
replacing a quotation mark " with a quote ', usually results in a compile-time
error. In some very specific cases, there are several syntax options. For
example, the word void in the main declaration is optional.
,
Sometimes, especially in the design phase, a program can be syntactically-...
correct, but the program does not behave as expected

www.biblio-scientifique.net
Chapter 2 - First programs

by the programmer, due to a design error or carelessness. The program is


said to have a bug.
,
The return 0 at the end of main indicates only that the value 0 is returned.
to the system (indicating that the program is terminated without error). We
won't be using the ability to return values to the system. These functions are
generally studied with operating systems.

Exercises

2.1 (∗) To convert degrees Fahrenheit to degrees Celsius, we have the following
formula:
C ≈ 0.55556 × (F - 32)
where F is a temperature in degrees Fahrenheit and C the corresponding temperature
in degrees Celsius.

a) Write a C program that converts a temperature entered from the keyboard into
degrees Fahrenheit and displays an approximate value of the same temperature in de-
grees Celsius. Temperatures will be expressed as real numbers.

b) Same question as in a) for the reverse conversion: from degrees Celsius to degrees
Fahrenheit.

2.2 (∗) D u r i n g a promotional campaign, a hardware components store


applies a 10% discount to all components. Write a program that
reads the price of a component from the keyboard and displays the price calculated
taking the discount into account.

2.3 (∗∗) Let the mathematical function ƒ be defined by ƒ (x) = (2x + 3)(3x2 + 2)
a) Write a C program that calculates the ƒ-image of a number entered on the keyboard.

b) An approximation of the derivative ƒJ of the function ƒ is given at each point x, for


h small enough (close to 0), by :
ƒ (x + h) - ƒ (x)
ƒ J(x) ≈ .
h
Write a C program that calculates and displays an approximation of the derivative of ƒ
at a point x entered from the keyboard. The h parameter can be entered from the keyboard.

10

www.biblio-scientifique.net
Answers

2.4 (c-∗) A lead ball is dropped from the top of a building and falls in free fall. After
a time t (expressed in seconds), the ball has descended from a height of -
teur (in meters) :
1
h = g.t 2
2
with
g = 9.81 (expressed in (m.s–2 ))

a) Write a program that calculates the height descended after a time t entered on the
keyboard.

b) Write a program to calculate the total duration of the fall, given the total height h
of the building entered on the keyboard. (You can use the sqrt function in the math.h
library, which calculates the square root of a number).

Answers

2.1
a)
int main(void)
{
float celsius, fahrenheit;
printf("Enter temperature in degrees Fahrenheit: ");
scanf("%f", &fahrenheit);
celsius = 0.55556 * (fahrenheit - 32.0);
printf("Temperature %f degree Celsius.n", celsius);
return 0;
}
Dunod. Unauthorized photocopying is an offence.

b)
int main(void)
{
float celsius, fahrenheit;
printf("Enter temperature in degrees Celsius: ");
scanf("%f", &celsius);
fahrenheit = (celsius / 0.55556) + 32.0;
printf("Temperature %f degree Fahrenheit.\n", fahrenheit);
return 0;
}

11

www.biblio-scientifique.net
Chapter 2 - First programs

2.2
int main(void)
{
float price, discountprice;
printf("Enter a price: ");
scanf("%f", &price);
discountprice = 0.9 * price;
printf("The price with 10% discount is %f.\n", discountPrice);
return 0;
}

2.3
a)
int main(void)
{
float x, fx;
printf("Enter a number: ");
scanf("%f", &x);
fx = (2.0 * x + 3.0) / (3.0 * x * x + 2.0);
printf("f(%f) = %f\n", x, fx);
return 0;
}
b)
int main(void)
{
float x, h, fx, fx_plus_h, fPrime_x;
printf("Enter a number: ");
scanf("%f", &x);
printf("Enter deviation h: ");
scanf("%f", &h);
fx = (2.0 * x + 3.0) / (3.0 * x * x + 2.0);
fx_plus_h = (2.0 * (x + h) + 3.0) / (3.0 * (x + h) * (x + h) + 2.0);
fPrime_x = (fx_plus_h - fx) / h;
printf("f'(%f) = %f\n", x, fPrime_x);
return 0;
}

2.4
a)
int main(void)
{
float h, t;

12

www.biblio-scientifique.net
Answers

printf("Enter duration: ");


scanf("%f", &t);
h = (9.81 * t * t) / 2.0;
printf("A t = %f, h = %f\n", t, h);
return 0;
}
b) Don't forget to add -lm at compile time
int main(void)
{
float h, t;
printf("Enter total height (in meters): ");
scanf("%f", &h);
t = sqrt(2.0 * h / 9.81);
printf("The ball hits the ground after %f seconds", t); return 0;
}
Dunod. Unauthorized photocopying is an offence.

13

www.biblio-scientifique.net
www.biblio-scientifique.net
D ATA TYPES
3
3.1 V ARIABLES AND OPERATIONS
In a program, variables are used to give names to data. Each variable must have a
type (integer, real number, charac- ter, character string, or more complex type). Each
variable also has an identifi- cator, which is the name of the variable. A variable
declaration always takes the form :
identifier type;

or the form with initialization (i.e. the variable is given an initial value) : type
identifier = value;
You can also declare several variables of the same type separated by commas.
Example
float x, y=2.0; /* real numbers. y has an initial value of 2.0 */
int n; /* integer */

Depending on the type of variable, certain operations are defined on these


variables (e.g. multiplication in the case of integers, etc.).

3.2 T YPE INTEGER int


The int type (short for integer) is a representation of integers. Like all computer
variables, an int can only take on a finite number of values. An int is generally
coded on 4 bytes (32 bits). In this case, the
values are between -231 and 231 - 1 (i.e. 232 possible values). Note that
on some older systems, int is coded on only 2 bytes.
The binary arithmetic operations +, -, ∗, / are defined on int and give
Dunod. Unauthorized photocopying is an offence.

always results in an int.


If the result of a multiplication, for example, exceeds the limit 2 131 -
of an int's capacity, the result is truncated, giving a sometimes unexpected
result. This is known as overflow.

The division of two integers is a Euclidean division whose result is always


an integer. For example, 7/2 equals 3, not 3.5. This is the source of many
bugs. For example, the result of a division between two variables of type int
may always unexpectedly be 0. This is due to a division between two
integers whose real quotient is between 0 and 1.

15

www.biblio-scientifique.net
Chapter 3 - Data types

The sign - can also designate the opposite of a number. This is referred to as a
unary operation, not a binary one.
There's also an operation called modulo. The modulo is the remainder of the
division between two integers, and is denoted %.
For example, when we say
• "in 17 how many times 5?"
• "3 times and 2 left"
In mathematics, we write: 17 = 3 × 5 + 2.
In computing, we write that 17/5 equals 3 and 17%5 equals 2.
More generally, we still have the expression for Euclidean division:
n = p ∗ (n/ p) + (n%p)
x˛ zx x ˛ _ z_ x
qu ot ie nt r es te

Here's another example: a program that displays the units of a number entered
from the keyboard.

#include <stdio.h>

int main(void){
int number, digit;
puts("Type an integer:");
scanf("%d", &number);
number = number%10;
printf("The last digit is: %d", digit); return 0;
}

3.3 R EAL TYPES float AND double


The float and double types can be used to represent real numbers with a certain
degree of precision (following a representation of numbers called floating point or
floating number).
A real number represented in this way has a mantissa (digits) and an exponent
corresponding to multiplication by a certain power of 10. For example, 3.546E - 3 is
equal to 3.546 × 10–3 , which is 0.003546.
The double type (coded on 8 bytes) is more precise than the float type (coded on 4 bytes).
tets). The maximum value of a double is around 10308 while that of a float is around
1038 . (The exact limit values are given by the constants DBL_MAX and FLT_MAX
in the float.h library).

16

www.biblio-scientifique.net
3.4. The char type

The four binary operations +, -, ∗, / and unary - are defined on real numbers.
The math.h library contains scientific calculation functions such as pow
(power), sqrt (square root), cos, sin, tan and more.

3.4 THE char TYPE


The char type (short for character) is a 1-byte character type. It is the smallest piece
of data that can be stored in a variable. The values (from -126 to 125) can represent
conventional characters.
For example, the uppercase alphabetic characters A, B, . . . Z are 65, 66, . . . 90 and
the corresponding lower-case characters a, b, . . . z have values 97, 98, . . . , 122.
This character coding is known as the ASCII code.
A char variable can be considered either as a number or as a character that can be
displayed. In all cases, it's the same type. To designate the character Z in a program,
for example, you can either write 'Z' (between quotes), or write 90, which is the
ASCII code for the character Z. In both cases, it's the same character and the same
data, which can be stored in the same char variable.

3.5 Unsigned TYPES


The int and char types are matched by unsigned int types (also 4-byte) and
unsigned char (also 1-byte) which represent only positive values.
A 4-byte unsigned int ranges from 0 to 232 - 1.
A 1-byte unsigned char ranges from 0 to 28 - 1 (i.e. from 0 to 255).
Dunod. Unauthorized photocopying is an offence.

3.6 A SSIGNMENTS AND CONVERSIONS


Given two variables of the same type, we can copy the contents of one variable into
the other by means of an assignment (= sign). More generally, you can copy the
value of an entire expression into a variable.
If the two variables are of different types, the = assignment operation will, where
possible, perform a conversion. If conversion is not possible, the compiler will
display an error message.

17

www.biblio-scientifique.net
Chapter 3 - Data types

Assignment example
int var1=0, var2=3; /* declarations with initializations */
var1=2*var2+1; /* assignment: after this var1 is 7 */

Example of converting a float to an int


int n;
float x=7.6587e2;
n = (int)x; /* after this n is 765 (rounded to the integer part) */

Example of converting an unsigned int to an unsigned char


unsigned char c;
unsigned int n = 321;
c = (unsigned char)n; /* after this c is 65 (321 modulo 256) */
/* i.e. c is 'A */

When assigning (for example) a double x to an int n, there is usually a loss of


information. The compiler gives us a warning message, unless we perform a cast,
also known as explicit conversion, by indicating the int type in brackets:

n = (int)x; /* Assignment with explicit conversion (cast) */

A final example: calculating the precise value o f a quotient (2 3 on the example


next) of two integers :
int n=2, m=3;
double two-thirds;
/* conversion before division : */
two-thirds = ((double)n)/((double) m);

Another possibility is to write :


double two-thirds; two-
thirds = 2.0/3.0;

For the calculation of two-thirds above, writing two-thirds=n/m or two-thirds=2/3


is a serious error which leads to the result that two-thirds is equal to 0,
because the quotient between integers gives a Euclidean division, even when
assigned to a float or double.

3.7 C ONSTANTS AND #define


A constant is a value that cannot be changed during program execution. For example,
9.81 is a float constant, 1024 is an int constant (which can also be assigned to a
float variable).

18

www.biblio-scientifique.net
3.8. Define your own types

Finally, 65, or AJJ is a char constant (which can also be assigned to an int or
float).
A constant can be given a name (which avoids the risk of repeating numbers and
increases the flexibility of the program) by a #define at the beginning of the program
(after the #include):
#define PI 3.14159265358979323846 /* Float constant */
#define G 9.81 /* float constant */
#define H 4816 /* int constant */

/* This is also a string constant: */


#define MESSAGE1 "Error, you must put the #define out of the main Ị"
The #define is not just another instruction. Like #include, it is a precompilation
directive.
Don't confuse character constants (char), with simple quotes like 'Z', and string
constants, with double quotes, like "Here's a sentence", which can contain several
characters. The character string "Z" also exists, as a special case of a string with a
single letter, but it's not of char type (we'll look at the string type later).
Do not confuse the character '6', whose ASCII code is 54, with the character 6,
whose ASCII code is 6, but which represents another character.

3.8 DEFINE YOUR OWN TYPES


In C, you can define your own types and give them any name you like. To name a
type, use typedef. In the following example, the programmer has chosen to call
the integers integer rather than int.
#include <stdio.h>

typedef int Integer; /* Definition o f a new Integer type */

int main(void)
{
Integer d, n;
Dunod. Unauthorized photocopying is an offence.

scanf("%d", &n);
d = 2*n;
printf("The double of %d is %d\n", n, d);
return 0;
}
In this case, the Integer type is simply a synonym for int. We'll see later how to
define more complicated types to represent information of all kinds. The various
types defined and used in a program are called data structures.

19

www.biblio-scientifique.net
Chapter 3 - Data types

Exercises

3.1 (∗) Knowing that April 1, 2004 was a Thursday, write a program that determines
the day of the week corresponding to May 4 of the same year. We can
represent the days of the week by numbers from 0 to 6.

3.2 (∗) Write a program that reads a number from the keyboard, answers 1 if the
number is odd and 0 if the number is even.

3.3 (∗∗) Write a program that displays the tens digit of a number entered from the
keyboard. Same question for the hundreds.

3.4 (∗) Write a program that rounds a real number entered on the keyboard to two
decimal places.

3.5 (∗) Write a program that reads a number r from the keyboard and calculates the
perimeter and area of a disk with radius r.

Answers

3.1
int main(void)
{
int ndays;
/* Convention : 0 <-> Monday, ... 6 <-> Sunday
33 days between April 1 and May 4 */
ndays = (33 + 3) % 7 + 1;
printf("May 4th was the %d th day of the week.\n", ndays); return
0;
}

3.2
int main(void)
{
int n, parite;
printf("Enter a number: ");

20

www.biblio-scientifique.net
Answers

scanf("%d", &n);
parite = n % 2;
printf("The parity of the number is %d\n", parity);
return 0;
}

3.3
int main(void)
{
int n, ten, hundred; printf("Enter a
number: "); scanf("%d", &n);
ten = (n / 10) % 10; hundred
= (n / 100) % 10;
printf("The tens digit is %d", ten); printf("The hundreds
digit is %d", hundred); return 0;

3.4
int main(void)
{
float n, rounded;
int multiplies;
printf("Enter a real number: ");
scanf("%f", &n);
multiplie = (int) ((n + 0.005) * 100);
rounding = multiplie / 100.0;
printf("%f two-digit rounding is %.2f\n", n, rounding); return 0;

3.5
int main(void)
Dunod. Unauthorized photocopying is an offence.

{
float radius, perimeter, area;
printf("Enter radius: ");
scanf("%f", &radius);
perimeter = 2.0 * M_PI *
radius; area = M_PI * radius *
radius;
printf("Perimeter = %f\nArea = %f\n", perimeter, area);
return 0;
}

www.biblio-scientifique.net
21

www.biblio-scientifique.net
www.biblio-scientifique.net
I NPUT /O UTPUT :
stdio.h 4
4.1 W HAT IS AN I/O LIBRARY ?
A library is a set of functions added to a programming language . Each library has a
theme. For example (in the C language):
1. the math.h library contains mathematical functions for numerical calculation and
constants such as M_PI to represent the number π ;
2. the time.h library contains types and functions for managing duration (date and
time, program execution time, etc.);
3. the float.h library contains limits and constants for the float and
double ;
4. etc.
5. The stdio.h library contains types and functions f o r managing input/output
(keyboard input, text display, files, etc.).
The .h extension is reserved for header files, which are used when you can't put
the whole program in a single file. Thanks to header files, you can use, in C code,
functions that are written in other files, possibly by other programmers, which is the
case for standard libraries such as stdio.h.
The name stdio.h is short for Standard Input Output. In this chapter, we'll take a
look at some of the library's functions for reading keyboard data and screen displays.
To use the features of the stdio.h library, you need to put at the beginning
program
#include <stdio.h>
Dunod. Unauthorized photocopying is an offence.

4.2 DISPLAYING DATA IN TEXT FORM


4.2.1 Display characters
To display a character, use the putchar function:

putchar('A'); /* Displays an 'A'*/


putchar(65); /* Also displays an 'A'*/

23

www.biblio-scientifique.net
Chapter 4 - Input-output: stdio.h

There's a simple way to display a message (or more generally a character string,
see below) using the puts function:

puts("cuckoo!");

The puts function automatically returns to the line after display. To display a
message without going to the line, you can use printf :

printf("cuckoo!");

4.2.2 D i s p l a y other data


To display numbers, you need to specify a ƒormat, i.e. how the result is to be
displayed.
Let's take the example of a character displayed in two different formats:

char caract='A';
printf("%c", caract); /* display as character 'A'*/
printf("%d", caract) /* displays as number 65 */

Incorrect format specification can lead to incomprehensible results. Sometimes,


several display formats are possible for the same data. They produce a display in
different forms.

1. To display whole numbers, the format is %d :


int number=185;
printf("%d", number);

2. To display a real number (float or double), the usual format is %f :


float x=2.0/3.0;
printf("%f", x);

3. To display a real number (float or double) with m o r e precision (more digits


after the decimal point), the format is %lf :
float x=2.0/3.0;
printf("%lf", x);

4. To display a real number by specifying the number of digits after the decimal
point, the format is %. ?f :
float x=2.0/3.0;
printf("%.3f", x); /* display 0.667 */

24

www.biblio-scientifique.net
4.3. Keyboard reading

5. To display a real number with a power of 10, the format is %e :


float x=6.02e23; /* x = 6.02 × 1023 */
printf("%e", x); /* display 6.020000e23 */
6. To display a character, the usual format is %c :
char caract = 68;
printf("%c", caract); /* Display 'D'*/
7. To display a character string, the format is %s :
printf("%s", "cuckoo!");
With the printf function, you can also combine the display of messages with the
display of numerical data:
double f=25.0/6.0;
int integer = (int) f; /* explicit conversion (cast) */ printf("The
integer part of %f is %d\n", f, integer); printf("The
fractional part of %f is %f", f, f-integer);

Remember that the special character '\n' causes a line break.

4.3 K EYBOARD READING


As in the case of ffichage, functions such as getchar (which reads a character)
and others can be used to read text data. The scanf function can be used to read
data in the following formats (non-exhaustive list):
• %d for type int ;
• %u for the unsigned int type ;
• %f for float type ;
• %lf for double type ;
• %c for the char type ;
• %s for the chain type (studied later).
Dunod. Unauthorized photocopying is an offence.

Don't forget the & in front of each variable in scanf, as this will cause a
memory error (segmentation error).

Unlike display format errors, which generally result in incomprehensible


displays, a wrong format in scanf can pro- vide a memory error. In
particular, in scanf, the %f and %lf formats are incompatible and strictly
dependent on the data type (float or double).

Note that multiple values can be read in a single scanf call, by separating %d,
%f,... with spaces.

25

www.biblio-scientifique.net
Chapter 4 - Input-output: stdio.h

Example
int number;
float f1;
double f2;

Puts("Type an integer:") scanf("%d",


&number);
printf("You've typed %d, bravo Ị\nLet's try again", number);
printf("Type two real numbers");
scanf("%f %lf", &f1, &f2);
printf("You typed: %f and %f. Is this correct?", f1, f2);

In the latter scanf, the user can enter either a space or a cha- riot return ("Enter"
key) between the two real numbers. Putting a character other than a space in scanf,
such as * in the following example, would force the user to enter a specific character.

float f1, f2;

printf("\nTap two real numbers"); puts("MUST be


separated by a * "); scanf("%f*%f", &f1, &f2);
printf("You typed: %f and %f. Is this correct?", f1, f2);

In the previous example, if the user doesn't enter a *, t h e program is blocked on


the scanf.

Exercises

4.1 (c) Write a program to display the ASCII code of a character entered on the
keyboard.

4.2 (∗∗) Write a program that :

1. reads two integers n1 and n2 from the keyboard;


2. displays the integer part of their quotient;
3. displays the fractional frac part of their quotient;
4. reads a real number l from the keyboard ;

26

www.biblio-scientifique.net
Answers

5. calculates the integer part of the product of l and frac modulo 256, then
converts the result into the character ;
6. displays the resulting character.

Test with n1 = 1321, n2 = 500, l = 500.

Answers

4.1
int main(void)
{
char c;
printf("Type a character: ");
scanf("%c", &c);
printf("The ASCII code for %c is %d\n", c, c);
return 0;
}

4.2
int main(void)
{
int n1, n2; int
quotient;
float frac, l;
char c;
printf("Enter two integers: "); scanf("%d
%d", &n1, &n2);
quotient = n1 / n2;
printf("Integer part of quotient: %d n",
\ quotient);
frac = (n1 / (float) n2) - quotient;
printf("Fractional part of quotient: %f", frac);
Dunod. Unauthorized photocopying is an offence.

printf("Enter a real number: ");


scanf("%f", &l);
c = (char) ((int) (l * frac) % 256);
printf("Character : %c\n", c);
return 0;
}

27

www.biblio-scientifique.net
www.biblio-scientifique.net
AL EXECUTION
C ONDITION
5
5.1 W HAT IS CONDITIONAL EXECUTION ?
Conditional execution allows you to do two different things, depending on what
h a p p e n s . The instruction will only be executed under certain conditions. More
specifically, the program tests a condition. If the condition is met, the program does
one thing; if it is not met, the program does something else. A conditional instruc-
tion can take several forms.

5.2 C ONDITION if-then


Suppose we have a condition (for example, that the captain's age is less than 30).
If the condition is met, we do something. If the condition is met, we do something; if
not, we do nothing. In algorithmic terms, this is written as :

instruction series 1 /* program start */


if (condition)
then series of insructions 2
end if
series of instructions 3 /* continuation of program */

This means that instruction series 2 will be executed only if the condition is met.
Let's look at an example in C.

char choix;

puts("Warning, this program may"); puts("offend the


sensibilities of those of you"); puts("who are
allergic to math!");
Dunod. Unauthorized photocopying is an offence.

puts("Do you want to continue? (y/n)");

choice = getchar(); /* getchar is used to enter a character */

if (choice == 'y')
{
puts("The square of the hypotenuse is equal to");
puts("The sum of the squares of the other two
sides!");
}

29

www.biblio-scientifique.net
Chapter 5 - Conditional performance

if (choice == 'n')
puts("Well, well, too bad for you...");

Conditional statements must form a block. A block can be made up of a single


statement (and therefore a single semicolon), or of several statements enclosed in
braces { }. In other words, the curly braces around the if statements are optional if
there is only one statement in the if.
Don't forget the braces { } when the if statement covers more than one
instruction, otherwise only the first instruction will be conditional and subsequent
instructions will not be, resulting in a bug.

Do not mix the = sign, which makes an assignment, and the == sign, which tests
the equality of two expressions. This error would not be detected by the compiler
and would cause a bug.

5.3 C ONDITION si-alors-sinon


Conditional instructions often take the following form:
instruction series 1 /* program start */
if (condition)
then
instruction set 2
or
instruction set 3
end if
series of instructions 4 /* continuation of program */

In other words, in one case, we do one thing, and in the opposite case, we do
something else. Taking the previous example:
...
puts("Do you want to continue? (y/n)");

choice = getchar();

if (choice == 'y')
{
puts("The square of the hypotenuse is equal to");
puts("The sum of the squares of the other two
sides!");
}
else
puts("Well, well, too bad for you...");

30

www.biblio-scientifique.net
5.4. Boolean calculation

Note that in this case, if the user types any character other than 'y' (not just 'n'), the
program enters the else case. Once again, braces are optional if there is only one
instruction.

5.4 B OOLEAN CALCULATION


5.4.1 Basic expressions
The conditions that can be included in an if statement are boo- lean conditions.
An example of a Boolean condition is a comparison test between two expres- sions
using the comparison operators ==, <, >, <=, >=, ! =. These operators have the
following meaning:

• x==y is verified when x is equal to y ;


• x<y is verified when x is strictly less than y ;
• x>y is verified when x is strictly greater than y ;
• x<=y is true when x is less than or equal to y ;
• x>=y is verified when x is greater than or equal to y ;
• x !=y is verified when x is different from y ;

A number (integer, real, etc.) can be considered true or false using the following
convention:

• A non-zero expression (different from 0) is considered true;


• A null expression (equal to 0) is considered false.
Often, the value 1 is given to indicate "true" and the value 0 to indicate "false".

Example
Dunod. Unauthorized photocopying is an offence.

int response;

puts("Type 1 to keep the message, 0 to delete it");

scanf("%d", &reponse);

if (response) /* If response is not zero! */


keep(); else
delete();

31

www.biblio-scientifique.net
Chapter 5 - Conditional performance

In this example, the keep and delete functions must of course have been designed in
advance (see Chapter 6).

5.4.2 Boolean operations


a) Conjunction
The conjunction of two Boolean expressions e1 and e2 is verified when e1 and e2
are both verified.

if (e1 and e2)


then series of instructions
end if

In C, conjunction is given by the && operator.

Example at customs
char papiers, rad;

puts("Do you have your papers? (y/n)");


papers = getchar();
getchar(); /* getchar to eat carriage return */
puts("Do you have anything to declare? (y/n)");
rad = getchar();

if (papers == 'y' && rad == 'n')


puts("O.K., you may pass. Bon voyage.");

Supplements
,
Using a getchar to eat a carriage return. When the user enters a character
or data using getchar or scanf, he or she must press the Enter (or carriage
return) key on the keyboard for the program to follow. The carriage return
character is then in the program's input character set. If you're not careful, this
carriage return will be read by the next scanf or getchar, causing a bug. The
carriage return can be eliminated by performing a getchar in the empty
space, as in the previous example.

b) Disjunction
The disjunction of two Boolean expressions e1 and e2 is verified when at least one of
e1 and e2 is verified.

32

www.biblio-scientifique.net
5.4. Boolean calculation

if (e1 or e2)
then series of instructions
end if

In C, disjunction is given by the | | operator.


Example at customs
char papiers, rad;

puts("Do you have your papers? (y/n)");


papers = getchar();
getchar();
puts("Do you have anything to declare? (y/n)");
rad = getchar();

if (papers Ị= 'y' || rad Ị= 'n')


puts("Please wait here.");

c) Denial
The negation of a condition e is true when condition e is false.
si (non e)
then series of instructions
end if

In C, negation is indicated by a ! (exclamation mark).

Example at customs
char papiers, rad;

puts("Do you have your papers? (y/n)");


papers = getchar();
getchar();
puts("Do you have anything to declare? (y/n)");
rad = getchar();
Dunod. Unauthorized photocopying is an offence.

if (Ị(papers == 'y' && rad == 'n'))


puts("Please wait here.");

Supplements
,
The negation of a conjunction, such as ! (A&&B) is equal to the disjunction of
thenegations (! A)|(! B). Similarly, the negation of a disjunction ! (A| |B) is equal to
the conjunction of negations (! A)&&(! B). This law is called Morgan's Law (to
be meditated on at leisure, using examples).

33

www.biblio-scientifique.net
Chapter 5 - Conditional performance

,
The operators ! &&, | | operators by creating expressions
such as (! A&&B| |C&&D). In the evaluation of expression, the priorities of evalua-
are first the ! then the &&, then the | |. Thus, the expression (! A&&B| |C&&D)
is equivalent to (((! A)&&B) | |(C&&D)). When in doubt, it's always best to
use brackets to avoid mistakes.

5.5 THE switch


The switch can be used to distinguish several cases according to the values of a
variable. The if allows you to distinguish between two cases, while the switch
allows you to distinguish between a large number of cases.
Example of a commercial database menu
char choix;

puts("Menu: make a choice:\n"); puts("Display


customer list -----> a"); puts("Display
customer data --> b"); puts("Enter customer --
----------------> c");
puts("Exit ---------------------------> d");

choice = getchar();

switch(choice)
{
case 'a': puts("Display customer list");
/* insert customer display c o d e here */
break;
box 'b': puts("Display customer data"); puts("Please
enter customer name");
/* enter input and display code here */
break;
box 'c': puts("Enter customer data"); puts("Please enter
data");
/* enter data entry code here */
break;
box 'd' :
break;
default : puts("Choice input error Ị");
}

Here, the choice variable is a char. Different code is executed according to the
values of the variable choice. The default case, which is optional, corresponds to
the code to be executed if none of the other cases apply. You can also make a
switch with variables of type int instead of char. In this case, there are no ' '
quotes in the case.

34

www.biblio-scientifique.net
Exercises

Don't forget the break after processing each case. This error is not detected by
the compiler, but i f the break is forgotten, the instructions for subsequent
cases will also be executed.

Exercises

5.1 (∗) Write a program that reads two variables from the keyboard and displays
them in ascending order, even if you have to modify them.

5.2 (∗) A company X sells two types of products. Type A products, which are subject
to 5.5% VAT, and type B products, which are subject to 5.5% VAT.
VAT at 19.6%. Write a program that reads a product's price before tax from the
keyboard, enters the product type from the keyboard and displays the product's VAT
rate and price including tax.

5.3 (∗) Write a program that reads three variables from the keyboard and displays the
maximum of the three.

5.4 (∗) Let ax2 + bx + c = 0 be a second-degree equation. Write a program that reads
a, b, c from the keyboard and displays any solutions.

5.5 (∗) Write a program that enters two '+' or '-' characters on the keyboard
and calculates the '+' or '-' sign of the product.

5.6 (∗) Write a program that reads two integers a and b and gives the user the choice
:
1. whether the sum a + b is even;
2. whether the product ab is even;
3. to know the sign of the sum a + b ;
4. to know the sign of the product ab.
Dunod. Unauthorized photocopying is an offence.

Answers
5.1
int main(void)
{
int n1, n2, temp;
printf("Enter two integers: "); scanf("%d
%d", &n1, &n2);

35

www.biblio-scientifique.net
Chapter 5 - Conditional performance

if (n1 > n2)


{
temp = n1;
n1 = n2;
n2 = temp;
}
printf("Smaller: %d ; Larger: %d", n1, n2); return 0;

5.2
int main(void)
{
float price, vat, ttc;
char type;
printf("Enter a price: ");
scanf("%f", &prix);
printf("Product type A or B? "); getchar();
type = (char) getchar();
if (type == 'A')
{
vat = 5.5;
}
else
{
vat = 19.6;
}
ttc = price * (1.0 + vat / 100.0);
printf("Price incl. VAT: %f (VAT at %.1f %%)n", ttc,
tva); return 0;
}

5.3
int main(void)
{
float a, b, c, max;
printf("Enter three real numbers: ");
scanf("%f %f %f", &a, &b, &c);
if (a < b)
max = b;
else
max = a;

36

www.biblio-scientifique.net
Answers

if (max < c)
max = c;
printf("The maximum of the three numbers is %f", max);
return 0;
}

5.4
int main(void)
{
float a, b, c, delta, root1, root2;
printf("Enter a, b and c (ax^2+bx+c) : ");
scanf("%f %f %f", &a, &b, &c);
delta = b * b - 4 * a * c;
if (delta == 0.0)
{
root1 = -b / (2 * a);
printf("This polynomial has a single root x = %f\n", root1);
}
if (delta > 0.0)
{
root1 = (-b - sqrt(delta)) / (2 * a);
root2 = (-b + sqrt(delta)) / (2 * a);
printf("This polynomial has two roots x1 = %f and x2 = %f",
root1, root2);
}
if (delta < 0.0)
printf("This polynomial has no real root"); return 0;

5.5
int main(void)
{
char c1, c2, c;
Dunod. Unauthorized photocopying is an offence.

printf("Enter two characters from + and - : ");


scanf("%c %c", &c1, &c2);
if (((c1 != '-') && (c1 != '+')) && ((c2 != '-') && (c2 != '-')))
printf("Incorrect input...");
else
{
if (c1 == c2)
c = '+';

37

www.biblio-scientifique.net
Chapter 5 - Conditional performance

else
c = '-';
printf("The sign of the product is %c\n", c);
}
return 0;
}

5.6
int main(void)
{
int a, b;
char choix;
printf("Enter two integers: ");
scanf("%d %d", &a, &b); printf("Type");
printf("1 to find out if the sum is even");
printf("2 to find out if the product is even");
printf("3 to find out the sign of the sum");
printf("4 to find out the sign of the product");
getchar();
choice = (char)
getchar(); switch
(choice)
{
box '1':
if ((a + b) % 2 == 0)
printf("The sum is even"); else
printf("The sum is odd"); break;
box '2':
if ((a * b) % 2 == 0)
printf("The product is even");
else
printf("The product is odd"); break;
box '3':
if (a + b >= 0)
printf("The sum is positive"); else
printf("The sum is strictly negative"); break;
box '4':
if (a * b >= 0)
printf("The product is positive");

38

www.biblio-scientifique.net
Answers

else
printf("The product is strictly negative");
break;
default:
printf("Wrong choice...");
}
return 0;
}
Dunod. Unauthorized photocopying is an offence.

39

www.biblio-scientifique.net
www.biblio-scientifique.net
C PROGRAM
S TRUCTURING A
6
6.1 W HAT IS A SUB - PROGRAM ?
When a program consists of many lines of code, it is difficult, if not impossible, to
put all the instructions one after the other in the main program. The program would
be unreadable, contain too many va- riables and so on. For this reason, problems are
broken down into sub-problems and the program into sub-programs that solve the
sub-problems. In the C language, the tool for creating sub-programs is the notion of
ƒfunction.

6.2 E XAMPLE OF A C FUNCTION


Suppose you have to calculate an expression several times, for example n7 for
different values of an integer n. It's impractical to repeat the multiplication of n seven
times by itself, and using the pow function in the math.h library is not recommended,
as it doesn't work on the int type, but on the double type. In this case, you can create
y o u r own :

#include <stdio.h>

int Puissance7(int a) /* function prototype */


{
int resultat; /* local variable */
resultat = a*a*a*a*a*a*a; /* calculation of a7 */
return resultat; /* return result */
}

/* Example of use in main : */


Dunod. Unauthorized photocopying is an offence.

int main(void)
{
int n, puiss7; /* main variables */
printf("Please enter n");
scanf("%d", &n); /* read n */
puiss7 = Puissance7(n); /* call function */
/* the result is retrieved from the variable puiss7 */
printf("n power 7 equals %d\n", puiss7); return 0;
}

41

www.biblio-scientifique.net
Chapter 6 - Structuring a C program

The function Puissance7 has one parameter: the integer a. The function calculates
a7 and returns the result so that it can be retrieved in the main function. In main, we
call the function Power7, passing the integer
n. On this line of code, the value of n is copied into parameter a of the Power7
function. The Power7 function code is then executed, calculating a7 . In main, the
value returned by the Power7 function is received by assigning it to the variable
power7. In the end, the variable puiss7 contains the value n7 . This value can then be
used, in this case by displaying it.

Note
The previous Power7 function performs 6 multiplications. We can give a version
that performs only 4 multiplications (with a gain in efficiency):

int Puissance7bis(int n) /* function prototype */


{
int resultat, n2; /* local variables */ n2 =
n*n; /* calculation of n2 */
resultat = n2*n2*n2*n; /* calculation of n7 */
return resultat; /* return result */
}

6.3 E XAMPLE OF A PROGRAM


STRUCTURE
Let's take a very simple (perhaps too simple) example of a program, which we'll de-
compose into sub-programs. This is the program that reads a number x from the
keyboard and calculates ƒ (x) = (x3 - 2x + 1) sin(3x + 1).

#include <stdio.h>
#include <math.h> /* for the sine function */

int main()
{
float x, y; /* we calculate y=f(x) */
puts("Please enter a value for x:");
scanf("%f", &x);
y = (x*x*x-2*x+1)*sin(3*x+1);
printf("we have : f(%f) = %f", x,
y); return 0;
}

42

www.biblio-scientifique.net
6.3. Example of a program structure

Decomposing the program into functions gives :

#include <stdio.h>
#include <math.h>

/* Read function, reads a value */


float Lire(void) /* The function lire returns a float */
{
float d; /* declaration of a local variable d */
puts("Please type a value:"); scanf("%f",
&d); /* we read the value of d */ return d; /*
return the value of d */
}

/* CalculF function, calculates a function value */


float CalculF(float x) /* returns f(x) for x float */
{
return (x*x*x-2*x+1)*sin(3*x+1);
}

/* Display function, displays a value */


void Affiche(float y) /* displays a float y value */
{
printf("The calculated value is %f \ n", y);
/* a void function returns nothing */
}

/* Main function, main program */


int main()
{
float x, y; /* we calculate y=f(x) */
x = Lire(); /* call the Lire function */
y = CalculF(x); /* calculate f(x) */
Affiche(y); /* call Affiche function */ return
0;
Dunod. Unauthorized photocopying is an offence.

Here, the Read function takes no parameters (void parameter). In fact, the
result returned by the Read function depends only on what the user enters on the
keyboard and no other parameters. The CalculF function takes a real number x as
parameter and returns ƒ (x). Note that after the return, a variable is not necessarily
found, but a whole expression can be returned.
In this example, the variable passed as a parameter in main has the same name, x,
as the parameter of the CalculF function. This poses no problem

43

www.biblio-scientifique.net
Chapter 6 - Structuring a C program

but be aware that the x in main and the x in the CalculF function are different
variables, stored in different memory locations, even though the value of the x
variable in main is copied into the x parameter of CalculF.
The Display function doesn't return any values. It simply performs af- fichages and
returns no results to main. Its return type is void. Such a function is also called a
procedure.
The advantage of this way of structuring a program is that, even on very small
programs like this example, the program can be broken down into phases (read,
calculate, display...). This increases modularity, as the Read or Display functions can
be reused as they are by other programs. You can also easily adapt the CalculF
function to calculate other functions. It also enhances source code readability.
Note. The main function could also be rewritten :

int main()
{
Display(CalculF(Lire()));
return 0;
}

However, this style is not recommended until you have mastered parameter
passing and retrieving returned values.

6.4 G ENERAL FORM O F A C FUNCTION


6.4.1 Prototype
The prototype of a function, which tells us how to use it, is of the form :

typeReturn FunctionName(type1 name1, type2 name2,...)

with :

• typeReturn, which is the type of the value returned by the function. If typeReturn
is void, the function returns nothing and is referred to as a procedure.
A procedure can, for example, display data, write to a file, etc.
• FunctionName is the name of the function.
• type1 and nom1, which are the type and name of the first parameter respectively,
type2 and nom2 the type and name of the second parameter, etc. Note that the
tion can have several parameters, separated by commas, and

44

www.biblio-scientifique.net
6.5. Passing parameters by value

that you must indicate the type of each parameter, even if several parameters have
the same type (you must then repeat the type for each parameter).
If the parameter list is empty or void, the function takes no parameters.
The function can, for example, take its data from the keyboard, from a file, etc.

6.4.2 Declaration and definition


A ƒfunction declaration is the prototype of this function followed by a semicolon. A
declaration can be repeated several times in the program and indicates what kind of
function it is (return type, parameter types, etc.).
A ƒfunction definition is the prototype followed by the function body (sequence of
variables and instructions) between braces. The definition must appear only once in
the program and indicates what the function does.

6.4.3 Local variables


Within the definition of a function, there are variable declarations. These variables
are local, i.e. they can only be used within the function. If a variable with the same
name is found elsewhere in the program, it is not the same variable, but a variable
with the same name.

6.5 P ASSING PARAMETERS BY VALUE


When a parameter is passed to a function, the function cannot modify the variable.
The variable is automatically copied, and the function works on a copy of the
variable. This technique is known as passing a parameter by value.
#include <stdio.h>

void DoNotChange(int x)
{
x = 2; /* the local x is modified, not the main x */
}
Dunod. Unauthorized photocopying is an offence.

int main(void)
{
int x=1;
NeModifiePas(x);
printf("%d", x); /* display 1 (value unchanged) */
}

For the moment, the only way we've seen for a trans- function to set a value in
main is for that function to return a result via return.

45

www.biblio-scientifique.net
Chapter 6 - Structuring a C program

With this technique, the function can only return a single value. Later, we'll look at
the technique of parameter passing by address, which allows a function to modify the
contents of a main variable, and thus transmit several values to main.

Exercises

6.1 (∗) Write a C function that displays the ASCII code of a character passed as a pa-
rameter. Write a main program that enters a character from the keyboard and displays
its ASCII code.

6.2 (∗) Write a C function that calculates the average of three numbers passed as a
pa- rameter. Write the main program that enters three numbers on the keyboard and
displays
their average.

6.3 (∗) Write a C function that affiches the area of a triangle whose base and height
are passed as parameters. Write the main program that enters the base and height of
the triangle.
height of a triangle and displays the area of the triangle.

6.4 (∗) Let a tax scale be defined as follows: for a household X with total income R
and a number n of household members, the tax is given by :
R
• 10% of R if n < 500 euros ;
R
• 20% R if n ≥ 500 euros.
a) Write an Impot function that calculates the amount of tax as a function of R and n.
b) Write an IncomeNet function that calculates a household's net income after taxes
as a function of R and n. A main program can be made that enters R and n on the
keyboard, then displays the tax and net income.
(2x3 +3)(x2 -1)
,
6.5 (∗∗) Let the mathematical function ƒ be defined by ƒ (x) = 23x +1
.
a) Write a C function that returns the value of ƒ (x) for a point x passed in parameter.

b) An approximation of the derivative ƒJ of the function ƒ is given at each point x, for


h small enough (close to 0), by :
ƒ (x + h) - ƒ (x - h)
ƒ J(x) ≈ .
2h

46

www.biblio-scientifique.net
Answers

Write a function C that calculates an approximation of the derivative ƒJ of ƒ at a point


x entered from the keyboard. We pass the value of h as a function parameter.
c) The second derivative of ƒ is the derivative of the derivative. Write a function C
that cal- culates an approximation of the second derivative ƒJJ of ƒ at a point x entered
on the keyboard. Pass the value of h as a parameter to the function.
d) Write a C function that determines the sign of the second derivative of ƒ as a
function of x. The main program can be made to read x from the keyboard and
display the result.
e) Write a C function that gives the user the choice of displaying the value of the
function ƒ , its first derivative or its second derivative at a point x read from the
keyboard.

Answers

6.1
void afficheASCII(char caractere)
{
printf("ASCII code = %d\n", character);
}
int main(void)
{
char c;
printf("Enter a character: "); c
= (char) getchar();
displayASCII(c);
return 0;
}

6.2
float average(float a, float b, float c)
{
Dunod. Unauthorized photocopying is an offence.

return (a + b + c) / 3.0;
}
int main(void)
{
float n1, n2, n3;
printf("Enter three numbers: ");
scanf("%f %f %f", &n1, &n2, &n3);
printf("The average number is %f\n", average(n1, n2, n3)); return
0;
}

www.biblio-scientifique.net
47

www.biblio-scientifique.net
Chapter 6 - Structuring a C program

6.3
void aire(float base, float height)
{
printf("Area = %f\n", (base * height) / 2.0);
}
int main(void)
{
float b, h;
printf("Enter the base and height of the triangle: ");
scanf("%f %f", &b, &h);
aire(b, h);
return 0;
}

6.4
a)
float Impot(float R, int n)
{
if (R / n < 500.0)
return 0.1 * R;
else
return 0.2 * R;
}
b)
float RevenuNet(float R, int n)
{
return R - Impot(R, n);
}

6.5
a)
float f(float x)
{
return ((2 * x * x * x + 3) * (x * x - 1)) / sqrt(3 * x * x + 1);
}
b)
float fPrime(float x, float h)
{
return (f(x + h) - f(x - h)) / (2 * h);
}

48

www.biblio-scientifique.net
Answers

c)
float fSecond(float x, float h)
{
return (fPrime(x + h, h) - fPrime(x - h, h)) / (2 * h);
}
d)
int sign(float x)
{
float h, dSecond;
printf("Enter approximation step h: "); scanf("%f",
&h);
dSecond = fSecond(x, h);
if (dSecond < 0.0)
return -1;
if (dSecond == 0.0)
return 0;
return 1;
}
e)
void choix()
{
int c;
float x, h;
printf("Do you want...\n");
printf("1 the value of f\n");
printf("2 the value of f'\n");
printf("3 the value of f''\n");
c = getchar();
printf("x = ? ");
scanf("%f", &x);
switch (c)
{
box '1':
Dunod. Unauthorized photocopying is an offence.

printf("f(%f) = %f\n", x, f(x));


break;
case '2': printf("h
= ? ");
scanf("%f", &h);
printf("f'(%f) = %f\n", x, fPrime(x, h));
break;
case '3': printf("h
= ? ");
scanf("%f", &h);

49

www.biblio-scientifique.net
Chapter 6 - Structuring a C program

printf("f''(%f) = %f\n", x, fSecond(x, h));


break;
default:
printf("Choice unknown...");
}
}

50

www.biblio-scientifique.net
S TRUCTURES
7
7.1 S TRUCTURE DECLARATION
A structure is a type that allows you to store several pieces of data, of the same or
different types, in a single structure variable. A structure is made up of several fields,
each field corresponding to a piece of data.

Example
Here's the declaration of a Point structure containing three float fields x, y
and z.

struct point
{ /* structure declaration */
float x,y; /* three fields x, y, z */
float z; /* fields are declared as variables */
/* but values cannot be initialized */
};

A struct point variable is then declared in the same way as any other variable:

struct point P; /* P variable declaration */

7.2 U SING A STRUCTURE


Once the variable has been declared, the x,y,z data for point P are accessed via a
point. This data is referred to in the program as P.x,P.y,P.z. The data
Dunod. Unauthorized photocopying is an offence.

P.x,P.y,P.z, here of float type, are treated like any other float data in the
program.
Note that other data of any type can be added after the x,y,z data in the structure.
Here's an example of a program with a point structure.

#include <stdio.h>

struct point
{ /* structure declaration */

51

www.biblio-scientifique.net
Chapter 7 - Structures

float x,y,z;
}; /* don't forget the semicolon */

int main(void)
{
struct point P;
puts("Please enter the coordinates of a 3D point:");
scanf("%f %f %f", &P.x, &P.y, &P.z);
puts("The homothety of center O and ratio 3");
printf("applied to this point gives:'');
printf("(%.2f, %.2f, %.2f)n", 3*P.x, 3*P.y, 3*P.z);
return 0;
}

To avoid repeating the word struct when declaring variables of type struc
point, we can define a shortcut with a typedef when defining the structure, to give
a new name to this type :

/* Point3D type definition */

typedef struct point


{ /* declaration of a */
float x,y,z; /* new type by typedef */
}Point3D;

The declaration of a Point3D variable is then made in the same way as for a variable
of another type, by first entering the type and then the variable identifier:

Point3D P; /* Declaration of a Point3D variable P */

Point3D P's x, y and z data are always referred to as P.x, P.y and P.z.
Let's now look at a program that calculates the addition (as a coordinate-by-
coordinate vector sum) of two Point3Ds entered via the keyboard:

#include <stdio.h>

typedef struct point


{ /* structure declaration */
float x,y,z;
}Point3D;

/* the following function takes a Point3D as parameter */


void Display(Point3D P)
{

52

www.biblio-scientifique.net
7.2. Using a structure

/* Field display : */
printf("(%f, %f, %f)", P.x, P.y, P.z);
}

/* the following function returns the structure */


Point3D InputPoint3D(void)
{
Point3D P; /* Point3D type variable */
printf("Enter three coordinates separated by spaces");
scanf("%f %f %f", &P.x, &P.y, &P.z); /* input fields */ return
P; /* return variable */
}

Point3D Addition(Point3D P1, Point3D P2)


{
Point3D result;
resultat.x = P1.x + P2.x; /* coordinate calculation */
resultat.y = P1.y + P2.y; /* field access via . */
resultat.z = P1.y + P2.z;
return resultat; /* the function returns the structure */
}

int main(void)
{
Point3D p1, p2, add;
printf("Enter the coordinates of two points");
p1 = SaisiePoint3D(); /* we retrieve the saisie structure */
p2 = SaisiePoint3D();
add = Addition(p1,p2); /* call the addition function */
printf("Addition is: ");
Display(add);
printf("\n");
return 0;
}
Dunod. Unauthorized photocopying is an offence.

53

www.biblio-scientifique.net
Chapter 7 - Structures

Exercises

7.1 (∗) Define a RationalNumber structure to encode a rational number, with


numerator and denominator. We'll write functions for entering, displaying and editing
rational numbers.
The following steps are used to solve the problems of multiplication and addition of
two rationals. To simplify addition, we won't necessarily be looking for the lowest
common denominator.

7.2 (∗) An industrial joinery manages a stock of wood panels. Each panel has a
width, length and thickness in millimeters, as well as the number of millimeters.
type of wood, which can be pine (code 0), oak (code 1) or beech (code 2).

a) Define a panel structure containing all the information relating to a wood panel.

b) Write input and display functions for a wood panel.

c) Write a function that calculates the volume in cubic meters of a panel.

7.3 (∗) A wholesaler of electronic components sells four types of products:


• Motherboards (code 1) ;
• Processors (code 2) ;
• Memory sticks (code 3) ;
• Graphics cards (code 4).
Each product has a reference number (which is an integer), a price in euros and
available quantities.

a) Define a product structure that codes a product.

b) Write a function for entering and displaying product data.

c) Write a function that allows a user to enter an order for a product. The user enters
order quantities and product data. The computer displays all order data, including
price.

www.biblio-scientifique.net
54

www.biblio-scientifique.net
Answers

Answers

7.1
typedef struct rational
{
int numerator, denominator;
} RationalNumber;
RationalNumber Input()
{
RationalNumber n;
printf("Enter numerator and denominator: ");
scanf("%f %f", &n.numerator, &n.denominator); return
n;
}

void Affichage(RationalNumber n)
{
printf("%f/%f\n", n.numerator, n.denominator);
}

RationalNumber Multiply(RationalNumber p, RationalNumber q)


{
RationalNumber r;
r.numerator = p.numerator * q.numerator;
r.denominator = p.denominator * q.denominator;
return r;
}

RationalNumber Add(RationalNumber p, RationalNumber q)


{
RationalNumber r;
r.numerator =
Dunod. Unauthorized photocopying is an offence.

p.numerator * q.denominator + q.numerator * p.denominator; r.denominator =


p.denominator * q.denominator;
return r;
}

55

www.biblio-scientifique.net
Chapter 7 - Structures

7.2
a)
typedef struct bois
{
float width, length, thickness;
petrol tank;
} Panels;
b)
Input() panels
{
Panels p;
printf("Enter width, length and thickness: "); scanf("%f %f
%f", &p.width, &p.length, &p.thickness); printf("Enter wood
type: ");
scanf("%c", &p.essence);
return p;
}

void Affichage(Panels p)
{
printf("Panel in ");
switch (p.essence)
{
case '0':
printf("pin\n");
break;
case '1':
printf("chêne\n");
break;
case '2':
printf("hêtre\n");
break;
default:
printf("unknown");
}
printf("width = %f ; length = %f ; thickness = %f",
p.width, p.length, p.thickness);
}
c)
float Volume(Panels p)
{
return (p.width * p.length * p.thickness) / 1e9;
}

56

www.biblio-scientifique.net
Answers

7.3
a)
typedef struct product
{
char type;
unsigned int reference;
float price;
unsigned int quantity;
} Product;
b)
Product Input()
{
Product p;
printf("Enter product code: \n"); scanf("%c",
&p.type);
printf("Enter reference:");
scanf("%u", &p.reference);
printf("Enter price:");
scanf("%f", &p.price);
printf("Enter quantity:");
scanf("%u", &p.quantity);
return p;
}

void Affichage(Product p)
{
printf("Type : %c\n", p.type);
printf("Reference : %u\n", p.reference);
printf("Price : %f\n", p.price);
printf("Quantity: %u\n", p.quantite);
}
c)
void Order()
Dunod. Unauthorized photocopying is an offence.

{
unsigned int qte;
Product p = Saisie();
printf("Enter quantity ordered: "); scanf("%u",
&qte);
printf("Order summary"); Display(p);
printf("Order value: %.2f\n", p.price * qte);
}

57

www.biblio-scientifique.net
www.biblio-scientifique.net
I TERATION
8
An iteration allows the same series of instructions to be repeated several times,
enabling recurrence or the processing of large volumes of data.

8.1 While LOOP


In the while loop, the program repeats a block o f instructions as long as a certain
condition is true. In algorithmic language, this is expressed as :
series of instructions 1; /* program start */
as long as (condition)
make series of instructions 2; /* repeated instructions */
end as long as
series of instructions 3; /* continuation of program */

This condition is called a stop condition. When the stop condition becomes false,
the program exits the as long as loop and moves on to the next part of the program. If
the program is well designed, instruction series 2 must make the stop condition false
at some point, otherwise the program continues indefinitely in an endless loop (the
program is said to loop).
Let's take an example. Suppose we want to make a function that calculates nk ,
where n is an integer and k is an integer exponent entered from the keyboard. The
result must be an integer. It's not a good idea to use math.h's pow function, as this
calculates using floating-point real numbers, which leads to rounding problems.

int Power(int n, int k)


{
int i = 0; /* initialization initialization */
int resultat = 1; /* initialize to 1 (product calculation) */
while (i < k) /* loop until */
Dunod. Unauthorized photocopying is an offence.

{
result = result*n;
i = i+1; /* progression progression */
}
return resultat;
}

Initially, variable i is 0 (initialization). If k is strictly positive, the stop condition


i<k is true, and we enter the while. Each time a while instruction is executed, the
instruction i=i+1 is executed, increasing the value of the variable.

59

www.biblio-scientifique.net
Chapter 8 - Iteration

of variable i (incrementing means increasing the value of a variable by 1). The


stopping condition is then retested before the next iteration. As the variable i
increases with each iteration, after a while the stop condition i<k becomes false,
and the loop ends; we move on to the rest of the program, in this case the return
instruction. If k is ever equal to 0, the stop condition is false from the start, the
program doesn't enter the while at all, and the result is 1, which is equal to nk
with k = 0.
In this way, multiplications by n are accumulated in the variable resultat, which
initially has a value of 1. With each iteration, the variable i increases and
eventually becomes equal to k after exactly k iterations. The stop condition i < k
then becomes false, and we exit the loop. The variable resultat is now nk ,
product of n times itself k times.
Be careful not to over- or under-multiply: the variable i starts at 0 and a condition
< is set, not <=. Multiplication by n therefore occurs exactly k times.

This is a until condition, not a until condition. The instructions are repeated as
long as the stop condition is true, and the program exits the loop when the
condition becomes false, not the other way around.

Note that the instructions in the while must form a block, i.e. they must be
enclosed in braces {}, unless there is only one instruction, in which case braces are
optional.

8.2 For LOOP


We can see that, in general, the structure of a while iteration is of the form :
initialization;
as long as (condition)
go to
{
series of instructions;
progression;
}

In C, there's a more convenient syntax for doing all this: the for loop:

for (initialization; condition; progress)


{
set of instructions;
}

60

www.biblio-scientifique.net
Exercises

Thus, the above program that calculates nk can be rewritten:

int PowerBis(int n, int k)


{
int i; /* no more initialization here */
int resultat = 1; /* initialize to 1 (product calculation) */
for (i=0; i < k; i=i+1) /* for loop */
{
result = result*n;
}
return resultat;
}

At the start of the for loop, the initialization instruction i=0 is executed. The stop
condition is then tested. If the stop condition is true, the instructions in the for
loop are executed, after which the progress instruction i=i+1 is executed. The
stop condition is then re-tested before the next iteration, etc., as long as the stop
condition is true.
Note that in this example, the braces in the for statement are optional, as there is
only one statement in the for loop.

Supplements
,
The instruction i=i+1 is called incrementing variable i. An increment
increases the value of the variable by 1. A more compact way of writing an
increment in C is to write i++ instead of i=i+1.

Exercises
Dunod. Unauthorized photocopying is an offence.

While loops
8.1 (∗) Write a function that calculates the factorial n! of an integer n passed as a
p a r a m e t e r (Remember: n! = 1 × 2 × - - - × n).

8.2 (∗) Write a function that calculates the sum :


s = 1 + 23 + 33 + - - - + n3
as a function of n.

61

www.biblio-scientifique.net
Chapter 8 - Iteration

8.3 (∗∗) We want to write a voting machine program. Users are made to vote as long
as there are votes between candidate A and candidate B. Each time, the computer
asks if he should continue. At the end, the computer must display the vote
percentages and the winner. The program must be 100% reliable and allow no input
errors.

8.4 (∗∗)
a) Write a function that calculates the number of digits in base 10 of a number n.

b) Write a function that calculates the ith digit in base 10 of a number n. The integers
i and n are entered from the keyboard. We'll assume that the digits are numbered
backwards (the units digit is 0, the tens digit is 1...).

Loops for
8.5 (∗) Write a function that displays the value in degrees Celsius corresponding to
the values 0, 10, 20,..., 300 degrees Fahrenheit. We'll use the conversion formula :
5
C = (F 32)
9 -

8.6 (∗) Write a function that returns the greatest power of 2 less than the constant C =
2,426,555,645.

8.7 (∗) A sequence (u )nn∈N is defined by recurrence :


,
u0 = 1 and un+1 = 2 ∗ u n + 1 - 1 for n ≥ 0
Give an algorithm for calculating un , the number n ≥ 0 being entered on the keyboard.
150 sin(i)
8.8 ( ) Let ƒ (i) = for n N.
∗∗ (i + 1) ∈

a) Write a function that returns the maximum of ƒ (i) for i integer between 0 and N- 1 ,
where N is an integer passed as a parameter.

b) Write a function that counts the number of ƒ(i) values between -a and
+a, with i between 0 and N - 1, for real a passed as parameter.
8.9 (∗∗) The Fibonacci sequence is defined by recurrence as follows:
u0 = 1, u1 = 1, and un = un–1 + un–2 for n ≥ 2 Write
a function that calculates the nth term of the Fibonacci sequence.

62

www.biblio-scientifique.net
Answers

Answers

8.1
int fact(int n)
{
int f = 1;
while (n > 0)
{
f = f * n;
n = n - 1;
}
return f;
}

8.2
int cube(int n)
{
int s = 0;
while (n > 0)
{
s = s + n * n * n;
n = n - 1;
}
return s;
}

8.3
void vote()
{
int nVotantA = 0, nVotantB = 0;
char c;
int stop = 0, choice; /* 0 <-> false; !0 <-> true */
Dunod. Unauthorized photocopying is an offence.

float voice;
while (!stop)
{
choice = 0;
printf("Shall we continue (o/n) ?
"); while (!choice)
{
c = (char) getchar();
choice = (c == 'o') || (c == 'n');
}

63

www.biblio-scientifique.net
Chapter 8 - Iteration

if (c == 'o')
{
choice = 0;
printf("Vote for A or B? "); while
(!choice)
{
c = getchar();
choice = (c == 'A') || (c == 'B');
}
if (c == 'A')
nVotantA = nVotantA + 1;
else
nVoterB = nVoterB + 1;
}
else
stop = !stop;
}
if (nVoterA + nVoterB > 0)
{
vote = (100.0 * nVoterA) / (float) (nVoterA + nVoterB); printf("A
obtained %f %% of the votes and B obtained %f %% of the votes",
votes, 100 - votes);
if (nVotantA >
nVotantB) printf("A is
elected"); if (nVotantA
< nVotantB) printf("B
is elected");
if (nVotantA == nVotantB)
printf("None elected");
} }

8.4
a)
int base10(int n)
{
int nombre = 0;
while (n > 0)
{
n = n / 10;
number = number + 1;
}
return number;
}

64

www.biblio-scientifique.net
Answers

b)
int base10i(int n, int i)
{
while (i > 0)
{
n = n / 10;
i = i - 1;
}
return n % 10;
}

8.5
void celsius()
{
int i;
for (i = 0; i <= 300; i = i + 10)
{
printf("%d degrees Fahrenheit give %.2f degrees Celsius", i, (5 *
(i - 32.0) / 9.0));
}
}

8.6
#define C 2426555645
unsigned int puissance2()
{
unsigned int n;
int i = 0;
for (n = C; n / 2 > 0; n = n / 2)
i = i + 1;
return i;
}

int main()
Dunod. Unauthorized photocopying is an offence.

{
printf("%u\n", puissance2());
return 0;
}

65

www.biblio-scientifique.net
Chapter 8 - Iteration

8.7
float un(unsigned int n)
{
float u = 1.0;
unsigned int i;
for (i = 1; i <= n; i++) u
= 2 * sqrt(u + 1) - 1;
return u;
}

8.8
a)
double f(int n)
{
return (150 * sin(n)) / (double) (1 + n);
}
double max(int N)
{
int i;
double fi, maxi = f(0);
for (i = 1; i < N; i++)
{
fi = f(i);
if (fi > maxi)
maxi = fi;
}
return max;
}

b)
int nombre(int N, double a)
{
int i, nb;
double fi;
nb = 0;
for (i = 0; i < N; i++)
{
fi = f(i);
if (fabs(fi) <= a)
nb++;
}
return nb;
}

66

www.biblio-scientifique.net
Answers

8.9
int fibonacci(int n)
{
int u = 1, v = 1;
int i;
for (i = 2; i <= n; i++)
{
v = u + v;
u = v - u;
}
return v;
}
Dunod. Unauthorized photocopying is an offence.

67

www.biblio-scientifique.net
www.biblio-scientifique.net
Part 2

Sequential structures

www.biblio-scientifique.net
www.biblio-scientifique.net
T ABLES
9
An array can be used to store several items of data of the same type. Unlike simple
variables, arrays can store large amounts of data in main memory. The difference
between arrays and structures is that not all the data in an array has to be declared
manually in the code; declaring the array in one line is enough to declare all the data.
On the other hand, all array data must be of the same type (even if the type of array
elements can be a complex type such as a structure).

9.1 D ECLARING AN ARRAY


A (static) array is declared by
typeElements tableName[NUMBER_ELEMENTS];

where typeElements is the type of elements in the array, arrayName is the name of
the array, and NUMBER_ELEMENTS is a constant indicating the number of elements in
the array.
For example, to declare an array of 100 integers called tab :
int tab[100];

To declare an array of 150 characters called string ;


char string[150];

In such a declaration, the number of array elements is necessarily a constant. The


number of array elements can be defined in a #define directive, which increases the
program's flexibility (the number of elements can be changed by changing the
#define). We'll see in the chapter on dynamic allocation how to create arrays whose
Dunod. Unauthorized photocopying is an offence.

number of memory locations is given by a variable.

9.2 E LEMENT ACCESS


The elements of an array are like cells arranged successively in main memory. The
elements of an array are numbered by indices. For example, the elements of the tab
array declared above, which has 100 elements, have indices 0, 1, 2, . . . , 99.

71

www.biblio-scientifique.net
Chapter 9 - Tables

tab[0] tab[1] tab[2] tab[3] tab[4] ...


0 1 2 3 4 ...
The indices of the elements of an array start at 0, not 1. Consequently, the
elements of an N-element array have indices ranging from 0 to N 1. Accessing- an
element with an index greater than or equal to N will systematically produce a false
result, and usually a memory error (segmentation error). This is known as array
overflow.

The element with index 3 in the tab array is denoted tab[3]. More generally, the
element with index i in the tab array is denoted tab[i]. The index i must be a
positive integer or zero, but it can be the result of a whole expres- sion, as in
tab[3*m+2], where m is an integer.

9.3 N UMBER O F ELEMENTS FIXED


The following program allows you to store different values entered from the
keyboard and to display them again in the order in which they were entered. The
number of values, or table elements, is set to 15.

#include <stdio.h>

#define NB_ELEM 15 /* Number of elements in array */

/* ******** Display function ********** */


/* Display an array */

void Affichage(float tableau[NB_ELEM])


{
int i;
for (i=0; i<NB_ELEM; i++)
{
printf("element number %d is %f", i, array[i]);
}
}

/* ********* Main function ********** */


/* Reads an array and displays it */

int main()
{
int i; /* index */
float tableau[NB_ELEM]; /* array declaration */
for (i=0; i<NB_ELEM; i++)

72

www.biblio-scientifique.net
9.4. Bounded number of variable elements

{
printf("Enter element %d: ", i);
scanf("%f", &tableau[i]); /* read an element */
}
Display(array); /* Display array */
return 0;
}

9.4 B OUNDED NUMBER O F VARIABLE ELEMENTS


The following program also reads elements from the keyboard and displays them
again, but this time the number of elements is read from the keyboard. However, the
number of elements must remain below a fixed constant maximum value. The idea is
to use only part of the array. Memory locations are reserved for NB_ELEM_MAXI
elements in the array, but it is not essential to use all the cells in the array. However,
the number of cells used must be less than or equal to NB_ELEM_MAXI.

#include <stdio.h>

#define NB_ELEM_MAXI 100 /* Maximum number of elements */


/* of the table */

/* ******** Display function ********** */


/* Displays an array of size n */

void Affichage(float tableau[], int n)


{
int i;
for (i=0; i<n; i++)
{
printf("element number %d is %f", i, array[i]);
}
Dunod. Unauthorized photocopying is an offence.

/* ********* Main function ********** */


/* Reads an array and displays it */

int main()
{
int n, i; /* number of elements and index */
float tableau[NB_ELEM_MAXI]; /* array declaration */
printf("Enter the number of elements to type: ");

73

www.biblio-scientifique.net
Chapter 9 - Tables

/* read number o f elements from keyboard (variable) */


scanf("%d", &n);
if (n > NB_ELEM_MAXI)
{ /* error t e s t */
puts("Error, number too large!"); return
1;
}
for (i=0; i<n; i++)
{ /* n elements */
printf("Enter element %d: ", i);
scanf("%f", &tableau[i]); /* read an element */
}
Display(array, n); /* Display array */
return 0;
}

The maximum number NB_ELEM_MAXI, which corresponds to the number of


available memory locations, is sometimes referred to as the physical size of the array.
The number n of array elements actually used is the array's logical size.
You could also read the elements of the array into a function. It is impossible to
return an array (unless it has been dynamically allocated, as explained in Chapter 12).
On the other hand, you can modify the elements of an array passed as a parameter to
initialize them.

#include <stdio.h>

#define NB_ELEM_MAXI 100 /* Maximum number of elements */

/* ******** Input function ********** */


/* Keyboard table entry */
/* The number of elements is returned */

int TableInput(float table[NB_ELEM_MAXI])


{
int n, i;
puts("Enter the number of elements in the array:
"); scanf("%d", &n);
if (n > NB_ELEM_MAXI)
{
puts("Error: the array is too small");
return -1; /* return an error code */
}
puts("Enter the elements one by
one"); for (i=0 ; i<n ; i++)

74

www.biblio-scientifique.net
9.5. Initialization on declaration

scanf("%f", &tableau[i]);
return n;
}

int main()
{
int n; /* number of elements */
float tableau[NB_ELEM_MAXI]; /* array declaration */
n = SaisieTableau(tableau);
if (n > 0) /* Error t e s t */
Display(array, n); /* Display array */
return 0;
}

In general, variables passed as parameters to a function cannot be modified


(value passing). However, for an array, you can modify the elements of an array
passed as a parameter. This is because, as we'll understand in greater detail in
Chapter 12, the array type is in fact an address at which the elements are stored
in memory.

9.5 I NITIALIZATION ON DECLARATION


As with other variable types, array elements can be initialized when the array is
declared. This is done by enclosing element values in { } braces, separated by
commas.

#include <stdio.h>

int main(void)
{
int tab[5] = {3, 56, 21, 34, 6}; /* with semicolon */

for (i=0; i<5; i++) /* display elements */


printf("tab[%d] = %d\n", i, tab[i]);
Dunod. Unauthorized photocopying is an offence.

return 0;
}

75

www.biblio-scientifique.net
Chapter 9 - Tables

Exercises

9.1 (∗) Write a function that takes an integer array and its number of elements as
parameters, and displays elements with odd indices.

9.2 (∗) Write a function that takes an array of integers as a parameter and calculates
the maximum of all the elements in the array.

9.3 (∗) Write a function that takes an array of integers as a parameter and calculates
the sum of its elements.

9.4 (∗) Write a function that takes as parameters an array of integers, its number of
elements n and an integer m, and returns 1 if there is an element equal to m in the
array.
array, 0 otherwise. (The return type of the function must be char).

9.5 (∗∗) Write a function that takes as parameters an array of size NB_MAX, its
number of elements n < NB_MAX, an integer i ≤ n, and an integer m. The function
must insert element m at position i in the array (without deleting any elements).

9.6 (∗∗ ∗)
a) Write a function that initializes each tab[i] element of a tab array passed in
parameter to the value 2i .

b) Using a), write a function that reads characters equal to 0 or 1 from the keyboard
and calculates the number these digits represent in binary. The result can be
displayed in base 10.

Answers

9.1
#define NB_ELEM_MAXI 100
void afficheImpair(int t[NB_ELEM_MAXI], int size)
{
int i;
for (i = 1; i < size; i += 2)
printf("t[%d] = %d\n", i, t[i]);
}

76

www.biblio-scientifique.net
Answers

9.2
#define NB_ELEM_MAXI 100
int max(int t[NB_ELEM_MAXI])
{
int i;
int max = t[0];
for (i = 1; i < NB_ELEM_MAXI; i++)
{
if (max < t[i])
max = t[i];
}
return max;
}

9.3
#define NB_ELEM_MAXI 100
int sum(int t[NB_ELEM_MAXI])
{
int i;
int sum = t[0];
for (i = 1; i < NB_ELEM_MAXI; i++)
sum += t[i];
return sum;
}

9.4
#define NB_ELEM_MAXI 100
char recherche(int t[NB_ELEM_MAXI], int taille, int m)
{
int i;
for (i = 0; i < size; i++)
{
if (t[i] == m)
return 1;
Dunod. Unauthorized photocopying is an offence.

}
return 0;
}

9.5
#define NB_MAX 100
void insertion(int t[NB_MAX], int n, int i, int m)
{
int j = n;
while (j > i)

77

www.biblio-scientifique.net
Chapter 9 - Tables

{
t[j] = t[j - 1];
j--;
}
t[i] = m;
}

9.6
#define NB_MAX 31
a)
void fill(unsigned int t[NB_MAX])
{
int i = 1;
t[0] = 1;
while (i < NB_MAX)
{
t[i] = t[i - 1] * 2;
i++;
}
}
b)
void keyboard()
{
char c;
int choice, i = 0;
unsigned int n;
unsigned int t[NB_MAX]; fill(t);
while (!0)
{
choice = 0;
printf("Enter 0 or 1 : ");
while (!choice)
{
c = getchar();
choice = ((c == '0') || (c == '1'));
}
if (c == '1')
n += t[i];
i++;
printf("Current value: %d\n", n);
}
}

78

www.biblio-scientifique.net
T EXT FILES
10
10.1 W HAT I S A TEXT FILE ?
There are two main types of memory in a computer: main memory and disk memory.
The data stored in main memory are the va- riables of the various programs and last
only as long as the execution of a pro- gram. Arrays store data in main memory. To
store data permanently, you need to store it on a disk (or a peripheral device such as a
USB key).
A file is a set of data stored on a disk or storage device. A text file is a file
containing ASCII text.
Reading into a file is the transfer of data from the file to main memory. Reading
from a text file is analogous to reading from the keyboard: the text comes from the
file rather than from the keyboard.
Writing to a file is the transfer of data from main memory to the file. Writing to a
text file is analogous to writing to the screen: the text goes into the file instead of
being displayed.
The aim of this chapter is to show how a C program can read and write data in a
text file.

10.2 O PEN AND CLOSE A TEXT FILE


To use text files, you need to include the :
#include<stdio.h>
Dunod. Unauthorized photocopying is an offence.

To read or write to a text file, we need a file pointer. The file pointer allows us to
designate the file we wish to read from or write to. A file pointer is of type FILE *.
We declare such a pointer like any other variable:
FILE *fp; /* declaration of a file pointer fp */

Before the file can be written to or read from, the file pointer must be linked to a
file on disk. This operation is called opening the file. This is done with the fopen
function, which takes the name of the file on disk as a parameter.

79

www.biblio-scientifique.net
Chapter 10 - Text files

Let's take the case of opening a file for reading, i.e. opening the file only to be
able to read data from it.

FILE *fp;
fp = fopen("myfile.txt", "r");
/* (example of relative path: local directory) */

FILE *fp;
fp = fopen("/home/remy/algo/monfichier.txt", "r");
/* (example of an absolute path under Unix or Linux) */

FILE *fp;
fp = fopen("C:\remy\algo\\monfichier.txt", "r");
/* (example of an absolute path under Windows) */

The first parameter is the file name, or more precisely, the path to the file in the
directory tree. In the case of a relative path, the path starts from the working directory
(given by pwd under Unix/Linux). In the case of an absolute path, the path starts from
the root of the directory tree (the / partition under Unix or Linux or a C:, D:, etc.
partition under Windows). Note that the
\ (backslash) is represented in character strings by a special character (in the same
way asJ \nJ for line breaks). This special character is JJ . This is precisely because
the \ is used to designate special characters such asJ \n ,JJ \%J , etc.
The second parameter of the fopen function is the mode, and "r" stands for "file open
read-only". The various possible modes for a text file are :
- "r": read-only mode. The file is opened at the beginning, ready to read data. Any
attempt to write to the file will result in a segmentation error.

• "w": write-only mode. The file is initially empty. If the file already existed before
fopen was called, it is overwritten and the data in the file
are lost. After calling fopen, the file is ready for data writing. Any attempt to read
data will result in a segmentation error.

- "a": add mode. The file is not overwritten, but is ready to be written after the
existing data. Any attempt to read the file will result in a segmentation error.

- "r+": read-write mode. The file is ready for reading and writing at the beginning of
the file. The file is not overwritten.
• "w+": read-write mode. The file is overwritten.
- "a+": read-write mode. The file is not overwritten, but is ready to be written after
the existing data.

80

www.biblio-scientifique.net
10.3. Read and write formatted data

The last three modes (read-write) are not often used for text files, but we'll see in
another chapter how to use them in binary files.
The fopen function returns the NULL pointer in the event of a file opening error
(non-existent file, filename error, or insufficient read or write permissions to access
the file at system level). The NULL pointer is often used as an error code for
functions returning a pointer.
After using a file, you need to close it using fclose. The function
fclose takes the file pointer as parameter and closes the file.

If you forget to call fclose, some data may not be transferred between the file and
main memory (this is due to the existence of a buffer, where data is temporarily
stored until it is finally transferred; calling fclose causes the buffer to be
transferred).

10.3 R EAD AND WRITE FORMATTED DATA


10.3.1 Read formatted data
To read a file, it must first be opened in "r" mode, "r+", "w+", or "a+".
To read numerical or other data from a text file, you can use the fscanf function,
which is similar to scanf except that it reads from a file instead of from the
keyboard. The fscanf function takes the file pointer as its first parameter, then the
other parameters are the same as those for scanf (the format string with %d,%f,...,
then the variable addresses with &). The fscanf function returns the number of
variables actually read, which may be less than the number of variables requested
to be read in the event of an error or the end of the file. This can be used to detect
end-of-file or read errors in in if or while.
Dunod. Unauthorized photocopying is an offence.

Example
Loading an integer file into main memory.
We assume that a text file contains whole numbers separated by spaces:
10 2 35 752 -5 4 -52 etc.

We'll load these integers into main memory (i.e., put them in an array), then
display the array.

81

www.biblio-scientifique.net
Chapter 10 - Text files

#include <stdio.h>
#include <stdlib.h> /* to use the exit function */

#define NB_ELEM_MAX 100

int LoadFile(int array[NB_ELEM_MAX])


{
FILE *fp;
int i=0;
/* open file : */
fp = fopen("myfile.txt", "rt"); if
(fp ==NULL) /* error handling */
{
puts("File open error:");
puts("File does not exist or insufficient permissions");
exit(1); /* terminates program with error code */
}
/* you can include function calls such as fscanf in a condition.
Here, fscanf returns 1 on success */
while (i < NB_ELEM_MAX && fscanf(fp, "%d", &tableau[i])==1)
i++; /* increment: same as i=i+1 */
fclose(fp); /* close file */
return i; /* returns the number of elements read */
}

void Affiche(int tableau[], int n)


{
int i;
for (i=0; i<n; i++)
printf("array[%d] = %d\n", i, array[i]);
}

int main()
{
int tab[NB_ELEM_MAX];
int n;
n = LoadFile(tab); Display(tab,
n);
return 0;
}

The exit function in the stdlib.h library terminates the program at the point
where it is called (possibly with an error code passed as a parameter which is passed
to the system). This should not be confused with return, which exits the current
function but does not terminate the program (unless the function in

82

www.biblio-scientifique.net
10.3. Read and write formatted data

course is main). In main, a return is equivalent to an exit: it terminates the program.


In a function other than main, the return passes execution of the program to the
function that called the current function (e.g. main), just after the current function has
been called, but execution of the program continues.
Note the condition in the while that tests the value returned by fscanf. In this
example, a single value is requested from fscanf. The fscanf function must return 1
if successful. At the end of the file, fscanf fails to read the value, and the fscanf
function returns a value other than 1. We then exit the while without incrementing i.
As fscanf is called, the elements of the array are read from the file. At the end,
variable i contains the number of elements that have been read from the file. The
while condition also checks that the physical size of the array is not exceeded. This is
a safety feature that prevents a segmentation error if the file is longer than the
programmer intended.

Supplements
,
In the while test in the previous example, i < NB_ELEM_MAXI is tested before
fscanf reads it. This is essential, as the ANSI standard specifies that the
conditions in an && conjunction are tested in order from left to right. If the first
condition is false, the second condition is not tested, thus avoiding an array
overflow memory error in fscanf.

Finally, each time fscanf is read, the file pointer moves on to the next file. The
pointer automatically advances in the file when a read is made, without the need to
increment a variable.
Note
The file could have been organized differently, with a first line containing the
number of elements to be read and transferred to the array. The second line would
contain the elements separated by spaces. For example, :

6
Dunod. Unauthorized photocopying is an offence.

10 2 35 752 -5 4
In this case, we first fscanf to read the number of elements n in the file, then we can
do a classic for loop, with stop condition i<n to read the elements with fscanf.

The way data is organized in a file is called the ƒfile format. The designer of a
program that uses files must think about and specify exactly what data is in the file
and in what order that data is found before writing his program. Sometimes, the file
format is

83

www.biblio-scientifique.net
Chapter 10 - Text files

imposed because it may be a standard used by other programs and software.


10.3.2 Writing formatted data
To write to a file, it must first be opened in
"w", "a", "r+", "w+" or "a+".
To write numerical or other data to a text file, use the fprintf function, which is
analogous to the printf function. The fprintf function takes a file pointer as its first
parameter. The second parameter is the format string with the text to be written and
%d,%f, followed by the variables to be written, separated by commas.
Example
Here's a program that reads a text file containing integers, and writes a text file
containing triple integers (each integer is multiplied by 3).

#include <stdio.h>

int TripleFile(void)
{
FILE *fpr, *fpw; /* two pointers for two files */
int n; /* to read */

fpr = fopen("readfile.txt", "rt"); fpw =


fopen("writefile.txt", "wt");
if (fpr==NULL || fpw==NULL) /* error handling */
return 1; /* error code returned to main */
while (fscanf(fpr, "%d", &n)==1) /* read an integer */
fprintf(fpw, "%d ", 3*n); /* write the triple */
fclose(fpr); /* close both files */ fclose(fpw);
return 0; /* no error */
}
int main()
{
int codeErr;
codeErr = TripleFile();
/* the error code is retrieved from main : */
if(codeErr != 0)
puts("File open error!"); return 0;
}

84

www.biblio-scientifique.net
Exercises

Supplements
,
The feof function, which takes the file pointer as parameter, returns true if
the end of the file has been exceeded. This allows you to test the end of the
file, but is not always convenient, as you need to pass a failed read for
feof to return true.

Exercises

10.1 (∗) A statistical series gives, for each weight: 1kg, 2kg, 3kg,..., 200kg, the
number of people in the population weighing that weight. This data is stored in a file.
The ith line of the file contains the number of people weighing ikg.
n1
n2
etc.
n200

a) Write a program that loads this data into main memory and calculates the average
weight in the population.
b) Write a program that calculates the average weight in the population without
loading data into memory.

10.2 (∗) Write a function that saves an array of floats passed as parameters.
10.3 (∗∗
) A file contains item code and price descriptions. The item code is a number
between 0 and 99. Each line of the file contains a code and a price separated by a
space:
code1
price1
Dunod. Unauthorized photocopying is an offence.

code2
price2
etc.
We propose to organize the data in main memory in the form of tables: we find the
price of each product with code c in the cell with index c in the table.
a) Propose a data structure to represent products in main memory.

b) Write a function to load data into main memory.


c) Write a function that gives the price of a product from its code.

85

www.biblio-scientifique.net
Chapter 10 - Text files

d) Write a function that allows a user to enter a new product into the database. It will
be assumed that the database has already been loaded into memory.

e) Write a function to save the database to a file.

f) Write the main program that loads the data and, for as long as the user wishes,
offers a menu with three options:
• Add a product
• Consult a price
• Exit
At the end of the program, the data will be saved.

Answers

10.1
#define file "weight.txt
#define NB_ELEM_MAXI 200
a)
int main()
{
FILE *fp;
int t[NB_ELEM_MAXI], i, sum;
fp = fopen(fichier, "rt");
if (fp == NULL)
{
printf("Reading error file"); return -1;
}
i = 0;
while (fscanf(fp, "%d", &t[i]) == 1)
i++;
fclose(fp);
sum = 0; i-
-;
while (i >= 0)

86

www.biblio-scientifique.net
Answers

{
sum += t[i];
i--;
}
printf("Average = %f\n", sum / (float) NB_ELEM_MAXI);
return 0;
}

b)
int main()
{
FILE *fp;
int t, n, sum;
fp = fopen(file, "rt"); if
(fp == NULL)
{
printf("Reading error file"); return -1;
}
n = 0;
sum = 0;
while (fscanf(fp, "%d", &t) == 1)
{
sum += t;
n++;
}
fclose(fp);
printf("Average = %f\n", sum / (float) n);
return 0;
}

10.2
#define file "float.txt"
void sauveFloat(float t[], int size)
Dunod. Unauthorized photocopying is an offence.

{
FILE *fp;
int i;
fp = fopen(file, "wt"); if
(fp == NULL)
{
printf("File creation error");
}

87

www.biblio-scientifique.net
Chapter 10 - Text files

else
{
for (i = 0; i < size; i++) fprintf(fp,
"%f\n", t[i]);
fclose(fp);
}
}

10.3
#define file "product.txt
#define NB_ELEM_MAXI 100
a)
typedef struct product
{
float price[NB_ELEM_MAXI];
/* valid[.] = 1 if the product exists */
char valide[NB_ELEM_MAXI];
} Product;
b)
Product load()
{
FILE *fp;
int i, code;
float price;
Basic product;
fp = fopen(file, "rt");
for (i = 0; i < NB_ELEM_MAXI; i++)
base.valid[i] = 0;
if (fp == NULL)
{
printf("Error reading file");
}
else
{
while (fscanf(fp, "%d %f", &code, &prix) == 2)
{
base.valid[code] = 1;
base.price[code] = price;
}
fclose(fp);
}
return base;
}

88

www.biblio-scientifique.net
Answers

c)
float price(Product base, int code)
{
if (base.valid[code] == 1)
return base.price[code];
/* price unknown */
return -1.0;
}

d)
Product addition(Product base)
{
int code;
float price;
printf("Enter a code and a price: ");
scanf("%d %f", &code, &prix);
base.valid[code] = 1;
base.price[code] =
price; return base;
}

e)
void save(Product base)
{
FILE *fp;
int i;
fp = fopen(file, "wt"); if
(fp == NULL)
{
printf("File creation error");
}
else
{
for (i = 0; i < NB_ELEM_MAXI; i++)
Dunod. Unauthorized photocopying is an offence.

{
if (base.valid[i] == 1)
fprintf(fp, "%d %f\n", i, base.price[i]);
}
fclose(fp);
}
}

89
Chapter 10 - Text files

f)
int main()
{
int code; char
c = '0'; float
p;
Product base = load(); while (c
!= '3')
{
printf("Do you want to :\n");
printf("1- Add a product");
printf("2- Consult a price");
printf("3- Quit");
c = '0';
while (c != '1' && c != '2' && c != '3')
c = getchar();
switch (c)
{
box '1':
base = ajout(base);
break;
case '2':
printf("code ? ");
scanf("%d", &code); p
= price(base, code);
if (p < 0)
printf("Product unknown");
else
printf("The price of the product with code %d is : %.2f\n",
code, price(base, code));
break;
default:
break;
}
}
save(base);
return 0;
}

90
A DDRESSE
S,
11
POINTERS
AND
PASSAGE
BY ADDRESS

11.1 M AIN MEMORY AND ADDRESSES


A computer's main memory is made up of a very large number of bytes. Each byte is
identified by a number called the byte address.

addresses bits
byte 0 NULL
byte 1
byte 2

etc.

byte 2n - 2
byte 2n - 1

Each variable in memory occupies contiguous bytes, i.e. bytes that follow one
another. For example, a float occupies 4 consecutive bytes. The variable's address is
the address of its first byte. You can find out the address of a variable using the &
operator.

&x /* address of variable x : address of its first byte */


thorized photocopying is an offence.

11.2 P OINTER VARIABLES


The address of a variable can itself be stored in a variable. Variables whose values
are addresses are called pointers. A pointer to int is declared by type int*, a
pointer to float by type float*, and so on.
Here's an example using a pointer p that takes the address of x as its value (p is
said to point to x, see figure 11.1).

91
Chapter 11 - Addresses, pointers and address passing

zone m'emoire de x: 010011010...


p
Figure 11.1- The pointer p points to the variable x

#include <stdio.h>

int main(void)
{
int x = 2; /* declaration of variable x */
int *p; /* declaration of a pointer p */
p = &x; /* p points to x */
/* the value of p is the address of x */
scanf("%d", p); /* read value of x from keyboard */ printf("%d",
x); /* display new value of x */ return 0;
}

The data pointed to by a pointer (the value of x in the previous example) is accessed by
a star.

*p = 3; /* the object pointed to by p takes the value 3 */

Don't confuse the use of the star when declaring a pointer variable with the use of
the star to access the object pointed to by the pointer.

Don't confuse the value of a pointer p, which is an address, with the value of the
object pointed to by p, which is generally not an address, e.g. an int in the case
of an int* pointer.

#include <stdio.h>

int main(void)
{
int x = 2;
int *p = &x; /* x and *p become synonyms */
*p = 3;
printf("The new value of x is %d\n", x);
/* must display the value 3 */
return 0;
}

92
11.3 Passing parameters by value

#include <stdio.h>

int main(void)
{
int x = 2;
int *p = &x; /* x and *p become synonyms */ printf("The
value of x is %d\n", *p); /* display 2 */ x = 5;
printf("The new value of x is %d\n", *p);
/* must display the value 5 */
return 0;
}

In short, when p points to x, the value of p is the address of x, any modification of


*p modifies x and any modification of x modifies *p. The reason for this is that *p
and x are in the same memory location in RAM.

11.3 P ASSING PARAMETERS BY VALUE


When a parameter is passed to a function, the function cannot modify the variable.
The variable is automatically copied and the function works on a copy of the
variable. Modifying the copy does not modify the original variable. This is
parameter-by-value passing.

#include <stdio.h>

void Don'tChange(int x)
{
x = x+1; /* the local x is modified, not the main x */
}

int main(void)
{
int x=1;
Dunod. Unauthorized photocopying is an offence.

NeModifiePas(x);
printf("%d", x); /* display 1: value of x unchanged */
return 0;
}

11.4 A DDRESS - BASED PARAMETER PASSING


The idea behind address passing is that, in order to modify a variable with a function
call, you need to pass not the variable, but a pointer to it, as a parameter.

93
Chapter 11 - Addresses, pointers and address passing

on the variable. Thus, the parameter is the address of x. When we modify the
memory at this address, the data x is modified, as we are working on x's memory
location (see figure 11.2).

copy of p
zone m'emoire de x: 010011010...
p
Figure 11.2 - The pointer p and its copy both point to the variable x in main

#include <stdio.h>

/* the following function takes a pointer as parameter */


void Modifie(int *p)
{
*p = *p+1; /* p points to x, so does the copy of p */
/* the x in main is modified */
}

int main(void)
{
int x=1; /* varible x is not a pointer */
int *p;
p = &x; /* pointer to x */
Modify(p);
printf("%d", x); /* display 2 */
return 0;
}

When the Modify function is called, pointer p is copied, and the Modify function
works on a copy of pointer p. However, pointers p and its copy contain the same
value, which is the address of x. When we modify the object at this address, we
modify x.
The explicit use of a pointer in main is superfluous, as the address of x can be
passed directly to the function, without the need to define a pointer variable in main.

#include <stdio.h>

void Modifie(int *p) /* pointer parameter */


{
*p = *p+1; /* this pointer p has the value &x (x from main) */

94
Exercises

int main(void)
{
int x=1;
Modifie(&x); /* directly passes x's address */
printf("%d", x); /* display 2 */
return 0;
}

It's in this latter form that we generally use the address gateway.

Example
The scanf function, which reads variables from the keyboard, must modify the
contents of these variables. For this reason, variables are passed to scanf by
address, which explains the need for & in front of variables.

Before using the object pointed to by a p pointer, we must ensure that the p
pointer contains the address of a correct memory location (the address of a
variable or a dynamically allocated memory block, as discussed in the next
chapter). If you declare a pointer p without making it point to a correct memory
location, any access to *p will produce either a false result or a memory error
(segmentation error).

Exercises

11.1 (∗) Write a function that initializes two integers and a real to 0. Write the main
program that calls this function.

11.2 (∗) Write a function that returns the quotient and remainder of dividing an
integer p by an integer q. Write the main program that calls this function and
displays the results.
Dunod. Unauthorized photocopying is an offence.

11.3 (∗∗)
a) Write a program that enters two variables of type int, exchanges their contents
and displays the new values of the variables.
b) We propose to repeat question a) by exchanging values within a function. Write a
function that exchanges the contents of two variables passed by address. Write the
main program that enters two variables, exchanges them by calling the function and
displays the new contents of the variables.

95
Chapter 11 - Addresses, pointers and address passing

11.4 (∗) Write a function that initializes all values in an array to 0. Write the main
program that declares the array, calls the function and displays the ele-
ments in the table.

11.5 (∗) Write a function that calculates the sum and product of the elements of an
array passed as a parameter. Write the main program that initializes the array with
input; calculates and displays sum and product of elements.

Supplements
,
For the next exercise, we need to use pointers to a structure. If p is a pointer
to a structure containing a float field x, then (*p) is a structure, and
(*p).x is a float. To simplify writing, we can use the notation p->x instead
of (*p).x to designate the field x of the structure pointed to by p.

11.6 (∗∗) Let a Point structure contain two fields x and y of type float.

a) Write a function that exchanges two Point structures passed by address.

b) Write the main program that enters two Point structures into variables,
exchanges the contents of these variables by calling the function, and displays the
new contents of the variables.

Answers

11.1
void fill(int *a, int *b, float *x)
{
*a = 0;
*b = 0;
*x = 0.0;
}
int main()
{
int u, v;
float t;
fill(&u, &v, &t); return
0;
}

96
Answers

11.2
void divise(int p, int q, int *quotient, int *rest)
{
*remain = p % q;
*quotient = p / q;
}
int main()
{
int a, b;
divide(17, 3, &a, &b);
printf("17 = %d * 3 + %d\n", a,
b); return 0;
}

11.3
a)
int main()
{
int a = 14, b = 5;
int t;
printf("a = %d; b = %d\n", a,
b); t = a;
a = b;
b = t;
printf("a = %d; b = %d\n", a, b);
return 0;
}
b)
void echange(int *a, int *b)
{
int t; t
= *a;
*a = b;
Dunod. Unauthorized photocopying is an offence.

*b = t;
}
int main()
{
int a = 14, b = 5;
printf("a = %d; b = %d\n", a, b);
echange(&a, &b);
printf("a = %d; b = %d\n", a, b);
return 0;
}

97
Chapter 11 - Addresses, pointers and address passing

11.4
#define NB_ELEM_MAXI 100
void raz(int *t, int size)
{
int i;
for (i = 0; i < size; i++) t[i]
= 0;
}
int main()
{
int tab[NB_ELEM_MAXI];
int i;
for (i = 0; i < NB_ELEM_MAXI; i++)
printf("tab[%d] = %d\n", i, tab[i]);
raz(tab, NB_ELEM_MAXI);
for (i = 0; i < NB_ELEM_MAXI; i++)
printf("tab[%d] = %d\n", i, tab[i]);
return 0;
}

11.5
#define NB_ELEM_MAXI 100
void calcul(int t[], int size, int *sum, int *product)
{
int i;
*sum = 0;
*product = 1;
for (i = 0; i < size; i++)
{
*sum += t[i];
*product *= t[i];
}
}
int main()
{
int tab[NB_ELEM_MAXI];
int s, p, size=-1, i;
while (size < 0 || size > NB_ELEM_MAXI)
{
printf("Enter number of elements: ");
scanf("%d", &size);
}
puts("Please enter the table elements");

98
Answers

for (i=0; i<size; i++) scanf("%d",


&tab[i]);
calculation(tab, size, &s, &p);
printf("sum = %d and product = %d\n", s, p);
return 0;
}

11.6
typedef struct point
{
float x, y;
} Point;
a)
void echange(Point * a, Point * b)
{
Point t;
t.x = a->x;
t.y = a->y;
a->x = b->x;
a->y = b->y;
b->x = t.x;
b->y = t.y;
}
b)
int main()
{
Point M, N;
printf("Coordinates of first point?");
scanf("%f %f", &M.x, &M.y);
printf("Coordinates of second point?");
scanf("%f %f", &N.x, &N.y);
echange(&M, &N);
printf("M(%f,%f) and N(%f,%f)n", M.x, M.y, N.x, N.y);
Dunod. Unauthorized photocopying is an offence.

return 0;
}

99
D YNAMIC
ALLOCATION
12
12.1 M AIN MEMORY MANAGEMENT
Until now, the number of elements in an array was limited by a constant (usually
defined in a #define). In this section, we'll look at how to create an array during the
program, the size of which can be given by a variable, resulting from a calculation or
entered by the user. The tool for doing this is dynamic memory allocation. This
technique makes it possible to create arrays whose memory size varies according to
need, and to free this memory after use. The result is programs that are more perfor-
mant in terms of memory consumption.
In general, several programs or software packages run simultaneously on the same
computer. For example, a console, a text editor, a word processor, a compiler, etc.
may be running simultaneously. This is known as multitasking. All these programs
have their own data in memory (variables, arrays, etc.), but the programs generally
share the same hardware, and in particular the same memory slots. The system must
allocate memory to the different programs, without any conflicts. In particular, one
program cannot write to another's variables; this causes a memory error, or
segmentation error.
To create an array during program execution, a memory location must be reserved
in main memory. The programmer specifies the size of the memory location (roughly
the number of bytes), and when the program is executed, the system reserves a
memory location and gives the address of this location. This operation is called
dynamic memory allocation. The allocation functions in C are malloc and calloc.
Dynamic allocation is used because memory is allocated as and when required, as
opposed to the static array allocation studied in Chapter 9.
Dunod. Unauthorized photocopying is an offence.

12.2 A LLOCATION WITH malloc


The malloc function allocates a certain number o f bytes, i.e. it reserves bytes for use
by the program. The number of bytes is passed to the malloc function as a parameter.
The malloc function returns the address of the first byte reserved. This address is
stored in a pointer. To calculate the total number of bytes required for an array, use
the sizeof function, which gives the number of bytes required.

101
Chapter 12 - Dynamic allocation

bytes required for a variable of type float, int, char, etc. and multiply by the
number of elements in the array.
Once memory has been used, it must be freed using the free function. This
function takes the address of the memory block to be freed as a parameter. When free
is called, the memory is returned to the system, which can reuse it for another
purpose.

Example
In the following program, the ReturnArray function reads the number of elements in
an array, reserves memory space for floats accordingly, reads the array elements
from the keyboard and returns the array address. The number of array elements is
passed by address to main. Note that the number of elements in the array is given
here by a variable, not a constant.

#include <stdio.h>
#include <stdlib.h> /* to use malloc */

/* function returning a pointer of type float* */


float* ReturnTable(int *addrNumberElements)
{
int n, i;
float *tab; /* array address (pointer type) */
printf("Enter array size: "); scanf("%d", &n);
*addrNumberElements = n; /* pass by address, return n */
/* tab = (float*)malloc(n*sizeof(float)); /* allocation
*/ puts("Enter array elements:");
for (i=0 ; i<n ; i++)
scanf("%f", &tab[i]);
return tab; /* return array address */
}

void Affichage(float *tab, int nb) /* display a tab array */


{
int i;
for (i=0; i<nb; i++)
printf("tab[%d] = %f\n", i, tab[i]);
}

int main(void)
{
int nb;

102
12.3. Allocation with calloc

float *tab;
tab = ReturnTable(&nb);
/* retrieve array address from tab */
Display(tab, nb);
free(tab) /* mandatory memory release */
return 0;
}

The malloc function, which allocates memory, returns the address of the
allocated memory location. This address can be stored in a variable that can hold
addresses: a pointer variable. In this representation, an array is always given by a
pointer variable containing the address of the array's first element. Array elements
are accessed in the same way as any other array: using square brackets [ ] .
Note that, unlike static arrays, which you pass as parameters to functions to modify
their elements, you can return an array allocated dynamically by a return. The
function simply returns the value of a pointer (type float* in the example).
Note the passage by address, which allows the RentrerTableau function to trans-
hand both the array and its number of elements. An alternative would be to place the
array (as a pointer) and its number of elements in the same structure, and return the
structure.

12.3 A LLOCATION WITH calloc


The calloc function, like the malloc function, allocates a memory location and
returns the address of the first byte. The syntax of the two functions differs slightly.
The calloc function takes two parameters, the number of elements and the number of
bytes in each element. Unlike malloc, calloc initializes all bytes to 0.
Example
Dunod. Unauthorized photocopying is an offence.

In the following example, we allocate an array whose elements are all null
except those entered by the user.

#include <stdio.h>
#include <stdlib.h> /* to use calloc */

float* RentrerTableauBis(int *addrNbreElements)


{
int i, n;
char choix;

103
Chapter 12 - Dynamic allocation

float *tab; /* array address */


printf("Enter array size: ");
scanf("%d", &n);
*addrNumberElements = n; /* pass by address */
/* tab = (float*)calloc(n, sizeof(float)); /*
allocation */ puts("Enter the non-zero elements of the
array:"); choice = 'y';
while (choice=='y')
{
puts("Enter the index i of the element to be
entered"); scanf("%d", &i);
puts("Enter element tab[i]");
scanf("%f", &tab[i]);
getchar(); /* to eat the carriage return */ puts("Is
there another non-zero element? (y/n)"); choice =
getchar();
}
return tab; /* return array address */
}

void Affichage(float *tab, int nb)


{
int i;
for (i=0; i<nb; i++)
printf("tab[%d] = %f\n", i, tab[i]);
}

int main(void)
{
int nb;
float *tab;
tab = RentrerTableauBis(&nb);
Affichage(tab, nb);
free(tab) /* mandatory memory release */
return 0;
}

Supplements

,
Static arrays, like dynamic arrays, are represented by the address of their first
element. When a static array is declared in a function, the memory is local to
the function and is destroyed when the program exits the function. In
particular, such an array cannot be returned (the memory is destroyed). On
the other hand, the memory of an allocated array

104
Exercises

is dynamically maintained until released "manually" by a call to free.


,
Both types of memory, static and dynamic, are not stored in the
the same area of RAM. Static memory, including function variables, is stored in
a stack (called a call stack). Dynamic memory is stored in a heap. The stack and
heap are managed very differently by the system. Generally speaking, in the
default system settings, the stack is small, while the heap allows you to
allocate much more memory.

Exercises

12.1 (∗) Write a function that reads an integer n from the keyboard, allocates an array of n
integers initialized to 0, and returns n and the array.

12.2 (∗) A function is proposed to load a text file into main memory as an array of
floats. The file format is as follows:
• the first line of the file contains the number of elements in the array ;
• the following lines each contain a real number.
n
f_1
f_2
...
f_n

a) Create a load function in an array whose memory size corresponds exactly to the
number of elements in the file.
b) Create a displayboard function.
c) Write the main program that loads the file and displays the table.
Dunod. Unauthorized photocopying is an offence.

12.3 (∗) Let un be defined by :


u0 = 1 and un+1 = 3un2 + 2un + 1

a) Write a function that takes an integer n as parameter and returns an array


containing the first n terms of the sequence un . The function must work regardless of
the integer n entered.

b) Write the main program that enters the integer n and displays the first n terms of
the sequence un using the function defined in a).

105
Chapter 12 - Dynamic allocation

12.4 (∗∗) Consider the following TypeTableau structure, which contains the
address of an array and the number of elements in the array.
typedef struct{
int nb_elem; /* number of elements */
int *tab; /* array */
}TypeTable;

a) Write a prototype function


TypeTableau CreationTableau(int n);
which creates an array of n elements.

b) Writing a prototype function


void DestructionTableau(TypeTableau T);
which frees the memory occupied by an array.

c) Writing a prototype function


void SimpleReadingTable(TypeTable T);
which reads the elements of an array from the keyboard. This function assumes that
the array has already been allocated.

d) Write a prototype function void


Affichage(TypeTableau T); which
displays the contents of an array.

e) Writing a prototype function


TypeTableau DoubleTableau(TypeTableau T);
which creates a new array of the same size as T, but whose elements are double the
elements of T.

f) Write a main program that enters an array from the keyboard, calculates the double
of each element in the array and displays the results.

106
Answers

Answers

12.1
int *zero(int *n)
{
int *t = NULL;
printf("Enter size: ");
scanf("%d", n);
if (*n > 0)
{
t = calloc(*n, sizeof(int));
}
return t;
}

12.2
#define file "donnees.dat"
a)
float *charge(FILE * fpr, int *n)
{
float *t = NULL;
int i = 0; fscanf(fpr,
"%d", n); if (*n >
0)
{
t = calloc(*n, sizeof(float));
while (fscanf(fpr, "%f", &t[i]) == 1)
i++;
}
return t;
}
Dunod. Unauthorized photocopying is an offence.

b)
void affiche(float *t, int n)
{
int i;
for (i = 0; i < n; i++)
printf("t[%d] = %f\n", i, t[i]);
}

107
Chapter 12 - Dynamic allocation

c)
int main()
{
float *t;
int n;
FILE *fp;
fp = fopen(file, "rt"); if
(fp == NULL)
{
printf("Reading error"); return
-1;
}
t = load(fp, &n);
display(t, n);
return 0;
}

12.3
a)
unsigned int *suite(unsigned int n)
{
unsigned int *un = NULL;
unsigned int i;
if (n <= 0)
return one;
un = calloc(n, sizeof(unsigned int));
if (un != NULL)
{
un[0] = 1;
i = 1;
while (i < n)
{
un[i] = 3 * un[i - 1] * un[i - 1] + 2 * un[i] + 1;
i++;
}
}
return one;
}
b)
int main()
{
unsigned int n;
unsigned int *u;

108
Answers

unsigned int i;
printf("Number of terms ? ");
scanf("%u", &n);
u = suite(n);
if (u == NULL)
return -1;
i = 0;
while (i < n)
{
printf("u_%u = %u\n", i,
u[i]); i++;
}
return 0;
}

12.4
typedef struct
{
int nb_elem;
int *tab;
} TypeTable;
#define N 5
a)
TypeTable CreationTable(int n)
{
TypeTable t;
t.nb_elem = 0;
t.tab = NULL;
if (n > 0)
{
t.tab = calloc(n, sizeof(int));
if (t.tab != NULL)
t.nb_elem = n;
}
Dunod. Unauthorized photocopying is an offence.

return t;
}

109
Chapter 12 - Dynamic allocation

b)
void DestructionTable(TypeTable T)
{
if (T.nb_elem > 0)
{
free(T.tab);
T.nb_elem=0;
}
}
c)
void SimpleReadingTable(TypeTable T)
{
int i;
for (i = 0; i < T.nb_elem; i++)
{
printf("T[%d] = ? ", i);
scanf("%d", &(T.tab[i]));
}
}
d)
void Affichage(TypeTableau T)
{
int i;
for (i = 0; i < T.nb_elem; i++)
{
printf("T[%d] = %d\n", i, T.tab[i]);
}
}
e)
TypeTable DoubleTable(TypeTable T)
{
TypeTableau TT = CreationTableau(T.nb_elem);
int i;
for (i = 0; i < T.nb_elem; i++)
{
TT.tab[i] = 2 * T.tab[i];
}
return TT;
}

110
Answers

f)
int main()
{
TypeTable Ta, TaTa;
Ta = CreationTable(N);
SimpleReadTable(Ta); TaTa
= DoubleTable(Ta);
Display(TaTa);
DestroyTable(Ta);
DestroyTable(TaTa); return
0;
}
Dunod. Unauthorized photocopying is an offence.

111
TER STRINGS
CHARAC
13
13.1 W HAT IS A CHARACTER
STRING?

A character string is an array of characters ending with the special character '\0'
(which has an ASCII code of 0).
'e' 'x' 'e' 'm' 'p' 'l' 'e' '\0'

The ' 0' character


\ is used to mark the end of the string, avoiding the need to
know the number of characters in the string. In this way, you can pass a string of
characters as a parameter to a function, without needing to pass a second
parameter containing the number of characters.
You can declare a string like any other array, but with a place for the final '\0':

/* ******* static allocation version ******** */

char string[100];

/* ****** dynamic allocation version ******** */

char *chaine; /* don't forget allocation */


int n = 100; /* variable n */
string = (char*)calloc(n, sizeof(char)); /* allocation */

Example
Dunod. Unauthorized photocopying is an offence.

The following program shows a function that calculates the length of a string, i.e.
its number of characters excluding the '\0'.

#include <stdio.h>

int length(char* string)


{
int i;
/* we test the end of the string with the '\0'*/
for (i=0; string[i] != '\0'; i++)

113
Chapter 13 - Character strings

{} /* empty instruction b l o c k */
return i;
}
int main(void)
{
char string[101];
int long;
puts("Please enter a string (maximum 100 characters)");
puts("without spaces"); /* s c a n f stops at the first space */
scanf("%s", string); /* read string. no & */ long =
length(string);
printf("String length = %d", long);
}

We don't use & in scanf to read a character string. This is because a string is
already an address, and there's no need in scanf to pass the address of the
pointer containing the address of the memory block.

There are also string constants. These are made up of characters enclosed in
quotation marks.

#define MA_CHAINE "this is a constant of type string".


...
puts(MA_CHAINE); /* display string */

Don't mix string constants (type char*), which are enclosed in double quotes, and
character constants (type char), which are enclosed in single quotes like 'Z'.

13.2 P REDEFINED STRING OPERATIONS


13.2.1 <stdio.h> functions
a) Reading
The %s format of scanf and fscanf is used to read a character string from the
keyboard or a text file. The string ends as soon as a space or '\n' is
encountered.
Example 1
#include <stdio.h>
int main(void)
{
char string[100]; puts("Please
enter a word");

114
13.2 Predefined chain operations

scanf("%s", string);
printf("You have entered %s",
string); return 0;
}

The fgets function reads an entire line from a text file. The string read may
contain spaces. The read string ends with an '\n', which must be removed by hand if
it is unwanted. The prototype of the fgets function is :

char *fgets(char* s, int n, FILE *fp);

The function reads all characters up to the next 'n', but reads at most n-1
characters. The characters read are put into s, including the\'n'. Parameter n is used
to avoid a memory error if the line read is too long for the allocated array. If no 'n' is
encountered, the function sets a '0' without reading the rest. You must have
previously allocated (statically or dynamically) the string s with at least n
characters. The fgets function returns the string s.
If you pass the standard file pointer stdin as the third parameter, reading is done
from the keyboard and not from a file.

Supplements
,
All functions for reading or writing text in files can be used to read or write
from the keyboard. All you need to do is use the flot with standard input stdin
and standard output stdout as a file pointer (of type FILE*). This hints at the
fact that the FILE* type applies to more than just files. It's the notion of flot,
which makes it possible to manage all input and output in C.

Example 2
Dunod. Unauthorized photocopying is an offence.

#include <stdio.h>
int main(void)
{
char string[100];
puts("Please enter a line, then press enter"); fgets(string,
100, stdin);
printf("You have entered %s",
string); return 0;
}

115
Chapter 13 - Character strings

Example 3
#include <stdio.h>
int main(void)
{
char string[500], filename[100];
FILE *fp;
puts("Please enter a filename without spaces");
scanf("%s", filename);
if ((fp = fopen(filename, "rt")) == NULL)
puts("Error: file does not exist or insufficient rights");
else
{
fgets(string, 500, fp); /* read a line */
printf("The first line of the file is %s", string);
}
return 0;
}

b) Writing
The %s format of printf and fprintf allows you t o write a character string on
screen or in a text file. (See Example 1.)
The puts function displays a string followed by an '\n'.
Example 4
#include <stdio.h>

int main(void)
{
char string[100]; puts("Please
enter a word"); scanf("%s",
string); printf("You have
entered: ")
puts(string); /* no quotes: variable */
return 0;
}

You don't use quotation marks in the puts function to display the contents of a
char* variable. A puts("string") statement would display the word "string", not
the contents of the variable string, which would be another word or phrase.

The fputs function is used to write a character string to a text file.


The prototype of this function is :
char *fputs(char* s, FILE* fp);

The function returns EOF on error.

116
13.2 Predefined chain operations

13.2.2 The <string.h> library


The string.h library contains functions for processing character strings. Here are
just a few examples of string.h functions.
The strcpy function copies one string into another. It's the equivalent of a
assignment for strings. The prototype of the strcpy function is as follows:

char* strcpy(char* destin, char*source);

The function copies the source string to the destination string. The destin
string must have been allocated beforehand. The function returns destin.

When making an assignment :

char s1[50], *s2;

strcpy(s1, "This is a string"); s2

= s1; /* assignment */

string s1 is not copied, and the two strings s1 and s2 point to the same memory area
(address assignment). Subsequently, any modification of the characters in s1 leads to
a modification of s2 and vice versa. To copy the string s1, use strcpy(s2,s1).

The strcat function concatenates two strings, i.e. it places them end-to-end one after
the other in the same string. The prototype is :

char* strcat(char* s1, char* s2);

The function copies s2 after s1 The result is in s1. The string s1 must have been
allocated with sufficient memory to contain the result. The function returns s1.
Example 5
Dunod. Unauthorized photocopying is an offence.

#include <stdio.h>
#include <string.h>

int main(void)
{
char string[100], word1[50], word2[51]; puts("Please
enter a word (maximum 49 letters)"); scanf("%s",
word1);
puts("Please enter another word (maximum 50 letters)");

117
Chapter 13 - Character strings

scanf("%s", mot2);
strcpy(string, word1); /* copy word1 into string */
strcat(string, word2); /* put word2 next */ printf("The
two words entered are %s", string);
return 0;
}

The strcmp function compares two strings in alphabetical order. The prototype is :

int strcmp(char* s1, char *s2);

The result is < 0 if s1 < s2, equal to 0 if the characters in s1 are the same as the
characters in s2, and it is > 0 if s1 > s2.

The cs==ct test is a comparison of addresses, not an alphabetical comparison.

Example 6
#include <stdio.h>
#include <string.h>
int main(void)
{
char mot1[50], mot2[50];
puts("Please enter a word (maximum 49 letters)");
scanf("%s", word1);
puts("Please enter another word (maximum 49 letters)");
scanf("%s", word2);
if (strcmp(mot1, mot2)==0)
puts("both words are equal"); if
(strcmp(word1, word2) < 0)
printf("%s comes before %s in alphabetical order",
word1, word2);
if (strcmp(mot1, mot2) > 0)
printf("%s comes after %s in alphabetical order",
word1, word2);
return 0;
}
The strlen function returns the length of a string, i.e. its number of characters
(excluding the '0'). This function takes the string
\ as a parameter.

size_t strlen(char* s);

The size_t type is an integer type used to store byte numbers.

118
13.2 Predefined chain operations

Example 7
The following function reads a line from the keyboard and deletes theJ \nJ at the
end of the string.
void SaisieLigne(char string[502])
{
puts("Please enter a line of no more than 500 characters");
fgets(string, 502, stdin);
/* Replace the '\n' (last character) with a '\0'*/
string[strlen(string)-1] = '\0';
}

Example 8
The following function returns an allocated string with just enough memory space
for the string entered from the keyboard.
/* Allocation o f a string just the right size */

char* SaisieChaine(void )
{
char string[1000];
char *economy;
puts("Please enter one line (maximum 999 letters)");
fgets(string, 1000, stdin);
econome = (char *)calloc((strlen(string)+1)*sizeof(char ));
strcpy(econome, string);
return econome;
}
Dunod. Unauthorized photocopying is an offence.

119
Chapter 13 - Character strings

Exercises

Without using string.h


13.1 (∗) Make a function that takes a string as parameter, and returns the number of
occurrences of the letter ƒ in the string.

13.2 (∗) Make a function that returns the sum of the ASCII codes of the characters
in a string.

13.3 (∗) Make a function that copies a string and returns a copy of that string.

13.4 (∗∗) Make a function that returns the concatenation of two strings, i.e. a string
made up of the two strings put end to end.

13.5 (∗)Write a comparison function that takes two strings as parameters and returns:
- first stringis smaller than the second in alphabetical order.
if the
0 if both strings are equal; +1 if the first string is greater than the second in
alphabetical order.
Alphabetical order is the same as comparing ASCII codes.
characters.

13.6 (∗) Write a function that reads a string of characters from the keyboard and
counts the number of spaces in the string.

Possibly using string.h


13.7 (∗) a) Write a function that reads a file name from the keyboard, opens a file of
that name and counts the number of occurrences of a word in the file. We
will assume that the word contains no spaces and that the file contains no punctuation.
The word must be passed as a parameter.
b) Write the main program that reads a word from the keyboard and calls the function.

13.8 (∗) Write a function that opens a text file whose name is passed as a parameter
and calculates the sum of its line lengths.

13.9 (∗) Write a function that takes the name of a text file as a parameter and de-
termine the number of lines in the file that begin with the word "let's program".

120
Answers

Answers

13.1
int occ(char *s)
{
int occurrence = 0;
int t = 0;

while (s[t] != 0)
{
if (s[t] == 'f')
occurrence++;
t++;
}
return occurrence;
}

13.2
int ascii(char *s)
{
int sum = 0;
int t = 0;
while (s[t] != 0)
{
sum += s[t]; t++;
}
return sum;
}

13.3
char *recopie(char *s)
Dunod. Unauthorized photocopying is an offence.

{
int size = 0;
int t,u;
char *copy;
while (s[size] != ' 0')
\
{
s[size]++;
}
copy = calloc(size + 1, sizeof(char));

121
Chapter 13 - Character strings

if (copy != NULL)
{
t = 0;
u = 0;
while (s[t] != '\ 0')
{
copy[u] = s[t];
t++;
u++;
}
copy[u] = '\0';
}
return copy;
}

13.4
char *concat(char *s, char *t)
{
int sizes = 0, taillet = 0;
int tmps, tmpt, tmpc;
char *concat;
while (s[sizes] != ' 0') \
{
sizes++;
}
while (t[taillet] != '\ 0')
{
taillet++;
}
concat = calloc(sizes + taillet + 1, sizeof(char));
if (concat != NULL)
{
tmps = 0;
tmpt = 0;
tmpc = 0;
while (s[tmps] != '\ 0')
{
concat[tmpc] = s[tmps];
tmps++;
tmpc++;
}
while (t[tmpt] != '\ 0')
{
concat[tmpc] = s[tmpt];

122
Answers

tmpt++;
tmpc++;
}
concat[tmpc] = '\0';
}
return concat;
}

13.5
int ordre(char *s, char *t)
{
int tmps = 0, tmpt = 0;
while ((s[tmps] == t[tmpt]) && (s[tmps] != '\0') && (t[tmpt] != '\0'))
{
tmps++;
tmpt++;
}
if ((s[tmps] == '\0') && (t[tmpt] == '\0'))
return 0;
if ((s[tmps] != '\0') && (t[tmpt] == '\0'))
return 1;
if ((s[tmps] == '\0') && (t[tmpt] != '\0'))
return -1;
if (s[tmps] < t[tmpt])
return -1;
return 1;
}

13.6
#define SIZE 1000
int space()
{
char *s;
int tmp, esp = 0;
Dunod. Unauthorized photocopying is an offence.

s = calloc(SIZE, sizeof(char));
if (s == NULL)
return -1;
printf("Enter a string :\n");
fgets(s, SIZE, stdin);
tmp = 0;
while (s[tmp] != '\ 0')
{
if (s[tmp] == ' ')

123
Chapter 13 - Character strings

esp++;
tmp++;
}
return esp;
}

13.7
#define SIZE 1000
a)
int cherche(char *word)
{
FILE *fp;
char buffer[SIZE];
int occ = 0;
printf("File name ? ");
scanf("%s", buffer);
fp = fopen(buffer, "rt");
if (fp == NULL)
{
printf("Reading error"); return
-1;
}
while (fscanf(fp, "%s", buffer) > 0)
{
if (strcmp(buffer, word) == 0)
occ++;
}
fclose(fp);
return occ;
}

b)
int main()
{
char m[SIZE]; printf("Enter a
word :\n"); scanf("%s", m);
printf("%d occurrence(s) of %s in the file", cherche(m), m); return
0;
}

124
Answers

13.8
#define SIZE 1000
int sum(char *name)
{
FILE *fp;
char buffer[SIZE];
int s = 0;
fp = fopen(name,
"rt"); if (fp == NULL)
{
printf("Reading error"); return
-1;
}
while (fgets(buffer, SIZE, fp) != NULL)
{
/* fgets also reads the line break, it must be removed */
buffer[strlen(buffer) - 1] = '\0';
s += strlen(buffer);
}
fclose(fp);
return s;
}

13.9
#define SIZE 1000
int debutLigne(char *nom)
{
FILE *fp;
char buffer[SIZE];
char text[11] = "let's program";
int nb = 0;
fp = fopen(name,
"rt"); if (fp == NULL)
{
printf("Reading error"); return
Dunod. Unauthorized photocopying is an offence.

-1;
}
while (fgets(buffer, SIZE, fp) != NULL)
{
if (strncmp(buffer, text, sizeof(text)) == 0)
nb++;
}
fclose(fp);
return nb;
}

125
B INARY FILES
14
14.1 T HE DIFFERENCE BETWEEN TEXT
AND BINARY FILES
A text file contains ASCII text. When a text file contains numbers, these are
encoded as text using the characters '1', '2', etc. In this format, each digit takes up
one byte of memory. In this format, each number takes up 1 byte of memory. The
contents of a text file can be viewed with a text editor such as vi, emacs or notepad.
The functions for reading and writing to a text file (fscanf, fprintf...) are
analogous to the functions for reading and writing text in a scanf and printf console.
A binary file contains binary code. Its contents cannot be viewed with a text editor.
When a variable is written to a binary file, we write the exact value of the variable
directly, as encoded in binary in memory. This way of storing data is more precise
and compact for encoding numbers. The functions for reading and writing to a binary
file are fread and fwrite, which read and write blocks of data in binary form.

14.2 O PENING AND CLOSING A BINARY FILE


As with text files, to use binary files, you need to include the :

#include<stdio.h>
Dunod. Unauthorized photocopying is an offence.

and declare a file pointer for each file:

FILE *fp; /* declaration of an fp file pointer */

The file is opened in "r", "w", "a", "r+", "w+" or "a+" mode. Let's take the case
of opening a read-only file:

FILE *fp;
fp = fopen("myfile.dat", "r");

127
Chapter 14 - Binary files

The various possible modes for a binary file are :

- "r": read-only mode. The file is opened at the beginning, ready to read data. Any
attempt to write to the file will result in an error.
• "w": write-only mode. The file is initially empty. If the file existed before, it is
overwritten and the data is lost. After calling fopen, the file
is ready to write data. Any attempt to read data will result in an error.
- "a": add mode. The file is not overwritten, but is ready to write after the existing
data. Any attempt to read the file will result in an error.
- "r+": read-write mode. The file is ready for reading and writing at the beginning of
the file. The file is not overwritten. When data is written, it replaces any data that
may have been in the file at that location on disk.
• "w+": read-write mode. The file is overwritten.
- "a+": read-write mode. The file is not overwritten, but is ready to be written after
the existing data.

After using a file, you need to close it using fclose. The function
fclose takes the file pointer as parameter and closes the file.

14.3 R EADING FROM A BINARY FILE


To read a binary file, we generally read the elements of an array into the file. Each
element of the array is called a block. Each block has a size in bytes. For example, a
char corresponds to 1 byte, a float t o 4 bytes, and so on.
The sizeof function gives the size of each type. For example, sizeof(char)
is 1, and sizeof(float) is 4. It is preferable to use the sizeof function rather
than a constant such as 1 or 4, as this makes the program easier to read and does not
depend on the compiler or system. For example, the size of an int can be either 2
or 4, but sizeof(int) is always correct.
The fread function takes as parameters the array, the size of each block, the
number of blocks to be read (number of array elements), and the file pointer. The
physical size of the array must be at least equal to the number of blocks read, to
avoid a memory error. The fread function transfers data from the binary file to
the array.
A variable x can be read using the fread function. Simply set the variable's
address &x in place of the array and set the number of blocks equal to 1; the data is
then transferred to the variable.

128
14.3. Reading from a binary file

Supplements
,
Generally speaking, the address of a variable can always be considered as a
single-element array. This is because an array is only an address that
points to a memory area reserved for the program (statically or dynamically).

The fread function returns the number of elements actually read. If this number
is less than the number actually requested, either a read error has occurred, or the
end of the file has been reached.

Example
Let's suppose that a file contains the encoding of an integer array that we're
going to load into main memory. The file will contain int and float elements. The first
element of the file (of type int) gives the number of elements of type float that
follow. The following program loads an array into memory and displays it in the
console.
#include <stdio.h>
#include <stdlib.h>

/* the file name is passed as a parameter (char* type) */


float* Load(char * filename, int *adrNbElem)
{
int n, ret;
float *tableau;
FILE *fp;
if ((fp=fopen(filename, "r")) == NULL)
{
printf("Error:");
puts("file not found or insufficient rights");
exit(1);
}
fread(&n sizeof(int), 1, fp); /* the number o f elements is read */
*adrNbElem = n; /* pass by address */
Dunod. Unauthorized photocopying is an offence.

/* When the number of elements is known, the array is allocated:


*/ array = (float*)malloc(n*sizeof(float )); /* allocation */
ret = fread(array, sizeof(float), n, fp);
if (retỊ=n) /* read elements */
puts("Read error or end of file Ị");
fclose(fp); /* close file (mandatory) */ return
tableau;
}

129
Chapter 14 - Binary files

void Affichage(float* tableau, int nb)


{
int i;
for (i=0 ; i<nb ; i++)
printf("%.3f ", tableau[i]);
}

int main(void)
{
int nb; /* nb is not a pointer but an int */
float *tableau;
array = Load("myfile.dat", &nb);
Display(array, nb);
free(tableau); /* free memory */
return 0;
}

14.4 W RITING TO A BINARY FILE


To write to a binary file, use the fwrite function, which transfers data from
main memory to a binary file.
Like the fread function, the fwrite function takes as parameters the array,
the size of each block, the number of blocks to be written and the file pointer. The
physical size of the array must be at least equal to the number of blocks written, to
avoid a memory error. The fwrite function transfers data from the array to the
binary file.
The fwrite function returns the number of elements actually written. If this
number is less than the number actually requested, a writing error has occurred (file
not opened, disk full, etc.).

Example
The following program reads an array of real numbers from the keyboard and
saves them in a binary file. The format of the file is the same as in the previous
example: first the number of elements is found, then the successive elements in the
file.
#include <stdio.h>
#include <stdlib.h>

float* LectureTableau(int * adrNbElem)


{
float *tableau;
int i;

130
14.5. Positioning in a binary file

puts("Enter the number of elements");


scanf("%d", adrNbElem); /* pass by address, no & */
array = (float*)calloc(*adrNbElem, sizeof(float)); for
(i=0; i<*adrNbElem; i++)
scanf("%f", &tableau[i]);
return tableau;
}

void Sauvegarde(int *tableau, int nb, char* nomFichier)


{
FLIE *fp;
if ((fp=fopen(filename, "w")) == NULL)
{
puts("Permission denied or directory does not exist");
exit(1);
}
/* write number o f elements */
fwrite(&nb, sizeof(int), 1, fp)
/* writing elements */
if (fwrite(array, sizeof(float), nb, fp)Ị=nb) puts("Error
writing to file Ị");
fclose(fp);
}

int main(void)
{
int nb; /* do not put a pointer here */
float* table;
array = LectureTableau(&nb); Save(array,
nb, "myfile.dat") free(array); /* free
memory */ return 0;
}

14.5 P OSITIONING IN A BINARY FILE


Dunod. Unauthorized photocopying is an offence.

At any given time, an open file pointer is at a current position, i.e. the file pointer is
ready to read or write at a certain em- ployment in the file. Each call to fread or
fwrite advances the current position by the number of bytes read or written.
The fseek function allows you to position yourself in a file, modifying the current
position so that you can read or write to the desired location. When a location is
written to, any data that may have existed there is erased, and the file is deleted.

131
Chapter 14 - Binary files

replaced by the written data. The prototype o f the fseek function f o r positioning is
:

int fseek(FILE *fp, long offset, int origine);

The function modifies the position of the fp file pointer by a number of bytes equal to
offset from the origin. The origin can be :

• SEEK_SET: positions to the beginning of the file;


• SEEK_END: we position ourselves relative to the end of the file;
• SEEK_CUR: position relative to current position (position before fseek call).

Example
The following example deals with integer files. The function taking an integer i as
parameter allows the user to modify the (i + 1)th integer in the file.
void ModifieNombre(int i, FILE *fp)
{
int n, new;
fseek(fp, i*sizeof(int), SEEK_SET); /* positioning */
fread(&n, sizeof(int), 1, fp); /* reading */
printf("Old integer is %d\n", n);
puts("Please enter the new value");
scanf("%d", &new);
fseek(fp, -sizeof(int), SEEK_CUR); /* m o v e back one square */
fwrite(&new, sizeof(int), 1, fp); /* writing */
}

Exercises

14.1 (∗) A number file contains duplicates. The file is structured as follows:

• The first data item is an int giving the number of duplicates in the file.
• The following data are duplicates one after the other.

a) Write a function to display file data. Pass the f i l e name as a parameter.

132
Exercises

b) Write a function for entering file data. No arrays will be used. Pass the file name
as a parameter.

c) Write a function that displays all the values in the file between two numbers a and
b passed as parameters.

d) Write a function to display the ith data item in the file.

e) Write a function that displays the penultimate data in the file, if it exists.

Supplements
,
For the next exercise, we need to use pointers to a structure. If p is a pointer
to a structure containing a float field x, then (*p) is a structure, and
(*p).x is a float. To simplify writing, you can use the notation p->x
instead of (*p).x to designate the field x of the structure pointed to by p.

14.2 (∗∗) A sporting goods store has a database to manage its stock. Each item is
stored in memory as a :
typedef struct {
int code; /* item code */
char denomination[100]; /* product name */
float price; /* product unit price */
int stock; /* available stock */
}TypeArticle;
The database is a binary file whose :
• the first data item is an integer representing the number of items in the database;
the following data items are the structures representing the various items in the
- database.

a) Write a function to load the database into main memory in the form of an array of
Dunod. Unauthorized photocopying is an offence.

structures.

b) Write a function to save the database to a file.


In the following, we'll assume that the database is loaded into memory as an array.

c) Write a function to find the code of an item by its name.

d) Write a function to display an item whose code is passed as a parameter.

133
Chapter 14 - Binary files

e) Write a function allowing a user to modify an item whose code is passed as a


parameter.

f) Write a function to enter a new item in the database.

g) Write a function to delete an item from the database, with the code passed as a
parameter.

Answers

14.1
a)
void Affichage(char *nomFichier)
{
int n, ret, i;
double *tableau;
FILE *fp;
if ((fp = fopen(filename, "rb")) == NULL)
{
puts("Error: file does not exist or insufficient rights");
exit(1);
}
fread(&n, sizeof(int), 1, fp);
printf("n=%d \n", n);
array = (double *) malloc(n * sizeof(double));
ret = fread(array, sizeof(double), n, fp);
if (ret != n)
{
puts("read error or end of file"); exit(1);
}
fclose(fp);
printf("Array elements: n"); for (i = 0;
i < n; i++)
printf("%lg\n", array[i]);
free(array);
}
b)
void Input(char *filename)
{
int n, i;
double value;

134
Answers

FILE *fp;
if ((fp = fopen(filename, "wb")) == NULL)
{
puts("Permission not granted or directory does not exist");
exit(1);
}
printf("Enter number of elements");
scanf("%d", &n);
fwrite(&n, sizeof(int), 1, fp);
for (i = 0; i < n; i++)
{
printf("Enter element %d from array", i + 1);
scanf("%lg", &value);
fwrite(&value, sizeof(double), 1, fp);
}
fclose(fp);
}
c)
void Afficheab(char *filename, double a, double b)
{
double value;
int n, ret, i;
FILE *fp;
if ((fp = fopen(filename, "rb")) == NULL)
{
puts("Error: file does not exist or insufficient rights");
exit(1);
}
ret = fread(&n, sizeof(int), 1, fp);
if (ret < 1)
{
printf("Read error or end of file"); exit(1);
}
Dunod. Unauthorized photocopying is an offence.

printf("Items between %lg and %lg :n ", a, b); for (i = 0; i


< n; i++)
{
ret = fread(&value, sizeof(double), 1, fp);
if (value >= a && value <= b)
printf("%lg\t", value);
}
puts("");
fclose(fp);
}

135
Chapter 14 - Binary files

d)
void Affichageieme(char *filename, int i)
{
double value;
int n, ret;
FILE *fp;
if ((fp = fopen(filename, "rb")) == NULL)
{
puts("Error: file does not exist or insufficient rights");
exit(1);
}
fseek(fp, (1) * sizeof(int) + (i - 1) * sizeof(double), SEEK_SET);
ret = fread(&value, sizeof(double), 1, fp);
if (ret < 1)
{
printf("Read error or end of file"); fclose(fp);
exit(1);
}
else
printf("ith element= %lg\n", value);
fclose(fp);
}
e)
void DisplayBeforeLast(char *filename)
{
double value;
int n, ret;
FILE *fp;
if ((fp = fopen(filename, "rb")) == NULL)
{
puts("Error: file does not exist or insufficient rights");
exit(1);
}
fseek(fp, -2 * sizeof(double), SEEK_END);
ret = fread(&value, sizeof(double), 1, fp);
if (ret < 1)
{
printf("Read error or end of file");
}
else
printf("Second last element= %lg\n", value);
}

136
Answers

14.2
typedef struct
{
int code;
char denomination[100];
float price;
int stock;
} TypeArticle;
a)
TypeArticle *Loading(char *file_name, int *nb)
{
FILE *fp;
int i; TypeArticle
*tab;
fp = fopen(filename, "rb"); if
(fp == NULL)
{
fprintf(stderr, "Problem fopen");
exit(1);

}
fread(nb, sizeof(int), 1, fp);
printf("nb Loading=%d\n", *nb);
tab = (TypeArticle *) malloc((*nb) * sizeof(TypeArticle));
for (i = 0; i < *nb; i++)
{
fread(&tab[i].code, sizeof(int), 1, fp);
fread(tab[i].denomination, 100, 1, fp);
fread(&tab[i].price, sizeof(float), 1, fp);
fread(&tab[i].stock, sizeof(int), 1, fp);
} fclose(fp);
for (i = 0; i < *nb; i++)
{
printf("%d\t%s\t%f\t%d\n", tab[i].code, tab[i].denomination,
Dunod. Unauthorized photocopying is an offence.

tab[i].prix, tab[i].stock);
}
return tab;
}
b)
void Save(char *filename)
{
TypeArticle *tab;
int i, nb;

137
Chapter 14 - Binary files

FILE *fp;
if ((fp = fopen(filename, "wb")) == NULL)
{
puts("permission not granted or directory does not exist");
exit(1);
}
printf("Enter number of items"); scanf("%d",
&nb);
tab = (TypeArticle *) malloc((nb) * sizeof(TypeArticle));
fwrite(&nb, sizeof(int), 1, fp);
for (i = 0; i < nb; i++)
{
printf("Enter item code to be added"); scanf("%d",
&tab[i].code);
printf("Enter new name"); scanf("%s",
&tab[i].denomination); fscanf(stdin,
"%*c");
tab[i].denomination[strlen(tab[i].denomination)] = '\0';
printf("Enter new price \n");
scanf("%f", &tab[i].price);
printf("Enter new stock"); scanf("%d",
&tab[i].stock); fwrite(&tab[i].code,
sizeof(int), 1, fp);
fwrite(tab[i].denomination, 100, 1, fp);
fwrite(&tab[i].price, sizeof(float), 1, fp);
fwrite(&tab[i].stock, sizeof(int), 1, fp);
} free(tab);
fclose(fp);
}
c)
int Search(TypeArticle * array, char *denomination, int nb)
{
int i, cmp;
for (i = 0; i < nb; i++)
{
cmp = strcmp(denomination, array[i].denomination); if
(cmp == 0)
return tableau[i].code;
}
return -1;
}

138
Answers

d)
void Affichearticlecode(TypeArticle * tableau, int code, int nb)
{
int i, a;
for (i = 0; i < nb; i++)
{
if (array[i].code == code)
{
printf("code %d : denomination=%s, prix=%f, stock=%d \n",
array[i].code, array[i].denomination,
array[i].prix, array[i].stock);
break;
}
}
printf("The code you are looking for does not exist");
}
e)
int Modifiearticlecode(char *filename, int code)
{
int i, nb;
TypeArticle
Article; FILE *fp;
if ((fp = fopen(filename, "r+b")) == NULL)
{
puts("permission not granted or directory does not exist");
}
fread(&nb, sizeof(int), 1, fp);
printf("nb=%d\n", nb);
for (i = 0; i < nb; i++)
{
fread(&Article.code, sizeof(int), 1, fp);
printf("code=%d\n", code);
if (Article.code == code)
{
printf("Enter new name"); scanf("%s",
Dunod. Unauthorized photocopying is an offence.

Article.denomination); fscanf(stdin, "%*c");


Article.denomination[strlen(Article.denomination)] = '\0';
printf("Enter new price");
scanf("%f", &Article.price);
printf("Enter new stock"); scanf("%d",
&Article.stock);
fwrite(Article.denomination, 100, 1, fp);
fwrite(&Article.price, sizeof(float), 1, fp);

139
Chapter 14 - Binary files

fwrite(&Article.stock, sizeof(int), 1, fp);


fclose(fp);
return (0);
}
fseek(fp, (100 + sizeof(float) + sizeof(int)), SEEK_CUR);
} printf("item not found");
fclose(fp);
return 1;
}
f)
void Saisienouveauarticle(char *nomfichier)
{
int i, a, nb;
TypeArticle Article;
FILE *fp;
fp = fopen(filename, "r+b"); if
(fp == NULL)
{
fprintf(stderr, "Problem fopen");
exit(1);
}
fread(&nb, sizeof(int), 1, fp); printf("Enter new
item=%d\n", nb); printf("Enter item code to be
added"); scanf("%d", &Article.code);
printf("Enter new name"); scanf("%s",
Article.denomination); fscanf(stdin, "%*c");
Article.denomination[strlen(Article.denomination) - 1] = '\0';
printf("Enter new price");
scanf("%f", &Article.price);
printf("Enter new stock"); scanf("%d",
&Article.stock);
nb = nb + 1;
fseek(fp, 0, SEEK_SET);
fwrite(&nb, sizeof(int), 1, fp);
fseek(fp, 0, SEEK_END);
fwrite(&Article.code, sizeof(int), 1, fp);
fwrite(Article.denomination, 100, 1, fp);
fwrite(&Article.price, sizeof(float), 1, fp);
fwrite(&Article.stock, sizeof(int), 1, fp);
fclose(fp);
}

140
Answers

g)
int Suprimearticle(char *filename, int code)
{
int i = 0, nb, flag = 0;
TypeArticle Article;
FILE *fp;
if ((fp = fopen(filename, "r+b")) == NULL)
{
puts("permission not granted or directory does not exist");
}
fread(&nb, sizeof(int), 1, fp);
while (i < nb && flag == 0)
{
fread(&Article.code, sizeof(int), 1, fp);
if (Article.code == code)
{
flag = 1;
}
i++;
fseek(fp, 100 + sizeof(float) + sizeof(int), SEEK_CUR);
}
if (flag == 0)
{
printf("item not found");
fclose(fp);
return 1;
}
if (flag == 1 && i == nb) /* the item to be deleted is the last one */
{
fseek(fp, 0, SEEK_SET);
nb = nb - 1;
fwrite(&nb, sizeof(int), 1, fp);
fclose(fp);
return 1;
}
Dunod. Unauthorized photocopying is an offence.

while (i < nb)


{
fread(&Article.code, sizeof(int), 1, fp);
fread(Article.denomination, 100, 1, fp);
fread(&Article.price, sizeof(float), 1, fp);
fread(&Article.stock, sizeof(int), 1, fp);
fseek(fp, -2 * (sizeof(int) + 100 + sizeof(float) + sizeof(int)),
SEEK_CUR);
fwrite(&Article.code, sizeof(int), 1, fp);

141
Chapter 14 - Binary files

fwrite(Item.name, 100, 1, fp);


fwrite(&Article.price, sizeof(float), 1, fp);
fwrite(&Article.stock, sizeof(int), 1, fp);
i++;
fseek(fp, 1 * (sizeof(int) + 100 + sizeof(float) + sizeof(int)),
SEEK_CUR);
} fseek(fp, 0, SEEK_SET);
nb = nb - 1;
fwrite(&nb, sizeof(int), 1, fp);
fclose(fp);
return 0;
}

142
D OUBLE PANELS
INPUT
15
15.1 D IMENSION 2 TABLES
A 2-dimensional array, also known as a double-entry array or matrix, is an array of
arrays. You can declare a 2-dimensional array statically:

#define NB_LIGNES 100


#define NB_COLUMNS 50
...
int array[NB_LIGHTS][NB_COLUMNS];

The individual elements are accessed using square brackets: the element
array[i] is an array, and its element j is therefore denoted array[i][j].
Conventionally, such an array is conceived as having rows and columns, with
subscript i representing the number of a row, and subscript j representing the
number of a column. The element array[i][j] is located at the intersection of row
i and column j.

Example
The following program creates a matrix where each element (i, j) is i + j.
#define NB_LIGNES_MAX 100
#define NB_COLONNES_MAX 50
void Creer(int tableau[NB_LIGNES_MAX][NB_COLONNES_MAX],
int nbl, int nbc)
{
int i, j;
for (i=0; i<nbl; i++) /* for each row of the array */
for (j=0; j<nbc; j++) /* for each column */
array[i][j] = i+j;
}
Dunod. Unauthorized photocopying is an offence.

void Display(int array[NB_LIGNES_MAX][NB_COLUMNS_MAX],


int nbl, int nbc)
{
int i, j;
for (i=0; i<nbl; i++) /* for each line */
{
for (j=0; j<nbc; j++) /* for each column */
printf("%d ", array[i][j]);
printf("\n"); /* go to line */
}
}

143
Chapter 15 - Double entry tables

int main(void)
{
int array[NB_LIGNES_MAX][NB_COLUMNS_MAX];
int nbl, nbc;
puts("Enter number of rows and columns"); scanf("%d %d",
&nbl, &nbc);
if (nbl > NB_LIGNES_MAX || nbc > NB_COLONNES_MAX)
{
puts("Error, number exceeds array size"); exit(1);
}
Create(array, nbl, nbc);
Display(array, nbl, nbc); return
0;
}
The result of running this program for 4 rows and 6 columns is :
0 1 2 3 4 5
1 2 3 4 5 6
2 3 4 5 6 7
3 4 5 6 7 8

15.2 D YNAMIC ALLOCATION AND RELEASE OF


A 2-dimensional ARRAY

An array (of integers) of dimension 2 with dynamic allocation is declared by a


double pointer :

int** array;

The idea is that an array of integers is of type int* and an array of arrays of
integers is of type (int*)*.
To allocate the array of nbl rows and nbc columns, we first allocate an array of nbl
pointers. We then allocate each of these pointers with nbc integers in a loop (see
figure 15.2).

/* The function returns the double entry table */


int** Allocation(int nbl, int nbc)
{
int **tab;
int i;
/* 1) allocation o f an array of nbl pointers */
tab = (int**)calloc(nbl, sizeof(int*));

144
15.2. Allocation dynamique et libération d’un tableau de dimension 2

/* 2) allocation o f an array of nbc integers */


/* at the end of each pointer */
for (i=0; i<nbl; i++)
tab[i] = (int*)calloc(nbc, sizeof(int));
return tab;
}

To free the memory of a dynamically allocated array of dimension 2, we need to


free all the arrays one by one with a loop, then free the pointer array.

void Libération(int **tab, int nbl, int nbc)


{
int i;
for (i=0; i<nbl; i++)
if (nbc>0)
free(tab[i]);
Dunod. Unauthorized photocopying is an offence.

if (nbl>0)
free(tab);
}

The principle of one call for free for each call for
malloc or calloc to free all memory.

145
Chapter 15 - Double entry tables

Exercises

15.1 (∗)

a) Write a function for entering a static double-entry array of int. The number of
rows and columns will be entered using the keyboard.

b) Write a function that takes a static double-entry array of int, its number of rows
and its number of columns, and counts the number of times a number x passed in
parameter appears.

c) Write a function that takes a double-entry array tab as a parameter and returns
an array whose elements correspond to the parity of the elements in tab.

d) Write a main program that enters a double-entry array, and counts the number of
even-numbered elements in the array.

15.2 (∗∗) Consider a table with m rows and n columns entered in a file. The first line
of the file contains the numbers m and n. The following rows of the
files contain the coefficients of the table. Columns are separated by spaces.
m n
a_0,0 a_0,1 a_0,2 ... a_0,n-1
a_1,0 a_1,1 a_1,2 ... a_1,n-1
... ... ... ... ...
a_m-1,0 a_m-1,1 a_m-1,2 ... a_m-1,n-1

a) Write a function to allocate a 2-dimensional array of m rows and n co-rows, with


the numbers m and n passed as parameters.

b) Write a memory release function for an array of dimension 2.

c) Write a function that loads the file into an array of arrays (or matrix) A.

d) Write a function that calculates the sum of the coefficients in each row of the A-
maze and puts all the results in an array of m numbers. The function will return this
array.

e) Write the main program that displays the sum of the coefficients of each row of a
matrix stored in a file, and frees the memory.

146
Exercises

15.3 (∗∗) A spelling dictionary is represented by an array of strings that are the
words in the dictionary.

a) It is assumed that the words in the dictionary are stored, one per line, in a file. The
first line of the file contains the number of words. Write a function to char- gize the
file in main memory as an array of strings. The following steps can be taken:

• read word count and allocate pointer array.


• For each word
– Word reading ;
– Allocation of the corresponding string in the string array ;
– Copy the word into the allocated string.

b) Assume that the words in the file are arranged in alphabetical order. Write a
function to find a word in the dictionary.

c) Write a function to add a word to the dictionary. The following steps can be
followed:

• Entering the new word on the keyboard ;


• Check that the word is not already in the dictionary;
• To increase the memory size of the dictionary :
– Allocating a new pointer array ;
– Point all pointers in the new table that correspond to words smaller in
alphabetical order than the word you're looking for to the word memory of the
old dictionary;
– Allocate and copy the new word from the dictionary ;
– Point all pointers in the new table that correspond to words larger in alphabetical
Dunod. Unauthorized photocopying is an offence.

order than the word you're looking for to the word memory of the old
dictionary;
– Free the old pointer array and return the new one.

d) Write a dictionary backup function.

e) Write the main program that loads a dictionary, prompts the user to search for or
add words to the dictionary, or to quit, and then saves the dictionary at the end of the
program.

147
Chapter 15 - Double entry tables

Answers

15.1
#define NB_LIGNES_MAX 100
#define NB_COLONNES_MAX 50
a)
void Saisie(int tableau[NB_LIGNES_MAX][NB_COLONNES_MAX], int *nbl, int *nbc)
{
int i, j;
puts("Enter number of rows and columns"); scanf("%d
%d", nbl, nbc);
for (i = 0; i < *nbl; i++)
{
printf("Enter line %d\n", i + 1); for
(j = 0; j < *nbc; j++)
scanf("%d", &tableau[i][j]);
}
}
b)
void
CompteApparitionx(int tableau[NB_LIGNES_MAX][NB_COLONNES_MAX], int nbl,
int nbc, int x)
{
int i, j, counterx = 0; for
(i = 0; i < nbl; i++)
for (j = 0; j < nbc; j++)
if (tableau[i][j] == x)
counterx++;
printf("The number %d appears %d times", x, counterx);
}
c)
int *tableauparite(int tableau[NB_LIGNES_MAX][NB_COLONNES_MAX],
int nbl, int nbc, int *nbtableau)
{
int i, j;
int *tabparite;
*nbtable = 0;
tabparite = (int *) malloc(nbl * nbc * sizeof(int));
for (i = 0; i < nbl; i++)

148
Answers

for (j = 0; j < nbc; j++)


if (array[i][j] % 2 == 0)
{
tabparite[*nbtableau] = tableau[i][j];
(*nbtableau)++;
}
return tabparite;
}
d)
int
Compteparite(int tableau[NB_LIGNES_MAX][NB_COLONNES_MAX], int nbl, int nbc)
{
int i, j, nbtableau = 0;
for (i = 0; i < nbl; i++)
for (j = 0; j < nbc; j++)
if (array[i][j] % 2 == 0)
array++;
return nbtableau;
}
main program
int main(void)
{
int array[NB_LIGNES_MAX][NB_COLUMNS_MAX];
int nbl, nbc, nbtableau;
if (nbl > NB_LIGNES_MAX || nbc > NB_COLONNES_MAX)
{
puts("Error, number exceeds array size"); exit(1);
}
Input(array, &nbl, &nbc);
nbtableau = Compteparite(tableau, nbl, nbc);
printf("the number of even elements in the array= %d", nbarray);
return 0;
Dunod. Unauthorized photocopying is an offence.

15.2
a)
int **Allocation(int m, int n)
{
int **tab;
int i;

149
Chapter 15 - Double entry tables

tab = (int **) calloc(m, sizeof(int *));


for (i = 0; i < m; i++)
tab[i] = (int *) calloc(n, sizeof(int));
return tab;
}

b)
void Liberation(int **tab, int m, int n)
{
int i;
for (i = 0; i < m; i++)
if (n > 0)
free(tab[i]);
if (m > 0)
free(tab);
}
c)
int **Load(char *filename, int *nbl, int *nbc)
{
FILE *fp;
int i, j;
int **tab;
fp = fopen(filename, "rt");
if (fp == NULL)
{
puts("File open error"); exit(1);
}
fscanf(fp, "%d %d", nbl, nbc);
tab = Allocation(*nbl, *nbc);
for (i = 0; i < *nbl; i++)
{
for (j = 0; j < *nbc; j++)
fscanf(fp, "%d", &tab[i][j]);
}
fclose(fp);
return tab;
}
d)
int *Sumcoefficient(int **tab, int nbl, int nbc)
{
int i, j;

150
Answers

int *tabsum;
tabsomme = (int *) calloc(nbl, sizeof(int));
for (i = 0; i < nbl; i++)
for (j = 0; j < nbc; j++)
tabsomme[i] += tab[i][j];
return tabsomme;
}

e)
main program
int main(void)
{
int i, nbl, nbc;
int **tab;
int *sumcoeff;
tab = Load("matrix.txt", &nbl, &nbc);
sommecoeff = Sommecoefficient(tab, nbl, nbc);
for (i = 0; i < nbl; i++)
printf("sum of line coeff. %d = %d\n", i + 1, sumcoeff[i]); free(sumcoeff);
Liberation(tab, nbl, nbc);
return 0;
}
15.3
a)
char **Load(char *filename, int *nbl)
{
FILE *fp;
int i, j;
char **tab;
char tmp[200];
if ((fp = fopen(filename, "rt")) == NULL)
Dunod. Unauthorized photocopying is an offence.

{
puts("File open error"); exit(1);
}
fscanf(fp, "%d", nbl);
tab = (char **) calloc(*nbl, sizeof(char *));
for (i = 0; i < *nbl; i++)
{
fscanf(fp, "%s", tmp);
tab[i] = (char *) calloc(strlen(tmp) + 1, sizeof(char));

151
Chapter 15 - Double entry tables

strcpy(tab[i], tmp);
} fclose(fp);
return tab;
}
b)
int Search(char **tab, int nbl, char *word)
{
int cmp, i;
for (i = 0; i < nbl; i++)
{
cmp = strcmp(tab[i], mot);
if (cmp == 0)
return 0; /* word found */
else if (cmp > 0)
return 1; /* word not found */
}
return 1;
}
c)
char **rajoutermot(char **tab, int *nbl)
{
int j, i = 0, flag = 0;
char mot[200];
char **newab;
printf("Enter word to add"); scanf("%s",
word);
if (Search(tab, *nbl, word) == 0)
{
printf("the word already exists in the dictionary");
return NULL;
}
*nbl = *nbl + 1;
nouveautab = (char **) calloc(*nbl, sizeof(char *));
while (i < *nbl - 1 && flag == 0)
{
if (strcmp(tab[i], word) < 0)
{
newab[i] = tab[i]; i++;
}
else
flag = 1;
}

152
Answers

newab[i] = (char *) calloc(strlen(word) + 1, sizeof(char)); strcpy(newab[i],


word);
i++;
for (j = i; j < *nbl; j++)
nouveautab[j] = tab[j - 1];
if (*nbl > 0)
free(tab);
return nouveautab;
}
d)
void Save(char *filename, int nbl, char **newab)
{
FILE *fp;
int i;
char **tab;
if ((fp = fopen(filename, "wt")) == NULL)
{
puts("File open error"); exit(1);
}
fprintf(fp, "%d\n", nbl);
for (i = 0; i < nbl; i++)
fprintf(fp, "%s\n", newab[i]); fclose(fp);
}
e)
/*main program*/
int main(void)
{
int i, motrecherche, nbl, choix;
char **tab;
char **newab = NULL;
char mot[200];
Dunod. Unauthorized photocopying is an offence.

tab = Load("dictionary.txt", &nbl); while


(choice != 0)
{
puts("\nMENU");
puts("To search for a word type 1");
puts("To add a word type 2");
puts("To quit type 0"); printf("Your
choice: "); scanf("%d", &choice);

153
Chapter 15 - Double entry tables

getchar();
switch
(choice)
{
box 1:
puts("Search for a word");
printf("Enter the word to search for");
scanf("%s", word);
motrecherche = Search(tab, nbl, mot); if
(motrecherche == 0)
printf("word is found"); else
printf("the word is not in the dictionary"); break;
box 2:
puts("Add a word");
nouveautab = rajoutermot(tab, &nbl);
break;
case 0:
puts("You've decided to leave... Goodbye !"); break;
}
}
if (nouveautab != NULL)
{
Save("dictionary.txt", nbl, nouveautab); for (i
= 0; i < nbl; i++)
free(newab[i]); free(newab);
}
return 0;
}

154
Part 3

Algorithms
HMIC LANGUAGE
A LGORIT
16
AND
COMPLEXITY
16.1 W HY ANOTHER LANGUAGE ?
Computer science includes a wide range of programming languages (C, C++, Java,
Caml, Fortran, Pascal, Lisp, Prolog, Cobol, etc.). Programming in all these languages
requires a basic knowledge that is independent of the programming language:
algorithmics. To achieve this, we need to distinguish between algorithms, which are
methods that can be applied by computers to solve different problems, and their
implementation in a particular language.
In this chapter, we study an algorithmic language that is not a programming
language. Conceptually, this language is not very far removed from the C language
studied so far, but it still allows algorithms to be designed independently of their
implementation in C.

16.2 TYPES
The basic language types are :

- integer: this is the integer type, corresponding to the C int type, except that it
is not necessarily coded on 4 bytes.
• reel: this is the real number type, which can correspond to the double or
float of the C.
• caractere: this is the character type, corresponding to C's char type.
character c, the ASCII(c) function will give the ASCII code of c.

16.3 I/O
16.3.1 Keyboard and display
The read function is used to read a variable. If x is a variable (integer, real,
Dunod. Unauthorized photocopying is an offence.

character or string), the :


Read(x);

is used to read the value of x from the keyboard.


The ecrire function is used to write the contents of a variable to the screen. If x is
a variable (integer, real, character or string), the :
ecrire(x);
displays the value of x.

157
Chapter 16 - Algorithmic language and complexity

16.3.2 Text files


The file type allows you to read and write to a file. To do this, you must first declare
and open a :

File f;
f ← ouvrir("nom.txt", "lect");

File opening modes can be "lect" (read-only), "ecr" (read-only), "ecr" (read-only) or
"ecr" (read-only).
(write-only), or the "lectEcr" read-write mode.
The readF function is used to read a variable from a file. If x is of type integer,
real, character or string, and ƒ a file open for reading, the ins- truction :

readF(x, f);

sets x to the first value read from the file (and advances the current position in the
file).
The ecrireF function is used to write a variable to a text file. If x is of type
integer, real, character or string, and f is a file open for writing, the instruction :

writeF(x, f);

writes the value of x to the file (and advances the current position in the file).

16.4 S YNTAX
The assignment is denoted ←, the equality test is denoted =.
Example 1
The following algorithm calculates and displays 2n , where n is entered using the keyboard.
Start
algorithm
integer i, n,
puiss; puiss ← 1;
lire(n);
for i ← 0 to n-1 not 1 do puiss
← puiss * 2;
end do
write(power);
end

158
16.5. Functions and procedures

Example 2
Here's an interactive version of the previous algorithm:
Start
algorithm
integer i, n, power;
character choice;
ecrire("Do you want to calculate a power of 2?")
lire(choix);
if choice = 'y' do
power ← 1;
i ← 0;
read(n);
as long as i<n do
puiss ← puiss * 2;
i ← i+1
end do
write(power);
end do
end

16.5 F UNCTIONS AND PROCEDURES


16.5.1 Functions
A function in algorithmic language will have a prototype of the form :

FUNCTION FunctionName(Type1 name1, type2 name2,...): TypeReturn

where :
• ReturnType is the type of the value returned by the function;
• FunctionName is the name of the function;
• Type1, Type2... are the respective types of the parameters ;
• nom1, nom2... are the respective parameter identifiers.
Dunod. Unauthorized photocopying is an offence.

Example 3
The above algorithm calculating 2n can be restructured using a function:

FUNCTION TwoPuiss(integer n): integer


start
integer i, puiss;
puiss ← 1;
for i ← 0 to n-1 not 1 do
puiss ← puiss * 2;
end do

159
Chapter 16 - Algorithmic language and complexity

return power; end

Start
algorithm
integer n, power;
read(n);
puiss ← DeuxPuiss(n);
ecrire(puiss);
end

16.5.2 Procedures
A procedure is similar to a function, but returns no value. A procedure will have a
prototype of the form :

PROCEDURE FunctionName(Type1 name1, type2 name2,...)

Example 4
In the following example, the Display procedure is used to display integer data.
FUNCTION TwoPuiss(integer n): integer
start
integer i, puiss;
puiss ← 1;
for i ← 0 to n-1 not 1 do
puiss ← puiss * 2;
end do
return power; end

PROCEDURE Display(integer a)
start
write("the integer is : ");
write(a);
end

Start
algorithm
integer n, power;
read(n);
puiss ← DeuxPuiss(n);
Affiche(puiss);
end

160
16.6. Recordings

16.6 R ECORDINGS
A record corresponds to a C structure.

Example 5
record TypeArticle start
integer code;
character
name[100]; real
price;
end

PROCEDURE Display(TypeArticle A)
start
write(A.code);
write(A.name);
write(A.price);
end

Start
algorithm
TypeArticle A;
write("Enter code, name and price");
read(A.code, A.name, A.price);
Display(A);
end

16.7 P OINTERS , ADDRESSES AND ALLOCATION


In algorithmic language, pointers and addresses work in the same way as in C.

integer n;
integer
*p; n ←
2;
p ← &n;
*p ← *p+1;
Dunod. Unauthorized photocopying is an offence.

ecrire(n); /* affiche 3 */

The difference with C lies in the allocation f u n c t i o n s . The operator


new allows you to allocate memory in algorithmic language.

Example 6

record TypeArticle start


integer code;

161
Chapter 16 - Algorithmic language and complexity

character name[100];
real price;
end

FUNCTION AlloueTableau(integer* adr_n):


TypeArticle* start
TypeArticle *result;
integer n ;
write("Enter number of elements: "); read
(n);
*adr_n = n;
/* allocate an array of n TypeArticle */
resultat ← new TypeArticle[n];
return result;
end

16.8 N OTION OF ALGORITHM


COMPLEXITY

16.8.1 Intuitive definition of complexity


The complexity of an algorithm is an estimate of the number of basic operations
performed by the algorithm as a function of the size of the input data to the algo-
rithm.
For example, if an algorithm written in a function takes as input an array of n
elements, the complexity of the algorithm will be an estimate of the total number of
basic operations required for the algorithm, as a function of n. The larger n is, the
more operations are required. The nature of the algorithm will differ depending on
whether its complexity is of the order of n, n2 , n3 , or 2n . The computation time
taken by the algorithm will not be the same.
A basic operation can be an assignment, a test, an incrementation, an addition, a
multiplication, and so on.

16.8.2 Notion of big O

Any assignment, comparison test =, >, <, ≤, ... , arithmetic operation +, -, ∗, /,


function call such as sqrt, increment, decrement is called a basic or elementary
operation. When a function or procedure is
is called, the cost of this function or procedure is the total number of opera-

162
16.8. Notion of algorithm complexity

operations generated by calling this function or procedure. The computation time


taken by the algorithm (on a given machine) is directly linked to this number of
operations.
In fact, it's out of the question to calculate exactly the number of operations en-
gendered by the application of an algorithm. All we're looking for is an order of
magnitude (see figure 16.1). The asymptotic order of magnitude is the order of
magnitude when the data size becomes very large.
O(2 n)
number of operations

O(n 3)

)
O(n 2

n)
og
nl
O(
)
O(n

zone n)(
O

transition O(log n)

al O(1)

n
Figure 16.1- Asymptotic orders of magnitude

Let's consider an algorithm that depends on a datum d of size n (for example, an


array of n elements). Let NB = (d, n) denote the number of operations generated by
the algorithm. The algorithm is said to be O(n) if and only if we can find a number
K such that (for n large enough) :
Dunod. Unauthorized photocopying is an offence.

NB(d, n) ≤ K.n

In this case, the algorithm is also said to be linear.


The algorithm is said to be O(n2 ) if and only if it can find a number
K such that (for n large enough) :

NB(d, n) ≤ K.n2

In this case, the algorithm is also said to be quadratic.

163
Chapter 16 - Algorithmic language and complexity

The algorithm is said to be O(2n ) if and only if it can find a number


K such that (for n large enough)

NB(d, n) ≤ K.2n

In this case, the algorithm is also said to be exponential.

Exercises

For each of the exercises in this section, we'll evaluate the complexity of the proposed
algorithm.

16.1 (∗) Write an algorithm that initializes an array of n integers, the number n being
entered on the keyboard, the index value i of the array being worth- 1 if 3i + i 2 is a
2

multiple of 5 and 0 otherwise.

16.2 (∗) Write a function in algorithmic language that takes an integer i as a


parameter and calculates the value u(i) defined by recurrence by :

u0 = 1; u1 = 2

uj+1 = 3 ∗ u j - uj–1 for j ≥ 1

16.3 (∗) Write a function in algorithmic language that captures the elements of an
array whose number of elements n is passed as a parameter. Assume that the
array has already been allocated and is passed as a parameter.

16.4 (∗) Write a function in algorithmic language that takes an integer n and a two-
dimensional array of integers of size n n as parameters.
× The function calculates
the sum of the elements in the table.

16.5 (∗∗) Write a function in algorithmic language that calculates the values of an
array T of size n, the number n being entered from the keyboard, whose values T [i]
are such that T [0] = 1 and for i ≥ 1 :

T [i] = i ∗ (T [0] + T [1] + - - - + T [i - 1])

16.6 (∗∗) Let the function


(
3x2 + x + 1 if x ≥ 1
ƒ (x) =
0 otherwise

164
Exercises

a) Write a function in algorithmic language that takes an integer x as a parameter.


and calculates ƒ (x).

b) Write a function in algorithmic language that takes an integer n as a parameter.


and calculates the sum :

Sn = ƒ (n) + ƒ (n - 1) + ƒ (n - 2) + ƒ (n - 3) + ƒ (n - 4) + ---
We'll stop the sum when the calculated ƒ value is zero.

c) Write a function in algorithmic language that takes an integer n as a parameter.


and calculates the sum :

Tn = ƒ (n) + ƒ (n/22 ) + ƒ (n/32 ) + ƒ (n/42 ) + ƒ (n/52 ) + ---

In this sum, divisions are Euclidean divisions. We'll stop the sum when the calculated
ƒ value is zero.

d) Write a function in algorithmic language that takes an integer n as a parameter.


and calculates the sum :

Un = ƒ (n) + ƒ (n/2) + ƒ (n/4) + ƒ (n/8) + ƒ (n/16) + ---


In this sum, divisions are Euclidean divisions. We'll stop the sum when the calculated
ƒ value is zero.

16.7 (∗ ∗ ∗) ( Dichotomous search) We want to know if an array of n


contains a certain number a. It is assumed that the array is sorted
in ascending order, i.e. each element is less than or equal to the next in the table.
We could, of course, test all the numbers in the table by comparing them with a, but
this would require (in the worst case) n comparisons. We propose to apply a method
Dunod. Unauthorized photocopying is an offence.

that requires fewer operations. The method is called dichotomous search.


At each stage, we search for an element equal to a between two indices imin and imax .
Initially, the element can be found anywhere (between imin = 0 and imax = n - 1).
The element with index i = (imin + imax )/2 is compared with a. There are three
possible cases:

- If the element with index i is equal to a, the algorithm ends: the number a is
indeed in the array.

165
Chapter 16 - Algorithmic language and complexity

• If the element with index i is greater than a, an element equal to a can only be
found at an index smaller than i, since the array is sorted. The new imax is i - 1.
• If the element with index i is less than a, an element equal to a can only be found
at an index greater than i. The new imin is i + 1.

At each stage, an element equal to a can only be found between imin and imax . This
process is repeated until imin becomes strictly greater than imax . All that remains is to
test a single element.
As the number of elements in each step is divided by 2, the number of steps k
n
is such that ≥ 1. Therefore k ≤ (n).
2k
log2

a) Write a dichotomous search f o r a number x in an array of n


numbers. The function returns 1 if the element is in the array and 0 otherwise.

b) How complex is it?

Answers

16.1
Start
algorithm
integer i, n, puiss;
integer *tab;
read(n);
tab ← new integer[n]; for i
← 0 to n-1 not 1 do
if (3*i*i+i-2)%5 = 0 do
tab[i] ← 1;
otherwise do
tab[i] ← 0;
end do
end

166
Answers

Complexity is O(n)

16.2
FUNCTION Calculu(integer i): integer
start
whole j;
integer U0, U1,
U2; U0 ← 1;
U1 ← 2;
if i=0 do
return U0; end
do
if i=1 do
return U1; end
do
j ← 2;
as long as j<=i do
U2 ← 3 * U1-U0;
U0 ← U1;
U1 ← U2;
j ← j+1;
end return U2;
end
Complexity is O(i)

16.3
PROCEDURE Enter(integer n, integer *tab)
start
integer i;
for i ← 0 to n-1 not 1 read
(tab[i]);
end do end
Complexity is O(n)
Dunod. Unauthorized photocopying is an offence.

16.4
FUNCTION Sum(integer n,integer **tab): integer
start
integer i, j;
integer sum ← 0;
for i ← 0 to n-1 step 1 do
for j ← 0 to n-1 step 1 do

167
Chapter 16 - Algorithmic language and complexity

sum ← sum + tab[i][j]; end


do
end return sum;
end
The complexity is O(n )2

16.5
FUNCTION CalculateT(integer *nb):
integer * start
integer n,
i; integer
*tab;
read(n);
*nb ← n;
tab ← new integer[n]; tab[0]
← 1;
for i ← 0 to n-1 not 1 do tab[i]
← 0;
for j ← 0 to i-1 step 1 do
tab[i] ← tab[i] + tab[j];
end do
tab[i] ← tab[i]*i;
end do
return tab; end
The complexity is O(n )2

16.6
a)
FUNCTION CalculateFx(integer x): integer
start
if x<1 do
return 0;
end do
return 3*x*x+x+1; end
Complexity is O(1)
b)
FUNCTION CalculateSn(integer n): integer
start
integer j ← n;

168
Answers

integer S ← 0;
as long as j>0 do
S ←S +
CalculateFx(j); j ← j-
1;
end do
return S;
end
Complexity is O(n)
c)
FUNCTION CalculateTn(integer n): integer
start
integer i, j, Fx;
integer T ← 0;
i ← n;
j ← 2;
Fx ← CalculateFx(i);
as long as Fx !=0 do
T ← T + Fx;
i ← n/(j*j);
j ← j+1;
Fx ← CalculateFx(i);
end do
return T;
end
,
Complexity is O( n)
d)
FUNCTION CalculateUn(integer n): integer
start
integer i, j, Fx;
integer U ← 0;
i ← n;
j ← 1;
Dunod. Unauthorized photocopying is an offence.

Fx ← CalculateFx(i);
as long as Fx !=0 do
U ← U + Fx;
j ← j * 2;
i ← n/j;
Fx ← CalculateFx(i);
end do
return U;
end
Complexity is O(log2 (n))

169
Chapter 16 - Algorithmic language and complexity

16.7
a)
FUNCTION Searchdicho(integer a, integer *tab, integer n): integer
start
integer debut ← 0, fin ← n-1,
middle; as long as debut <=fin do
middle ← (start+end)/2;
if a= tab[middle]
return 1;
if a < tab[middle] do
fin=middle-1;
otherwise do
debut=milieu + 1;
end return
0;
end
b) Complexity is O(log2 (n))

170
Q UADRATIC SORTING
ALGORITHMS
17
17.1 W HAT IS SORTING ?
Let's give ourselves a table of numbers. The problem is to sort these numbers in
ascending order. In other words, we need to modify the array so that it contains the
same numbers as before, but this time the numbers are s o r t e d in ascending order,
from smallest to largest. This is a classic algorithmic problem.

Example
The result of sorting the :

6 3 7 2 3 5

is as follows:

2 3 3 5 6 7

More generally, we can try to sort objects on which an order relation is defined. In
this way, we can≤sort objects according to a criterion (sorting people according to
their height, sorting words in alphabetical order, etc.).

17.2 S ORT BY SELECTION


17.2.1 Selection sorting principle
Let's take an array T of n numbers. The principle of sorting by selection is as follows.
We select the maximum (largest) of all the elements, and place it in the last n-1
position by swapping. All that remains is to sort the first n-1 elements, for which we
iterate the process.
Dunod. Unauthorized photocopying is an offence.

Example
Or the table

6 3 7 2 3 5

The maximum in this table is 7. Let's place the 7 in the last position by an exchange.

6 3 5 2 3 7
____________________________
x ˛ z x
remains to sort

171
Chapter 17 - Quadratic sorting algorithms

The 7 is in its final position; all that remains is tosort the first five elements. The
maximum of these five elements is 6. Let's place it at the end by an exchange:

3 3 5 2 6 7
________ ________
x ˛z x
reste à tri er

The maximum number left to sort is 5. Let's place it in the last position by an
exchange:

3 3 2 5 6 7
____ ____
x ˛z x
at tr ier

Finally, the maximum number to be sorted is 3. This is placed last and the table
is sorted.

2 3 3 5 6 7

17.2.2 Selection sorting algorithm


The algorithm for sorting by selection (e.g. on integers) is as follows:

PROCEDURE TriSelection(integer *T, integer n)


start
integer k, i, imax, temp;
for k ← n-1 to 1 step -1 do
/* search for maximum index : */
imax ← 0;
for i ← 1 to k not 1 do if
T[imax] < T[i] do
imax ← i;
end do
end do
/* exchange: */
temp ← T[k];
T[k] ← T[imax];
T[imax] ← temp;
end do
end

17.2.3 Estimated number of operations


• Cost of exchanges. Sorting by selection on n numbers makes n - 1 exchanges,
which makes 3(n - 1) assignments.

172
17.3. Sort by insertion

• Cost of maximum searches :


– We search for the maximum among n elements: at most 4(n - 1) operations.
(this is the number of iterations of the loop on i for k set equal to n-1)
– We then search for the maximum among n - 1 elements: at most 4(n - 2) tests.
(this is the number of iterations of the loop on i for k set equal to n-2)
– We then search for the maximum among n - 2 elements: 4(n - 3) tests.
– ...
The total number of tests is :
(n - 1)n
4 (1 + 2 + 3 + - - - + (n - 2) + (n - 1)) = 4
2
It's the sum of the terms of an arithmetic sequence.
In total, the number o f operations is smaller than 3(n - 1) + 4(n–1)n
2 , which is a
polynomial of degree 2 in the number n of elements of the array. We say that the
is quadratic, or an O(n2 ) method. The degree 1 part in
n is negligible compared to the part in n2 when n becomes large.

17.3 S ORT BY INSERTION


17.3.1 Insertion sorting principle
The principle of insertion sorting is as follows: first sort the first two elements, then
insert the 3rd in its place to make a sorted list of 3 elements, then insert the 4th
element into the sorted list. The sorted list grows until it contains all n elements.
Example
Or the table

6 3 4 2 3 5
Dunod. Unauthorized photocopying is an offence.

Sorting the first two elements gives :

3 6 4 2 3 5
x˛zx
t rié

By inserting the third element in its place in the sorted list :

3 4 6 2 3 5
____ ____
x ˛zx
t rié

173
Chapter 17 - Quadratic sorting algorithms

Inserting the fourth element in its place in the sorted list :

2 3 4 6 3 5
________ ________
x ˛zx
t rié
Inserting the fifth element in its place in the sorted list :

2 3 3 4 6 5
____________ ____________
x
tr ié
Inserting the sixth element in its place in the sorted list :

2 3 3 4 5 6
To insert an element in its place, you need to offset the larger elements already
sorted.

17.3.2 Insertion sorting algorithm


The insertion sorting algorithm is as follows:

PROCEDURE TriInsertion(integer *T, integer n)


start
integer k, i, v;
for k ← 1 to n-1 not 1 do v
← T[k];
i ← k-1;
/* Shift elements for insertion */
as long as i ≥ 0 and v < T[i] do
T[i+1] ← T[i];
i ← i-1;
end do
/* We do the actual insertion */
T[i+1] ← v;
end do
end

17.3.3 Estimated number of operations


The index k varies from -1 to n 1, i.e.
- n 1 different values. For each value of k, the
index i takes on at most k different values. The total number of operations is
therefore at most :

3(n - 1) + 4 (1 + 2 + 3 + - - - + (n - 2) + (n - 1))
___________________________________________ ___________________________________________
xsum for diff˛érzentes values of xk

174
17.4. Bubble sorting

i.e. a maximum number of operations of :


(n – 1)n
3(n 1) + 4
- 2
which is a polynomial of the second degree in the number n of elements. The
algorithm is therefore quadratic (O(n2 )).

17.4 B UBBLE SORTING


17.4.1 Bubble sorting principle
In bubble sorting, we exchange two successive elements T[i-1] and T[i] if
they are not in order. Obviously, this has to be done a large number of times to
obtain a sorted array. More precisely, the maximum is moved up to its final position
by successive exchanges with its neighbors.

Example
Here's the sequence of successive element exchanges performed on an example.
6 3 4 2 3 5

3 6 4 2 3 5

3 4 6 2 3 5

3 4 2 6 3 5

3 4 2 3 6 5

3 4 2 3 5 6

We make a second pass:


3 2 4 3 5 6

3 2 3 4 5 6

Then another pass:


Dunod. Unauthorized photocopying is an offence.

2 3 3 4 5 6

17.4.2 Bubble sorting algorithm


PROCEDURE TriBubble(integer *T, integer
n) start
integer i, k, temp;
/* for each pass */
for k ← n-1 to 1 step -1 do

175
Chapter 17 - Quadratic sorting algorithms

/* the biggest one goes up */


for i ← 1 to k step 1 do if
T[i] < T[i-1] do
/* exchange of T[i-1] and T[i] */
temp ← T[i];
T[i] ← T[i-1];
T[i-1] ← temp;
end do
end do
end do
end

17.4.3 Estimated number of operations


The variable k takes n - 1 different values. For each of these values the variable
i takes k different values. The total number of operations is smaller than :

2(n - 1) + 5 (1 + 2 + 3 + - - - + (n - 2) + (n - 1))
kx
_________________________________________ _________________________________________
xsum for di˛ffzérentes values
This makes a number of operations at most :
(n – 1)n
1) + 5 2(n
- 2
which is a polynomial of degree 2 in the number n of array elements. The algorithm
is therefore quadratic (O(n2 )).

176
Q UICK SORTING
(quicksort) 18
Rapid sorting works on a divide-and-conquer basis. The ta- bleau is divided into two
parts, the left and the right, and each part is sorted separately. The result is a sorted
table.

18.1 P ARTITIONING
Suppose you want to sort part of an array T between the indices imin and imax.
Choose a pivot value, for example v = T[imax]. We want to separate elements below
v and elements above v in the array.

any elements v

imin imax
(a) before partitioning

elements <= v v elements >= v

imin imax
(b) after partitioning

Figure 18.1- Partitioning in quick sort

To do this, we introduce an index i, initialized to imin, and an index j,


initialized to imax-1. We then move index i up to the first element greater than v,
and move j down to the first element less than v. We then exchange
elements with indices i and j. This process is repeated until i ≤ j. At the end, we place the
pivot value in position i.

elements <= v elements >= v


Dunod. Unauthorized photocopying is an offence.

imin i j imax

Figure 18.2 - Exchanging index elements i and j, where applicable

The algorithmic code for this partitioning is :

FUNCTION Partitioning(integer *T, integer imin, integer imax)


: entire
start
integer v, i, j, temp;

177
Chapter 18 - Quicksort

v ← T[imax]; /* v pivot value */


i ← imin;
j ← imax-1;
as long as i<=j do
as long as i<imax and T[i] <= v
do i ← i+1;
end do
as long as j>=imin and T[j] >= v do
j ← j-1;
end do
if i<j do /* exchange */
temp ←
T[i]; T[i]
← T[j];
T[j] ← temp;
end do
end do
T[imax] ← T[i]; T[i] ← v; /* We place the pivot value in i */
return i; /* returns separation location */
end

18.2 T HE FAST SORTING ALGORITHM


After partitioning an array, the pivot v is in its definitive place in the sorted array. In
addition, all elements to the left of the pivot in the sorted array are those to the left of
the pivot after partitioning. Fast sorting consists in partitioning the array into two
parts, then sorting each of the two parts (left and right) according to the same
principle.

PROCEDURE TriRapide(integer *T, integer imin, integer imax)


start
integer i;
if imin < imax do
i ← Partitioning(T, imin, imax);
TriRapide(T, imin, i-1); /* sort left side */
TriRapide(T, i+1, imax); /* sort right side */
end do end

PROCEDURE QuickSort(integer *T, integer


n) start
TriRapide(T,0, n-1); /* imin=0 and imax=n-1 */
end

178
18.3. Comparison of calculation times

Note that the TriRapide procedure calls itself. This is known as a recursive
procedure. We'll take a closer look at this type of programming in another chapter.

18.3 C OMPARISON OF CALCULATION TIMES


Here (Figure 18.3) are experimental curves showing the computation time (CPU
usage time) of the bubble sort, insertion sort, selection sort and fast sort algorithms,
as a function of array size n. The number of elements n in the array varies from 1 to
2000. It can be seen that the computation time given by fast sorting is significantly
better than the computation time given by quadratic sorting (the curve is stuck close
to the x-axis). Complexity is reflected in calculation times.

70000

sort by

60000
bubbles sort

by selection
50000

sort by
40000
insertion

30000 rapid sorting

20000

10000

0
Dunod. Unauthorized photocopying is an offence.

0 200 400 600 800 1000 1200 1400 1600 1800

Figure 18.3 - Experimental comparison o f sorting algorithm computation times

Exercises

179
Chapter 18 - Quicksort

18.1 (∗) Apply the partitioning method to the following table:

7 9 2 3 6 7 4 3 8 1 5

18.2 (∗) Apply the partitioning method to the following table:

3 1 7 8 6 5 4 3 6 7 6

18.3 (∗) Apply quick sort to sort the following table:

7 2 6 9 3 5 3 1 4

18.4 (∗) Apply quick sort to sort the following table:

7 9 2 3 6 7 4 3 8 1 5

18.5 (∗) Apply quick sort to sort the following table:

3 1 7 8 6 5 4 3 6 7 6

Answers

18.1
1 3 2 3 4 5 6 9 8 7 7

18.2
3 1 3 4 6 5 6 7 6 7 8

18.3
1 2 3 3 4 5 6 7 9
1 2 3 3 4 5 6 7 9
1 2 3 3 4 5 6 7 9
1 2 3 3 4 5 6 7 9
1 2 3 3 4 5 6 7 9
1 2 3 3 4 5 6 7 9
1 2 3 3 4 5 6 7 9
1 2 3 3 4 5 6 7 9

18.4

180
Answers

1 3 2 3 4 5 6 9 8 7 7
1 3 2 3 4 5 6 9 8 7 7
1 3 2 3 4 5 6 9 8 7 7
1 2 3 3 4 5 6 9 8 7 7
1 2 3 3 4 5 6 7 8 7 9
1 2 3 3 4 5 6 7 8 7 9
1 2 3 3 4 5 6 7 7 8 9
1 2 3 3 4 5 6 7 7 8 9
Dunod. Unauthorized photocopying is an offence.

181
Chapter 18 - Quicksort

18.5
3 1 3 4 6 5 6 7 6 7 8
3 1 3 4 5 6 6 7 6 7 8
3 1 3 4 5 6 6 7 6 7 8
3 1 3 4 5 6 6 7 6 7 8
1 3 3 4 5 6 6 7 6 7 8
1 3 3 4 5 6 6 7 6 7 8
1 3 3 4 5 6 6 7 6 7 8
1 3 3 4 5 6 6 6 7 7 8
1 3 3 4 5 6 6 6 7 7 8

182

You might also like