Professional Documents
Culture Documents
Algorithms New Way
Algorithms New Way
B. Mareschal
Campus Plaine - Building NO
Level 3 - Office 2.N.3.214
Phone: 650.5884
e-mail: bmaresc@ulb.ac.be
Summary :
0. Introduction
Algorithms and Programming Modules
Course Organisation
1. Computing & Programming Concepts
Computers, Programming, Languages
2. Introduction to C Programming
Simple Programs, Memory Concepts, Arithmetic in C
2.5 DOS, Windows & the C++ Compilers
Operating Systems, Basic Commands,
Borland C++ and C++ Builder Compilers
3. Structured Program Development
Algorithms, Problem Solving Techniques, Control Structures
4. Program Control
More Control Structures, Logical Operators
5. Functions
6. Arrays
7. Pointers
8. Characters and Strings
9. Formatted Input/Output
-1-
0. Introduction
The 'Algorithms and Programming' Modules :
Algorithms and Programming I (B. Mareschal)
Basic programming skills using the C language.
Algorithms and Programming II (M. Dehon)
Advanced programming : structures, pointers, lists, sets, files,
Methods of Programming (D. Leemans)
Stacks, queues, recursion, backtracking, trees, graphs,
Course Organisation :
Textbook(s) :
Theory
Exercises
Exercises Exercises
Evaluation :
Homeworks (programs)
Exam. in January (Alg.&Pr. I and II)
Computer Room : NO Building, level 4.
-2-
Useful references
Textbooks
(http://www.deitel.com)
H. M. Deitel & P. J. Deitel
nd
C How to Program (2 edition)
Prentice Hall, 1994, 926p., ISBN 0-13-226119-7
B. Gottfried
Programming with C (2nd edition)
K. B. Rojiani
Programming in C with Numerical Methods for Engineers
Prentice Hall, 1996, 1130p. ISBN 0-13-726498-4
H. Schildt
C++ The Complete Reference (2nd edition)
Osborne, McGraw-Hill, 1995, 671p., ISBN 0-07-882123-1
Compilers
K. Reisdorph & K. Henderson
Teach Yourself Borland C++ Builder in 14 days
Language Reference
B. W. Kernighan & D. M. Ritchie
The C Programming Language (2nd edition)
Prentice Hall, 1989, 274p., ISBN 0-13-110362-8.
B. Stroustrup
The C++ Programming Language (3rd edition)
Addison Wesley Series in Computer Science, 1997, 928p., ISBN 0-201-88954-4.
Algorithms
L. Ammeraal
Algorithms and Data Structures in C++
Wiley, 1996, 352p., ISBN 0-471-96355-0
R. Sedgewick
Algorithms in C
R. Sedgewick
Algorithms in C++
Programming :
Planning, scheduling or performing a task or an event.
Computer :
Programmable device that can store, retrieve and process data.
Computer Programming :
Process of planning a sequence of steps for a computer to
follow.
Computer Program :
List of instructions to be performed by a computer.
A third phase
Maintenance Phase :
1 Use :
Use the program.
2 Maintain :
Modify the program if necessary : new requirements, errors.
Problem-Solving
Analysis
and
Specification
General Solution
(Algorithm)
Implementation
Maintenance
Specific Solution
(Program)
Use
Test
Maintain
Verify
Algorithm :
Step-by-step procedure for solving a problem in a finite
amount of time.
Examples :
recipes, instructions, ...
-5-
Programming Language :
Set of rules, symbols and special words used to construct a
program.
Problem-Solving
Algorithm
Implementation
Coding
Program
Documentation :
Written text and comments that make a program easier for
others to understand, use and modify.
Development of programming languages :
Machine language
+1300042774
+1400593419
+1200274027
Assembly language
LOAD
ADD
STORE
BASEPAY
OVERPAY
GROSSPAY
Machine Language :
Language made up of binary-coded instructions, that is used
directly by the computer.
Assembly Language :
Low-level programming language in which mnemonics are
used to represent the different machine language instructions.
Assembler :
Program that translates an assembly language program into
machine code.
High-level Language :
-6-
Compiler :
Program used to translate a high-level language into machine
code.
Input = program in high-level language = source program.
Output = machine language program
= object program.
Compilation Execution
What is a Computer ?
Memory Unit :
Internal data storage in a computer (RAM).
-8-
Peripheral devices :
- additional I/O devices, secondary storage devices, ...
-9-
Problem-Solving Techniques
Ask questions :
Gather information about the problem to solve.
Solve by analogy :
Adapt solutions from similar problems.
Means-Ends analysis :
Consider the actions possible to solve the problem.
Merging solutions :
Combine existing solutions.
- 10 -
2. Introduction to C Programming
A first program in C
C code :
/* A first program in C */
main()
{
printf(Welcome to
}
C !\n);
Output :
Welcome to C !
Analysis :
/* A first program in C */
/*
main()
- 11 -
C !\n);
The right brace } indicates the end of the body of the main()
function.
- 12 -
/* declaration */
/*
/*
/*
/*
/*
prompt */
read integer1 */
promt */
read integer2 */
assignment */
/* print sum */
Output :
Enter first integer :
23
Enter second integer :
54
Sum is 77
- 13 -
Analysis :
#include <stdio.h>
This is a declaration :
- 14 -
scanf(%d, &integer1);
Assignment statement :
The expression on the right side of the assignment operator =
is computed.
The result is assigned to the variable on the left side.
= reads as gets , not equals .
Both = and + are binary operators (with two operands).
printf(Sum is %d\n, sum);
Memory Concepts
23
Arithmetic in C
C Operator
Example
x + y
t - 2
2 * Pi * Radius
x / t
a % b
34 % 7 6
Some examples :
m = (a + b + c + d + e) / 5;
m = a + b + c + d + e
5;
y = m * x + b;
z = p * r % q + w / x - y;
k = 12 * (a * (b + c) + c * (d + e))
- 17 -
Relational
>
<
C Operator
Example
==
x == y
!=
x != y
>
x > y
<
x < y
>=
x >= y
<=
x <= y
- 18 -
C code :
#include <stdio.h>
main()
{
int num1, num2;
printf(Enter two integers : );
scanf(%d%d, &num1, &num2);
if (num1 == num2)
printf(%d is equal to %d\n, num1, num2);
if (num1 != num2)
printf(%d is not equal to %d\n, num1, num2);
if (num1 < num2)
printf(%d is less than %d\n, num1, num2);
if (num1 > num2)
printf(%d is greater than %d\n, num1, num2);
if (num1 <= num2)
printf(%d is less than or equal to %d\n,
num1, num2);
if (num1 >= num2)
printf(%d is greater than or equal to %d\n,
num1, num2);
return 0;
}
Associativity
left to right
left to right
left to right
left to right
left to right
right to left
( )
*
<
<=
>
>=
== !=
=
break
continue
else
for
long
signed
switch
void
case
default
enum
goto
register
sizeof
typedef
volatile
- 20 -
char
do
extern
if
return
static
union
while
Structure :
1 Central Unit
- CPU
- Disk drives (floppy, hard, CD-Rom)
- Expansion slots (disk controller, video, I/O,
network, modem, ...)
2 Keyboard
3 Monitor
4 Mouse, scanner, digitizer, joystick, ...
5 Printer, plotter, ...
Boot :
1 Turn computer on !
2 Memory check.
3 Loading drivers (network, mouse, CD-Rom,
memory manager, ...).
4 DOS prompt or Windows.
Operating system :
Program(s) responsible for the I/O management. Provides
services to the programs and a user interface.
Examples :
MS-DOS, OS/2, Windows 3.1, Windows 95/98, Unix, ...
- 21 -
File organisation :
- Drives : refer to physical devices (diskette drive, hard disk,
CD-Rom drive, network server, ...) or logical devices (RAM
disk, ...)
Drives are named using letters :
A:
B:
C:
D:
...
TEST1.EXE
EMPLOYEE.DB
C:\DATA\SALES\REGIONAL\BRUSSELS.DAT
C:BRUSSELS.DAT
CD
MD
REN
DEL
EDIT
MEM
CHKDSK
RD
MOVE
Windows :
Control menu.
Minimize and Maximize buttons.
Resizing and deplacing.
Menus.
WIN
Using Flowcharts
false
grade = 12
print "Failed"
true
print "Passed"
- 24 -
Structured Programming
if grade 12 go to A
print Failed
go to B
A: print Passed
B: ...
if grade 12 then
print Failed`
else
print Passed
goto-less
programming
do
print Press C to continue
read character from keyboard
while character C
control structures.
- 25 -
Control Structures
Sequence, Selection and Repetition
Sequence structure :
Normal behaviour, one statement after the other in the order in
which they are written.
Selection structures :
1 Single-selection structure :
if
2 Double-selection structure :
if/else
3 Multiple-selection structure :
switch
Repetition structures :
1 while
2
do/while
for
- 26 -
The if Structure
Pseudocode :
If students grade is greater than or equal to 12
Print Passed
C code :
if (grade >= 12)
printf(Passed\n);
Pseudocode :
If students grade is greater than or equal to 12
Print Passed
else
Print Failed
C code :
if (grade >= 12)
printf(Passed\n);
else
printf(Failed\n);
- 27 -
- 28 -
- 29 -
Example :
Find the first power of 2 larger than 1000.
Pseudocode :
Set product equal to 2
while product is less than or equal to 1000
multiply product by 2
C code :
product = 2;
while (product <= 1000)
product = 2 * product;
- 30 -
Formulating algorithms - I
Problem :
The grades of a class of ten students are available. Determine
the class average.
Pseudocode :
Set total to 0.
Set grade counter to 1.
While grade counter is less than or equal to 10 :
Input the next grade.
Add the grade to the total.
Add 1 to the grade counter.
Set the class average equals to the total divided by 10.
Print the class average.
Remarks :
1 counter-controlled repetition
The number of repetitions is known (10) and is controlled by a
counter (variable).
2 initialisation of the variables.
C code :
/* Class average calculation I */
#include <stdio.h>
main()
{
int counter, grade, total, average;
- 31 -
total = 0;
counter = 1;
while (counter <= 10) {
printf(Enter grade : );
scanf(%d, &grade);
total = total + grade;
counter = counter + 1;
}
average = total / 10;
printf(Class average is %d\n, average);
return 0;
}
Remarks :
1 Integer division integer average !
2 Checking data input :
while (counter <= 10) {
grade = 21;
while (grade > 20) {
printf(Enter grade : );
scanf(%d, &grade);
}
total = total + grade;
counter = counter + 1;
}
- 32 -
Formulating algorithms - II
Problem :
Determine the class average for an arbitrary number of
students (not known in advance).
Solution :
Use a sentinel value, i.e. a special value that indicate that all
the data have been entered.
For grades, the sentinel should be outside of the 0-20 range.
When the user enters the sentinel value, the input process
stops.
Pseudocode :
Top-down approach. (stepwise refinement)
- top level : overall function of the program :
Determine the class average.
- 1st refinement : main tasks to perform :
Initialize variables.
Input, sum and count the grades.
Calculate and print the class average.
- 33 -
- 2nd refinement :
Initialize total to 0.
Initialize counter to 0.
Input the first grade.
While the user has not entered the sentinel :
Add this grade to the running total.
Add 1 to the counter.
Input the next grade.
If the counter is not equal to 0 :
Set the average equals to the total divided by the counter.
Print the average.
else :
Print No grades were entered.
Sufficient refinement for translation to C language.
C code :
/* Class average II */
#include <stdio.h>
main()
{
float average;
/* floating point data type */
int counter, grade, total;
- 34 -
total = 0;
counter = 0;
printf(Enter grade (-1 to end) : );
scanf(%d, &grade);
while (grade != -1) {
total = total + grade;
counter = counter + 1;
printf(Enter grade (-1 to end) : );
scanf(%d, &grade);
}
if (counter != 0) {
average = (float) total / counter; /*type cast*/
printf(Class average is %.2f\n, average);
}
else
printf(No grades were entered.\n);
return 0;
}
Remarks :
1 New data type, for floating point (real) numbers.
2 Type cast to ensure that average is computed correctly.
3 Conversion specifier %.2f prints a floating point value with
two decimal digits to the right of the decimal point.
- 35 -
Problem :
We have to analyze the results of a test for a group of 10
students, as follows :
1. Input the results (either 1: passed or 2: failed).
2. Count the number of results of each type.
3. Display a summary of the results : number of students who
passed and number of students who failed.
4. If more than 8 students passed, print a warning message.
Remarks :
1. 10 students counter-controlled loop.
2. Data are either 1 or 2.
3. Two counters needed : passes and failures.
- 36 -
C code :
/* Test results analysis */
#include <stdio.h>
main()
{
int passes = 0, failures = 0, student = 1, result;
while (student <= 10) {
printf(Enter result (1:pass, 2:fail) : );
scanf(%d, &result);
if (result == 1)
passes = passes + 1;
else
failures = failures + 1;
student = student + 1;
}
printf(Passed : %d\n, passes);
printf(Failed : %d\n, failures);`
if (passes > 8)
printf(Course too easy!\n);
return 0;
}
Remark :
Variables can be initialized whithin the declaration statement.
- 38 -
First example :
x = x + 5
Advantage : faster.
Second example :
x = x + 1
x += 5
-=
*=
/=
%=
x++
or
++x
(--x)
(x--)
Examples :
x = 2;
printf(%d\n,
printf(%d\n,
printf(%d\n,
y = x-- + 2;
printf(%d\n,
printf(%d\n,
x++);
x);
++x);
Output :
2
3
4
y);
x);
6
3
y = ++x + 2 * x;
- 39 -
4. Program Control
Repetition Structures :
Counter-controlled vs Sentinel-controlled
Counter-controlled repetition :
- definite repetition : number of iterations known in advance,
- use of a counter variable that is incremented at each
iteration.
Sentinel-controlled repetition :
- indefinite repetition : number of iterations not known in
advance,
- use of a sentinel value that indicates the end of the data.
- 40 -
Counter-controlled repetition
Requires :
1 A control variable,
2 The initial value of the conrol variable,
3 The increment (decrement) of the control variable at each
iteration,
4 The condition that tests for the final value of the control
variable.
Example :
/* Prints numbers from 1 to 10 */
#include <stdio.h>
main()
{
int counter = 1; /* control var. decl. & init. */
while (counter <= 10) {
/* condition */
printf("%d\n", counter);
++counter;
/* increment */
}
return 0;
}
Remarks :
1 Variables can be initialized within their declaration.
2 More concise form :
#include <stdio.h>
main()
{
int counter = 0;
while (++counter <= 10)
printf("%d\n", counter);
return 0;
}
- 41 -
The
for
Repetition Structure
(mostly) equivalent to :
initialization;
while (condition) {
loop_body;
increment;
}
Example :
/* Prints numbers from 1 to 10 */
#include <stdio.h>
main()
{
int counter;
for (counter = 1; counter <= 10; counter++)
printf("%d\n", counter);
return 0;
}
Remarks :
1 The three expression in the for structure are optional.
2 Multiple, comma-separated, expressions can be used as
initialization and increment.
3 The increment may be negative (decrement).
- 42 -
4 Flowchart :
initialization
condition
true
loop_body
false
is equivalent to :
for (j = 2; j <= 80; j += 5)
printf("%d\n");
4 From 7 to 77 in steps of 7 :
for (i = 7; i <= 77; i += 7)
- 43 -
increment
5 From 20 to 2 in steps of 2 :
for (i = 20; i >= 2; i -= 2)
equivalent to :
int sum, number;
for (sum = 0, number = 2; number <= 100;
sum += number, number += 2);
Output :
Year
1
2
3
4
5
6
7
8
9
10
Amount on deposit
1050.00
1102.50
1157.62
1215.51
1276.28
1340.10
1407.10
1477.46
1551.33
1628.89
Remarks :
1 Library math.h : includes function pow :
pow(a, b) returns a to the power b where a and b are double.
2 double : floating-point data type with higher precision than
float.
3 Both arguments of pow are of type double and year is of
type int. Automatically converted.
4 Would be better to use int for monetary amounts
(precision).
- 45 -
Computers memory :
Sequence of storage places. To each place is associated an
address (index).
1
15
16
10
17
18
H
e
25
26
27
28
2.357412e012
19
l
29
20
l
30
137
11
12
13
14
21
o
22
23
24
base 2
digits 0-1
235 = 111010112 =
127 + 126 + 125 + 024 + 123 + 022 + 121 + 120
- 46 -
base 8
digits 0-7
32
16
255
32
16
- on 2 bytes :
...
...
...
...
...
1024
...
...
...
...
1024
32
16
64
32
16
65535
64
C Data types :
Type
16-bit
32-bit
Bytes
Range
Bytes
Range
unsigned
char
char
0 to 255
0 to 255
-128 to 127
-128 to 127
short int
-32768 to 32767
-32768 to 32767
unsigned int
0 to 65535
0 to 4294967295
int
-32768 to 32767
-2147483648 to 2147483647
enum
-32768 to 32767
-2147483648 to 2147483647
unsigned
long
long
0 to 4294967295
0 to 4294967295
-2147483648 to 2147483647
-2147483648 to 2147483647
float
double
long double
10
10
near (pointer)
far (pointer)
- 48 -
The
do/while
Repetition Structure
Syntax :
do {
loop_body;
} while (condition);
- 49 -
The
switch
Multiple-Selection Structure
printf(A:
printf(B:
printf(C:
printf(D:
printf(F:
%d\n,
%d\n,
%d\n,
%d\n,
%d\n,
aCount);
bCount);
cCount);
dCount);
fCount);
return 0;
}
Remarks :
- Multiple-selection according to the value of an integer (or
character) expression.
- getchar() reads one character from the keyboard and returns
it. Characters are read one at a time after the user presses the
Enter key. Different from scanf : one character at a time,
including blanks, newline , ...
- Characters correspond to 1-byte integers can be used
either way :
gotos
and labels :
i = 0;
again:
printf(%d\n, i++);
if (i <= 10) goto again;
- 51 -
The
break
and
continue
Statements
== %d\n, x);
#include <stdio.h>
main()
{
int x;
for (x = 1; x <= 10; x++) {
if (x == 5)
continue;
printf(%d , x);
}
printf (\Used continue to skip printing 5\n);
return 0;
}
- 52 -
Logical Operators
AND, OR and NOT
Operator :
in C :
AND
OR
NOT
&&
||
A && B
0
0
0
0
0
0
0
0
0
0
0
1
A || B
0
0
0
0
0
1
1
1
0
0
0
Examples :
if (gender ==1 && age >= 65)
++seniorFemales;
if semesterAverage >= 90 || finalExam >= 90)
printf(Student grade is A\n);
if (!(grade == sentinelValue))
printf(The next grade is %f\n, grade);
which is equivalent to :
if (grade != sentinelValue)
printf(The next grade is %f\n, grade);
- 53 -
Associativity
left to right
right to left
left to right
left to right
left to right
left to right
left to right
left to right
right to left
right to left
left to right
( )
++
--
-(unary)
*
<
(type)
<=
>
>=
== !=
&&
||
?:
=
+=
-=
*=
/=
%=
Caution:
Confusing == (equality) and
Example 1 :
if (payCode == 4)
printf(You get a bonus !);
if (payCode = 4)
printf(You get a bonus !);
Example 2 :
x = 1;
x == 1;
- 54 -
(assignment)
5. Functions
In C :
Functions
- Standard functions :
printf
scanf
getchar
Function call :
- Specifies the function name as well as arguments
(information that is passed to the function).
printf(%d, number);
pow(2.5, 2);
Local variables :
Variables that are declared within a function. They are known
only within the function.
- 55 -
Header file :
#include <math.h>
Description
square root of x
exponential
log(x)
natural logarithm
log10(x)
base 10 logarithm
fabs(x)
absolute value
ceil(x)
smallest integer x
floor(x)
largest integer x
pow(x,y)
x raised to power y
fmod(x,y)
remainder of x / y
sine of x (radians)
cosine of x
tangent of x
sin(x)
cos(x)
tan(x)
- 56 -
Example
sqrt(25.0) : 5.0
exp(1.0) : 2.718282
exp(2.0) : 7.389056
log(2.718282) : 1.0
log(7.389056) : 2.0
log10(1.0)
: 0.0
log10(10.0) : 1.0
log10(100.0) : 2.0
fabs(12.5) : 12.5
fabs(-5.0) : 5.0
ceil(7.3) : 8.0
ceil(-1.5) : -1.0
floor(7.3) : 7.0
floor(-1.5) : -2.0
pow(4, 3)
: 64.0
pow(9, 0.5) : 3.0
fmod(14, 2.5) : 1.5
sin(0.0) : 0.0
cos(0.0) : 1.0
tan(0.0) : 0.0
Function Definition
Example 1 :
/* Prints the squares of integers 1 to 10 */
#include <stdio.h>
int square(int);
/* function prototype */
main()
/* main function */
{
int x;
for (x=1; x <= 10; x++)
printf(%d , square(x));
printf(\n);
return 0;
}
int square(int y)
{
/* function definition */
return y * y;
}
2 parts :
1 Function prototype : useful for checking syntax,
2 Function defintion : general format :
return_value_type function_name(parameter_list)
{
declarations
statements
}
- 57 -
Function definition :
- function_name is any valid identifier.
- return_value_type indicates the data type of the result
returned to the caller. Two special cases :
- void indicates that no value is returned by the function,
- int is assumed if no return_value_type is specified.
- parameter_list is a comma-separated list containing the
declarations of the parameters :
- each parameter is declared separately (type),
- void is used if there are no parameters,
- int is assumed if no type is specified.
- The braces determine the function body. It is a block
(compound statement including declarations).
Function call :
- Using the function_name followed by a comma-separated
list of arguments.
- A copy of the actual arguments value is passed to the called
function and is associated to the corresponding parameter in
the function The actual argument value cannot be
modified by the function (security: avoid side effects).
Example of potential side effect :
int ipower(int a, int b) /* computes a to the power b */
{
int c = a;
while (b > 1) {
c *= a;
b--;
}
return c;
}
- 58 -
Example 2 :
/* Finds the maximum of three integers */
#include <stdio.h>
int maximum(int, int, int); /* prototype */
main()
{
int a, b, c;
printf(Enter three integers : );
scanf(%d%d%d, &a, &b, &c);
printf(The maximum is : %d\n, maximum(a, b, c));
return 0;
}
int maximum(int x, int y, int z)
{
int max = x;
if (y > max)
max = y;
if (z > max)
max = z;
return max;
}
- 59 -
Coercion of arguments :
- Example : math function expect double arguments,
but sqrt(4) is still valid and returns 2.0 : the integer value is
first converted to double.
- Type conversions should be done according to C promotion
rules to avoid the loss of data : toward highest level.
int
double : OK
int : truncation !
- From highest to lowest type :
double
Data Type
in printf :
in scanf :
long double
double
float
unsigned long int
long int
unsigned int
int
short
char
%Lf
%f
%f
%lu
%ld
%u
%d
%hd
%c
%Lf
%lf
%f
%lu
%ld
%u
%d
%hd
%c
Header files :
Contains the function prototypes of all the functions in a
library, as well as data types and constants definitions.
Description
Character handling functions
Floating point size limits
Integer size limits
Math library functions
Standard I/O functions
Conversions text/numbers, ...
String processing functions
Time and date functions
ctype.h
float.h
limits.h
math.h
stdio.h
stdlib.h
string.h
time.h
Call by value :
A copy of the argument's value is passed to the called
function. Changes made to the copy do not affect the original
variable's value. No side effects.
Call by reference :
- 61 -
In C :
Always call by value.
But call by reference can be simulated : Cf. arrays and
pointers.
- 62 -
Example 2 :
#include <stdio.h>
#include <stdlib.h>
main()
{
int face, roll, frequency1 = 0, frequency2 = 0,
frequency3 = 0, frequency4 = 0,
frequency5 = 0, frequency6 = 0;
for (roll = 1; roll <= 6000; roll++) {
face = 1 + rand() % 6;
switch (face) {
case 1:
++frequency1;
break;
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
case 4:
++frequency4;
break;
case 5:
++frequency5;
break;
case 6:
++frequency6;
break;
}
}
printf("%s%13s\n", "Face", "Frequency");
printf("
1%13d\n", frequency1);
printf("
2%13d\n", frequency2);
printf("
3%13d\n", frequency3);
printf("
4%13d\n", frequency4);
printf("
5%13d\n", frequency5);
printf("
6%13d\n", frequency6);
return 0;
- 63 -
Pseudo-random numbers :
- Each time Example 2 is run, it generates the same sequence
of random numbers.
- Pseudo-random numbers are actually computed, using an
appropriate recurrence formula, so that they appear to be
random.
- The sequence of numbers generated can be changed by
modifying the seed of the generator : using the srand function.
- Important to be able to reproduce a given situation for
debugging a program.
- To produce a different sequence of numbers each time the
program is run :
srand(time(NULL));
- 64 -
Rules :
The player rolls two dices.
If the sum of the points obtained is 7 or 11, the player wins.
If the sum is 2, 3 or 12, the player loses.
In all other cases, the sum becomes the point of the player.
The player rolls the two dices until either he obtains his point
(win) or obtains a 7 (lose).
C program :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int rollDice(void);
main()
{
int gameStatus, sum, point;
srand(time(NULL));
sum = rollDice();
switch(sum) {
case 7: case 11:
gameStatus = 1; /* win */
break;
case 2: case 3: case 12:
gameStatus = 2; /* lose */
break;
default:
gameStatus = 0;
point = sum;
printf(Point is %d\n", point);
break;
}
while (gameStatus == 0) {
- 65 -
sum = rollDice();
if (sum == point)
gameStatus = 1; /* win */
else
if (sum == 7)
gameStatus = 2; /* lose */
}
if (gameStatus == 1)
printf(Player wins\n");
else
printf(Player loses\n");
return 0;
}
int rollDice(void)
{
int die1, die2, locSum;
die1 = 1 + rand() % 6;
die2 = 1 + rand() % 6;
locSum = die1 + die2;
printf(Player rolled %d + %d = %d\n", die1, die2,
locSum);
return locSum;
}
- 66 -
Storage Classes
extern
static
register
Automatic storage duration : auto
- Variables created when the block in which they are declared
is entered, and destroyed when the block is exited.
- Local variables are are automatic by default (hence auto is
rarely used).
- register asks the compiler to store a variable in a high
speed processor register (if possible). Becomes unnecessary
with modern optimizing compilers.
- 67 -
extern
static
Static storage duration :
- Variables that exist during the whole execution of the
program.
- static is used with local variables :
void printCounter(void)
{
static int count = 1;
printf(Call number %d\n", count++);
}
Scope Rules
Example :
#include <stdio.h>
void a(void);
void b(void);
void c(void);
int x = 1;
main()
{
int x = 5
/* global variable */
/* local variable */
- 69 -
Recursion
Principle :
- A general problem has to be solved.
- The solution is known for the simplest case(s) (base case(s)).
- The problem can be divided into two sub-problems : one
(simple) whose solution is known and another one that cannot
be solved directly but is a simpler version of the original
problem.
- 70 -
Example 2 :
The Fibonacci series.
0
1
1
2
3
5
8
13 21 34 ...
- Starts with 0 and 1.
- Each subsequent number in the series is the sum of the two
previous ones.
#include <stdio.h>
long fibonacci(long);
main()
{
long result, number;
printf(Enter an integer : );
scanf(%ld, &number);
result = fibonacci(number);
printf(Fibonacci(%ld) = %ld\n", number, result);
return 0;
}
long fibonacci(long n)
{
if (n == 0 || n == 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
- 71 -
6. Arrays
Array :
- Data structure consisting of related data items of the same
type.
- A sequence of memory locations that are accessed using the
same name and that can contain the same type of data.
- Each location is accessed by specifying its position number
in the array (starting with 0).
Using arrays :
C[0]
34
C[1]
C[2]
-1
C[3]
-2
C[4]
12
C[5]
-1
C[6]
28
C[7]
C[8]
11489
C[9]
C[10]
C[11]
52
name[subscript_expression]
printf(%d\n, c[3]);
c[10] = 45;
c[n + 1] = 0;
for (i=0; i < 12; i++)
printf(%d , c[i]);
- 72 -
Declaring arrays :
element_type array_name[number_of_elements];
Examples :
int c[12];
int b[100], x[27];
Initializing an array :
- using a for loop :
#include <stdio.h>
main()
{
int n[10], i;
for (i = 0; i < 10; i++)
n[i] = 0;
printf(%s%13s\n, Element, Value);
for (i = 1; i < 10; i++)
printf(%7d%13d\n, i, n[i]);
return 0;
}
- also :
- 73 -
- 74 -
Remarks :
- Element number 0 of array frequency is not used.
- No array bounds checking potential errors !
- 75 -
- 76 -
Character arrays
- 77 -
Example :
#include <stdio.h>
main()
{
char string1[20], string2[] = Good bye !;
int i;
printf(Enter a string : );
scanf(%s, string1);
printf(string1 is : %s\nstring2 is : %s\n
string1 with spaces :\n,
string1, string2);
for (i = 0; string1[i] != \0; i++)
printf(%c , string1[i]);
printf(\n);
return 0;
}
A typical run :
Enter a
string1
string2
string1
H e l l
Static Arrays
- 78 -
Example :
int hourlyTemperatures[24];
...
modifyArray(hourlyTemperatures, 24);
Output :
array = FFF0
&array[0] = FFF0
Function header :
void modifyArray(int b[], int size)
Function prototype :
void modifyArray(int [], int);
- 79 -
Example :
#include <stdio.h>
#define SIZE 5
void modifyArray(int [], int);
void modifyElement(int);
main()
{
int a[SIZE] = {0, 1, 2, 3, 4};
int i;
printf(Original array:\n);
for (i = 0; i < SIZE; i++)
printf(%3d, a[i]);
printf(\n);
modifyArray(a, SIZE);
printf(Modified array:\n);
for (i = 0; i < SIZE; i++)
printf(%3d, a[i]);
printf(Original value of a[3]: %d\n, a[3]);
modifyElement(a[3]);
printf(Modified value of a[3]: %d\n, a[3]);
return 0;
}
void modifyArray(int b[], int size)
{
int j;
for (j = 0; j < size; j++)
b[j] *= 2;
}
void modifyElement(int e)
{
printf(Value in modifyElement: %d\n, e *= 2);
}
- 80 -
Using const :
Prevents the modification of array values in a function.
makes the array a constant in the function body,
any attempt to modifiy an element of the array results in a
compile time error.
Example :
#include <stdio.h>
void tryToModifyArray(const int []);
main()
{
int a[] = {10, 20, 30};
tryToModifyArray(a);
printf(%d %d %d\n, a[0], a[1], a[2]);
return 0;
}
void tryToModifyArray(const int b[])
{
b[0] /= 2;
/* error ! */
b[1] /= 2;
/* error ! */
b[2] /= 2;
/* error ! */
}
- 81 -
Sorting Arrays
Principle :
1 Find the smallest (largest) component in the list and
exchange it with the first component.
2 Repeat the procedure with the remaining components
(starting with the second one), until all are ordered.
void exchangeSort(int a[], int size)
{
int hold, pass, place, minIndex;
for (pass = 0; pass < size - 1; pass++)
{
minIndex = pass;
for (place = pass + 1; place < size; place++)
if (a[place] < a[minIndex])
minIndex = place;
hold = a[minIndex];
a[minIndex] = a[pass];
a[pass] = hold;
}
}
- 82 -
- 83 -
Searching Arrays
Linear search :
Compare sequentially each element of the array with the key.
#include <stdio.h>
#define SIZE 100
int linearSearch(int [], int, int);
main()
{
int a[SIZE], x, searchKey, element;
for (x = 0; x < SIZE; x++)
a[x] = 2 * x;
printf(Enter search key: );
scanf (%d, &searchKey);
element = linearSearch(a, searchKey, SIZE);
if (element == -1)
printf(Value not found !\n);
else
printf(Value found at position: %d\n, element);
return 0;
}
- 84 -
- 85 -
#include <stdio.h>
#define SIZE 100
int binarySearch(int [], int, int);
main()
{
int a[SIZE], x, searchKey, element;
for (x = 0; x < SIZE; x++)
a[x] = 2 * x;
printf(Enter search key: );
scanf (%d, &searchKey);
element = binarySearch(a, searchKey, SIZE);
if (element == -1)
printf(Value not found !\n);
else
printf(Value found at position: %d\n, element);
return 0;
}
int binarySearch(int array[], int key, int size)
{
int low, high, middle;
low = 0;
high = size - 1;
while (low <= high) {
middle = (low + high) / 2;
if (key == array[middle])
return middle;
else if (key < array[middle])
high = middle - 1;
else
low = middle + 1;
}
return -1;
}
- 86 -
Multiple-Subscripted Arrays
Two-dimensional arrays :
Useful for representing tables.
Example : Integer array a with three rows and four columns :
Column 0
Column 1
Column 2
Column 3
a[0][0]
a[0][1]
a[0][2]
a[0][3]
a[1][0]
a[1][1]
a[1][2]
a[1][3]
a[2][0]
a[2][1]
a[2][2]
a[2][3]
a[0][0]
a[0][1]
a[0][2]
a[1][0]
a[1][1]
a[1][2]
a[1][3]
a[2][1]
a[2][2]
a[2][3]
Row 0
Row 1
Row 2
Storage in memory :
a
a[0]
a[1]
a[0][3]
a[2]
a[2][0]
Declaration :
int a[3][4];
Initialization :
int
int
int
int
b[2][2]
c[2][2]
d[2][2]
e[2][2]
=
=
=
=
Example 1 :
#include <stdio.h>
void printArray(int [][3]);
main()
{
int array1[2][3] = { {1, 2, 3}, {4, 5, 6} },
array2[2][3] = { 1, 2, 3, 4, 5 },
array3[2][3] = { {1, 2}, {4} };
printf(array1:\n);
printArray(array1);
printf(array2:\n);
printArray(array2);
printf(array3:\n);
printArray(array3);
return 0;
}
void printArray(int a[][3])
{
int i, j;
for (i = 0; i <= 1; i++) {
for (j = 1; j <= 2; j++)
printf(%d , a[i][j]);
printf(\n);
}
}
- 88 -
Example 2 :
#include <stdio.h>
#define STUDENTS 3
#define EXAMS 4
int minimum(int [][EXAMS], int, int);
int maximum(int [][EXAMS], int, int);
float average(int [], int);
void printArray(int [][EXAMS], int, int);
main()
{
int student,
studentGrades[STUDENTS][EXAMS] =
{{77, 68, 86, 73},
{96, 87, 89, 78},
{70, 90, 86, 81}};
printf(The array is:\n);
printArray(studentGrades, STUDENTS, EXAMS);
printf(\n\nLowest grade: %d\nHighest grade: %d\n,
minimum(studentGrades, STUDENTS, EXAMS),
maximum(studentGrades, STUDENTS, EXAMS));
for (student = 1; student < STUDENTS; student++)
printf(Average grade for student %d : %.2f\n,
student,
average(studentGrades[student], EXAMS));
return 0;
}
int minimum(int grades[][EXAMS], int pupils, int tests)
{
int i, j, lowGrade = 100;
for (i = 0; i < pupils; i++)
for (j = 0; j < tests; j++)
if (grades[i][j] < lowGrade)
lowGrade = grades[i][j];
return lowGrade;
}
int maximum(int grades[][EXAMS], int pupils, int tests)
- 89 -
{
int i, j, highGrade = 100;
for (i = 0; i < pupils; i++)
for (j = 0; j < tests; j++)
if (grades[i][j] > highGrade)
highGrade = grades[i][j];
return highGrade;
}
float average(int setOfGrades[], int tests)
{
int i, total = 0;
for (i = 0; i < tests; i++)
total += setOfGrades[i];
return (float) total / tests;
}
void printArray(int grades[][EXAMS], int pupils,
int tests)
{
int i, j;
printf(
[0] [1] [2]
for (i = 0; i < pupils; i++) {
printf(\nstudentGrades[%d] ,i);
for (j = 0; j < tests; j++)
printf(-5d, grades[i][j]);
}
}
- 90 -
[3]);
7. Pointers
Pointer Variables
&countPtr
&count
312412
432180
432180
......
Initialisation :
Either to 0 to NULL (defined in stdio.h) or to a valid address.
- 91 -
Example :
#include <stdio.h>
main()
{
int a, *aPtr;
a = 7;
aPtr = &a;
printf(Address of a
printf(Value of aPtr
printf(Value of a
printf(Value of *aPtr
:
:
:
:
%p\n,
%p\n,
%d\n,
%d\n,
&a);
aPtr);
a);
*aPtr);
return 0;
}
Output :
Address of a
Value of aPtr
Value of a
Value of *aPtr
:
:
:
:
FFF4
FFF4
7
7
- 92 -
Example 1 :
- call by value :
#include <stdio.h>
int cubeByValue(int);
main()
{
int number = 5;
number = cubeByValue(number);
printf(Cube is : %d\n, number);
return 0;
}
int cubeByValue(int n)
{
return n * n * n;
}
- call by reference :
#include <stdio.h>
void cubeByReference(int *);
main()
{
int number = 5;
cubeByReference(&number);
printf(Cube is : %d\n, number);
return 0;
}
void cubeByReference(int *nPtr)
{
*nPtr = *nPtr * *nPtr * *nPtr;
}
- 93 -
- 94 -
Remarks :
- use of *array instead of array[] : equivalent, array = pointer
to first element of the array
- prototype of swap inside bubbleSort : restricts proper calls of
the function to those made from bubbleSort.
--
Examples :
+=
-=
/* or vPtr = v; */
vPtr += 2;
vptr--;
/* subtracts 1 * 4 to vPtr */
Example 1 :
int b[5], *bPtr;
bPtr = b;
/* or bPtr = &b[0]; */
...
*(b + 3)
...
bPtr[1]
/* equivalent to b[1] */
...
b += 3;
/* invalid */
Example 2 :
#include <stdio.h>
main()
{
int i, offset, b[] = {10, 20, 30, 40};
int *bPtr = b;
printf(Using subscript notation :\n);
for (i = 0; i <= 3; i++)
printf(b[%d] = %d\n, i, b[i]);
printf(Using pointer/offset notation with b :\n);
for (offset = 0; offset <= 3; offset++)
printf(*(b + %d) = %d\n, offset, *(b + offset));
printf(Using pointer subscript notation :\n);
for (i = 0; i <= 3; i++)
printf(bPtr[%d] = %d\n, i, bPtr[i]);
printf(Using pointer/offset notation :\n);
for (offset = 0; offset <= 3; offset++)
printf(*(bPtr + %d) = %d\n, offset,
*(bPtr + offset));
return 0;
}
- 96 -
Example 3 :
Copying strings.
#include <stdio.h>
void copy1(char *, const char *);
void copy2(char *, const char *);
main()
{
char string1[10], *string2 = Hello,
string3[10], string4[10] = Good Bye;
copy1(string1,string2);
printf(string1 = %s\n, string1);
copy2(string3,string4);
printf(string3 = %s\n, string3);
return 0;
}
void copy1(char *s1, const char *s2);
{
/* array notation */
int i;
for (i = 0; s1[i] = s2[i]; i++) ;
}
void copy2(char *s1, const char *s2);
{
/* pointer notation */
for ( ; *s1 = *s2; s1++, s2++) ;
}
Remarks :
- use of const,
- use of the null string termination character.
- 97 -
\n
#include <ctype.h>
Strings
123.45
In C :
- Array of characters, ending with the null character (\0).
- Accessed using a pointer to the first character.
- Value of a string = address of its first character.
- 98 -
Example 1 :
#include <stdio.h>
main()
{
char sentence[80];
void reverse(char *);
printf(Enter a line of text:\n);
gets(sentence);
printf(\Line printed backwards:\n);
reverse(sentence);
return 0;
}
void reverse(char *s)
{
if (s[0] == \0)
return;
else {
reverse(&s[1]);
putchar(s[0]);
}
}
- 99 -
Example 2 :
#include <stdio.h>
main()
{
char c, sentence[80];
int i = 0;
puts(Enter a line of text:);
while ((c = getchar()) != \n)
sentence[i++] = c;
sentence[i] = \0;
puts(The line entered was:)
puts(sentence);
return 0;
}
- 100 -
9. Formatted Input/Output
- 101 -
Whats Next ?
File processing.
Data structures :
- Linked Lists,
- Stacks,
- Queues,
- Trees, ...
- 102 -