C Programing
C Programing
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:
- 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.
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.
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.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.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
Data flow
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 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.
www.biblio-scientifique.net
Chapter 2 - First programs
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.
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
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.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.
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
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 */
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;
}
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.
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 */
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 */
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.
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!");
char caract='A';
printf("%c", caract); /* display as character 'A'*/
printf("%d", caract) /* displays as number 65 */
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
Don't forget the & in front of each variable in scanf, as this will cause a
memory error (segmentation error).
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;
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.
Exercises
4.1 (c) Write a program to display the ASCII code of a character entered on 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.
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.
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.
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;
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...");
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.
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.
A number (integer, real, etc.) can be considered true or false using the following
convention:
Example
Dunod. Unauthorized photocopying is an offence.
int response;
scanf("%d", &reponse);
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).
Example at customs
char papiers, rad;
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
c) Denial
The negation of a condition e is true when condition e is false.
si (non e)
then series of instructions
end if
Example at customs
char papiers, rad;
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.
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
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.
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.
#include <stdio.h>
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):
#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
#include <stdio.h>
#include <math.h>
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.
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.
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.
46
www.biblio-scientifique.net
Answers
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.
49
www.biblio-scientifique.net
Chapter 6 - Structuring a C program
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:
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 :
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'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>
52
www.biblio-scientifique.net
7.2. Using a structure
/* Field display : */
printf("(%f, %f, %f)", P.x, P.y, P.z);
}
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.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.
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);
}
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.
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.
{
result = result*n;
i = i+1; /* progression progression */
}
return resultat;
}
59
www.biblio-scientifique.net
Chapter 8 - Iteration
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.
In C, there's a more convenient syntax for doing all this: the for loop:
60
www.biblio-scientifique.net
Exercises
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).
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.
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).
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];
71
www.biblio-scientifique.net
Chapter 9 - Tables
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.
#include <stdio.h>
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;
}
#include <stdio.h>
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
#include <stdio.h>
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;
}
#include <stdio.h>
int main(void)
{
int tab[5] = {3, 56, 21, 34, 6}; /* with semicolon */
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.
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).
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 */
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
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
#include <stdio.h>
int TripleFile(void)
{
FILE *fpr, *fpw; /* two pointers for two files */
int n; /* to read */
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.
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.
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
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.
91
Chapter 11 - Addresses, pointers and address passing
#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.
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;
}
#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;
}
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>
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>
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.
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
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.
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 */
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.
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 */
103
Chapter 12 - Dynamic allocation
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
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.
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;
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'
char string[100];
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>
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.
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'.
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 :
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.
116
13.2 Predefined chain operations
The function copies the source string to the destination string. The destin
string must have been allocated beforehand. The function returns destin.
= 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 :
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 :
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.
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.
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
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.
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.
#include<stdio.h>
Dunod. Unauthorized photocopying is an offence.
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
- "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.
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>
129
Chapter 14 - Binary files
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;
}
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>
130
14.5. Positioning in a binary file
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;
}
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
:
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 :
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.
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.
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.
133
Chapter 14 - Binary files
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.
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.
139
Chapter 14 - Binary files
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.
141
Chapter 14 - Binary files
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:
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.
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
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).
144
15.2. Allocation dynamique et libération d’un tableau de dimension 2
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
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:
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:
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.
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
15.2
a)
int **Allocation(int m, int n)
{
int **tab;
int i;
149
Chapter 15 - Double entry tables
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
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.
157
Chapter 16 - Algorithmic language and complexity
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
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:
159
Chapter 16 - Algorithmic language and complexity
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 :
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
integer n;
integer
*p; n ←
2;
p ← &n;
*p ← *p+1;
Dunod. Unauthorized photocopying is an offence.
ecrire(n); /* affiche 3 */
Example 6
161
Chapter 16 - Algorithmic language and complexity
character name[100];
real price;
end
162
16.8. Notion of algorithm complexity
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
NB(d, n) ≤ K.n
NB(d, n) ≤ K.n2
163
Chapter 16 - Algorithmic language and complexity
NB(d, n) ≤ K.2n
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
u0 = 1; u1 = 2
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 :
164
Exercises
Sn = ƒ (n) + ƒ (n - 1) + ƒ (n - 2) + ƒ (n - 3) + ƒ (n - 4) + ---
We'll stop the sum when the calculated ƒ value is zero.
In this sum, divisions are Euclidean divisions. We'll stop the sum when the calculated
ƒ value is zero.
- 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
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
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.).
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
172
17.3. Sort by insertion
6 3 4 2 3 5
Dunod. Unauthorized photocopying is an offence.
3 6 4 2 3 5
x˛zx
t rié
3 4 6 2 3 5
____ ____
x ˛zx
t rié
173
Chapter 17 - Quadratic sorting algorithms
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.
3(n - 1) + 4 (1 + 2 + 3 + - - - + (n - 2) + (n - 1))
___________________________________________ ___________________________________________
xsum for diff˛érzentes values of xk
174
17.4. Bubble sorting
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
3 2 3 4 5 6
2 3 3 4 5 6
175
Chapter 17 - Quadratic sorting algorithms
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
imin imax
(b) after partitioning
imin i j imax
177
Chapter 18 - Quicksort
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.
70000
sort by
60000
bubbles sort
by selection
50000
sort by
40000
insertion
20000
10000
0
Dunod. Unauthorized photocopying is an offence.
Exercises
179
Chapter 18 - Quicksort
7 9 2 3 6 7 4 3 8 1 5
3 1 7 8 6 5 4 3 6 7 6
7 2 6 9 3 5 3 1 4
7 9 2 3 6 7 4 3 8 1 5
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