Algorithm&CProgramming Chap 1&2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

i

ALGORITHMIC; C
PROGRAMMING AND
DATA STRUCTURES

M. Sc. Jean Sylvain BUCUMI

Bujumbura International University

Email : bjsylva@gmail.com
jean-sylvain.bucumi@ub.edu.bi
Phone: +257 71 017 262
+257 75 964 441
+257 69 686 003

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


ii

Contents

Chapter I: Background on Algorithms

Chapter II: Basics of Procedural Programming

Chapter III: Control structures

Chapter IV: Functions and Procedures

Chapter V: Structures

Chapter VI: Array

Chapter VII: Linked Lists

Chapter III: Queues

Chapter IX: Stacks

Chapter X: Trees (Binary)

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


iii

TABLE OF CONTENTS

Contents ................................................................................................................................................... ii
TABLE OF CONTENTS ....................................................................................................................... iii
Chapter I: Background on Algorithms .................................................................................................... 1
I.1 Introduction .................................................................................................................................... 1
I.2 Caracteristics of an algorithm ........................................................................................................ 1
I.3 How to design an algorithm ........................................................................................................... 2
I.4 Structure of an algorithm ............................................................................................................... 2
I.5 Inputs/Outputs ................................................................................................................................ 2
I.6 Variables ........................................................................................................................................ 3
I.6.1 Variables of simple types ........................................................................................................ 3
I.6.2 Variables of complex types ..................................................................................................... 4
I.7 Determination of variables ............................................................................................................. 4
I.8 Operators ........................................................................................................................................ 5
I.9 Applications ................................................................................................................................... 5
Chapter II: BASES OF PROCEDURAL PROGRAMMING ................................................................. 6
II.1 Introduction................................................................................................................................... 6
II.2 Some programming forms ............................................................................................................ 6
II.3 C language program ...................................................................................................................... 6
II.4 Structure of a C program .............................................................................................................. 7
II.5 Steps for running a C program ...................................................................................................... 7
II.6 Creation of a project ..................................................................................................................... 7
II.7 Variables ....................................................................................................................................... 8
II.8 Display and input .......................................................................................................................... 8
II.9 Operators....................................................................................................................................... 9
II.10 Application exercises .................................................................................................................. 9
Chapter III: CONTROL STRUCTURES .............................................................................................. 10
III.1 Introduction ............................................................................................................................... 10
III.2 Conditional control structures ................................................................................................... 10
III.2.1 IF – ELSE ........................................................................................................................... 10
III.2.2 SWITCH - CASE ............................................................................................................... 11
III.3 Repetitive control structures ...................................................................................................... 11
III.3.1 For ...................................................................................................................................... 12
III.3.2 Do-while ............................................................................................................................. 12
III.3.3 While .................................................................................................................................. 13

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


iv

III.4 Application exercises ................................................................................................................ 13


Chapitre IV : FUNCTIONS ET PROCEDURES .................................................................................. 15
IV.1 Introduction ............................................................................................................................... 15
IV.2 Definitions ................................................................................................................................. 15
IV.3 Simple Functions (procedures).................................................................................................. 15
IV.3.1 Structure of a function (procedure) .................................................................................... 15
IV.3.2 Using a function (procedure).............................................................................................. 16
IV.3 Recursive functions (procedures) .............................................................................................. 17
Chapter V : STRUCTURES .................................................................................................................. 18
V.1 Introduction ................................................................................................................................ 18
V.2 Definition.................................................................................................................................... 18
V.3 Use and access ............................................................................................................................ 18
V.4 Dynamic allocation ..................................................................................................................... 18
V.5 Application exercises.................................................................................................................. 19
Chapter VI : ARRAYS .......................................................................................................................... 20
VI.1 Definition .................................................................................................................................. 20
VI.2 Structure of a table .................................................................................................................... 20
VI.3 Access ....................................................................................................................................... 20
VI.4 Panel operations ........................................................................................................................ 20
VI.4.1 Display values from array .................................................................................................. 20
VI.4.2 Filling values in the array ................................................................................................... 21
VI.4.3 Occurrences in an array ...................................................................................................... 21
VI.4.4 Existence in an array .......................................................................................................... 21
VI.4.5 Elements fulfilling a condition in an array ......................................................................... 21
VI.4.6 Small / large value in a table .............................................................................................. 21
VI.4.7 Sum / average of a table ..................................................................................................... 21
VI.4.8 Sorting an array .................................................................................................................. 22
VI.5 Advantages and drawback ......................................................................................................... 22
VI.6 Exercises ................................................................................................................................... 22
Chapter VII : Linked Lists..................................................................................................................... 24
VII.1 Definition ................................................................................................................................. 24
VII.2 Advantages and drawback ....................................................................................................... 24
VII.3 Modeling .................................................................................................................................. 24
VII.4 Remind on pointers and structures........................................................................................... 25
VII.5 List operations.......................................................................................................................... 26
VII.5.1 Initialize a list .................................................................................................................... 26
VII.5.2 Content of a pointer .......................................................................................................... 26

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


v

VII.5.3 Allocating a Cell ............................................................................................................... 26


VII.5.4 Releasing a Cell ................................................................................................................ 26
VII.5.5 Check if the list is empt .................................................................................................... 27
VII.5.6 Prepare a Cell .................................................................................................................... 27
VII.5.7 Search for a Cell................................................................................................................ 27
VII.5.8 Inserting a Cell .................................................................................................................. 27
VII.5.9 Delete a Cell ...................................................................................................................... 27
VII.5.10 Add at the top of the list .................................................................................................. 27
VII.5.11 Add at the bottom of the list ........................................................................................... 27
VII.5.12 Remove the head of the list ............................................................................................. 27
VII.5.13 Top item .......................................................................................................................... 27
VII.5.14 Item at the bottom of the list ........................................................................................... 27
VII.5.15 Display the list ................................................................................................................ 28
VII.6. Exercise ................................................................................................................................... 28
Chapter VIII: QUEUES......................................................................................................................... 29
VIII.1 Definition................................................................................................................................ 29
VIII.2 Advantages, drawbacks and use of queues ............................................................................. 29
VIII.3 Queues modeling .................................................................................................................... 29
VIII.4 Queue Operations ................................................................................................................... 29
IX.4.1 Initialize a queue ................................................................................................................ 29
IX.4.2 Check if queue is empty ..................................................................................................... 29
IX.4.3 Find the element at the top of the queue ............................................................................ 30
IX.4.4 Add an item in the queue.................................................................................................... 30
IX.4.5 Remove an element of the Queue....................................................................................... 30
Chapter IX: STACKS ............................................................................................................................ 31
IX.1 Definition .................................................................................................................................. 31
IX.2 Advantages, drawbacks and use of stacks ................................................................................. 31
IX.3 Stacks modeling ........................................................................................................................ 31
IX.4 Stacks Operations ...................................................................................................................... 31
IX .4 .1 I nitialize a stack ............................................................................................................... 31
IX .4.2 Check if a stack is empty................................................................................................... 31
IX.4.3 Find the element on top of a stack ...................................................................................... 31
IX.4.4 Add an element in the stack ............................................................................................... 32
IX.4.5 Removing an item from the stack....................................................................................... 32
Chapter X: BINARY TREES ................................................................................................................ 33
X.1 Definition.................................................................................................................................... 33
X.2 Structure ..................................................................................................................................... 33

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


vi

X.3 Advantages, drawbacks and use ................................................................................................. 33


X.4 Tree terminology ........................................................................................................................ 33
X.5. Measuring a tree ........................................................................................................................ 34
X.6 Browser of a tree ........................................................................................................................ 34
X.6.1 Prefixed route ...................................................................................................................... 34
X.6.2 In-fixed route ....................................................................................................................... 34
X.6.3 Post-fixed route ................................................................................................................... 34
X.7 Tree operations ........................................................................................................................... 34
X.7.1. Initializing a tree ................................................................................................................. 35
X.7.2 Prepare a node ..................................................................................................................... 35
X.7.3 Add a node ........................................................................................................................... 35
X.7.4 Add an element .................................................................................................................... 35
X.7.5 Check if an element exists ................................................................................................... 35
X.7.6 Extract the maximum........................................................................................................... 35
X.7.7 Delete a root ........................................................................................................................ 35
X.7.8 Extract an element ............................................................................................................... 35

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


1

Chapter I: Background on Algorithms


I.1 Introduction
Computing is a science of automatic information processing.
It is a science that processes data from different fields and deemed useful to be managed
reliably and quickly.
Data can be a numeric value or characters representing information from a domain.
Information is a knowledge associated with data and having importance in the studied field.
This automatic processing is carried out by computers composed of 2 main parts: hardware
and software.
The software part is composed of a set of computer programs responsible for processing the
data. These programs are designed using algorithms for solving problems by automatic
information processing.
An algorithm means « a process or set of rules to be followed in the calculation or other
problem-solving operations ». It refers to a set of rules/instructions that step-by-steps define
how a work is to be executed upon in order to get the expected results.
An algorithm is a paper resolution of a problem (written in natural language) that will be
executed by the computer after being translated into one of the programming languages. The
algorithm is the logic of programming.

We can have multiple algorithms to solve the same problem and an algorithm can be
implemented in different programming languages. The faster algorithm is the one which takes
least space and time to execute.

I.2 Caracteristics of an algorithm


In order for some instructions to be an algorithm, it must have the following characteristics:
• Clear and Unambiguous: Algorithm should be clear and unambiguous. Each of its
steps should be clear in all aspects and must lead to only one meaning.
• Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined
inputs.
• Well-Defined Outputs: The algorithm must clearly define what output will be yielded
and it should be well-defined as well.
• Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite loops
or similar.
• Feasible: The algorithm must be simple, generic and practical, such that it can be
executed upon will the available resources. It must not contain some future
technology, or anything.

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


2

• Language Independent: The Algorithm designed must be language-independent, i.e.


it must be just plain instructions that can be implemented in any language, and yet the
output will be same, as expected.

I.3 How to design an algorithm


In order to write an algorithm, following things are needed as a pre-requisite:
1. The problem that is to be solved by this algorithm.
2. The constraints of the problem that must be considered while solving the problem.
3. The input to be taken to solve the problem.
4. The output to be expected when the problem is solved.
5. The solution to this problem, in the given constraints.

I.4 Structure of an algorithm


An algorithm can be made up by 3 main parts:
- The name of the algorithm: it shows the expected result or the treatment performed. It
is made up of a single word or several words pasted.
- Variables: these are the different types of data necessary for processing the algorithm.
- The body of the algorithm: delimited by the words START and END, it contains the
sequence of instructions allowing obtaining the expected result.
Algorithm NameAlgorithm
Variables: …
START
….INSTRUCTIONS
END

I.5 Inputs/Outputs
An algorithm uses data supplied by the user to do the processing and can also display
messages intended for the user.
In algorithmic, the instruction to display a message may be:
Write (« Message »)
The message can be composed by text and / or data contained in the variables.
If it is a text, it must be enclosed in quotation marks. If it is data contained in variables, you
just need to mention only the names of the variables outside the quotation marks.

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


3

Example: Let consider the variable b that contains the value 2. The instruction to display this
value is:
Write (« The value of b = », b)
To get a value entered on the keyboard by the user, we can use the instruction:
Read (variable)
The variable mentioned between () must be declared in the section. It is this variable which
will contain the value entered by the user on the keyboard. This value must have the same
type as the variable.
You can get more than one value in the same Read instruction. In this case, just indicate the
different variables that will contain the entered values separated by commas.
Example. Read (a,b)

I.6 Variables
A variable (in computer science) is a memory location that can contain data. Its type depends
on the data it can contain. A variable is characterized by:
- The name: generally composed by letters, it used to identify the variable in a unique
way in the algorithm.
- The type: it indicates the type of data that the variable can contain. This is the area of
definition of the variable.
- The value: it is what the variable contains. At a given moment, a variable contains
only one value at a time.
Variables can be classified into 2 main categories:
- Variables of simple types
- Variables of complex types

I.6.1 Variables of simple types


Also called primitive variables, they are generally composed of the following types:
- Integer: These are numeric values without commas
- Real: these are also numeric types but have commas
- Character: these are values corresponding to the different keys on the keyboard.
These values can be alphabet letters, numbers, special characters, and punctuation.
They are mentioned in apostrophes ‘‘. Ex. ‘A’, ‘1’, etc.
- Boolean: it is variable that takes one of the following values: True or False; Yes or no.
It’s a logical variable.
To declare a variable, you must mention its name and type in the variables section. If the
variables are of the same type, just mention their names separated by commas.
E.g. Let variables b and d be of integer type; r of real type; c of character type and t of
Boolean type.

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


4

We can declare them in the variables section as follows:


Variables: b,d : integer
r : real
c : character
t : boolean
The values of these variables will be assigned in the body of the algorithm:
- Either by the assignment operation
- Either by the read operation

I.6.2 Variables of complex types


A variable of complex type is a variable composed of variables of simple types. It is used to
manage more than one value of the same type or not.
For example arrays, objects with different characteristics as well as different structures such
as linked lists, lists, stacks and trees (search binaries) are complex types.
An array is a complex structure that manages data of the same type. It is often used to avoid
declaring several variables of the same types. These are consecutive boxes of a size defined in
advance which can have values of the indicated type.
To declare an array, you must indicate:
- The name: this is the identifier of the array which also corresponds to the address of
the 1st element of the array in memory.
- The type: is the type of data that each box of the array can contains. It is generally of
primitive type.
- The Size: is the maximum number of elements that the array can contain.
An array can be one or more dimensions. Each dimension is indicated by its size.
For example.
- To declare an array named tab of 10 integers, we write:
tab: array [10] of integers
- To declare an array named T of 3 rows and 4 columns of reals, we write:
T: array [3] [4] of reals
To access an element in the array, you must specify their rank between []. E.g.
Tab [2] corresponds to the 2nd box of the tab array
T [1] [3] corresponds to the box located in the 1st row and 3rd column of the array T

I.7 Determination of variables


In an algorithm, the declared variables can be identified in these situations:
- Either variables to contain the data entered by the user
- Either variables containing results to display to the user
- Or variables to contain intermediate results of treatments

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


5

I.8 Operators
The algorithms use different types of operators in their processing. The main types of
operators are :
- Arithmetic operators: +; -; ×; ÷; Mod
- Relational operators (comparison) : >, <, ≥,≤, =, ≠
- Logical operators: AND, OR, NOT
- Assignment operator: <-

I.9 Applications
Ex1: Write an algorithm to display Hello
Ex2: Write an algorithm to input an integer and then display its triple
Ex3: Write an algorithm allowing inputting 2 real numbers then to display the sum of these
values

Correction
1) Algorithm DisplayHello
Variables : …
START
Write (« Hello»)
END

Ex4 : Write an algorithm allowing to input 2 integers then to exchange their values and to
display these values before and after the exchange.

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


6

Chapter II: BASES OF PROCEDURAL PROGRAMMING


II.1 Introduction
After defining an algorithm, it is possible to translate it into one of the programming
languages understandable by the computer.
This translation gives a computer program composed of a sequence of instructions executed
by the computer to carry out treatments and obtain the expected and desired results.
In this chapter, we will use the C language in the translation of algorithms.

II.2 Some programming forms


There are different forms of programming that depend on the field as well as the point of view
of the system. Procedural programming differs from other forms of programming. It is based
on the definition of different procedures allowing to solve a problem by the sequential call of
these procedures.
Other forms of programming are for example:
- Event programming: it consists of executing instructions according to the detection
of an event performed on an object of the graphic interface.
- Object Oriented Programming: It considers the system as a set of objects (having
the same characteristics and same methods) which exchange messages to solve a
problem.
- Mobile Programming: it deals with programs used in an environment which varies in
time and space.
- Web programming: it allows you to create static and / or dynamic Web pages
accessible by a browser.
- Network Programming: it takes care of the programming of objects interacting
locally or remotely.

II.3 C language program


The C language is an improvement of the Pascal language which was created based on Unix.
It is used to manage high-level data up to the memory addresses of the computer.
The C language is a compiled language, that is to say a compiler is required to execute the
instructions of the program. It offers syntax composed of keywords (in English) which are
reserved for the language and cannot be used as names of variables or functions of the
program. It is therefore necessary to install or have a compiler on the computer to run
programs in C language.
The programs are written in files created in projects. There are different software that offers a
C language compiler. In our practical course, we will use Codeblocks or DevCpp.

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


7

II.4 Structure of a C program


A C program is made up of 2 main parts :
- The header: it contains the different libraries and the global variables of the program.
A library is indicated by the keyword: #include <Bibname.h> A global variable is
indicated by the keyword: #define
- Program body: it consists of a set of functions and procedures among which is the
main function. A program written in C language must have the main program to be
executed.
A program written in C language can have the following form :
#include<stdio.h>
int main ()
{
….
}

II.5 Steps for running a C program


After having written the instructions of the program in C language, we can run it by following
these steps:
- Build: This step allows you to import the different libraries mentioned in the program
header. A library contains the definition of the various functions made available to
programmers to facilitate their tasks.
- Compile: this step checks the syntax and semantics of the program to detect possible
errors. It is impossible to run a program containing errors if they are not corrected.
- Run: this step allows you to run the various program instructions to display the results
of the treatments.

II.6 Creation of a project


The code files are created in projects. A project can contain one or more code files. For
example, to create a project in Codeblocks, we proceed as follows:
- Launch Codeblocks if it is not open
- Go to the File menu and click on New then on Project
- In the window that appears, click on Console Application then on Go
- Click on Next then choose the C compiler and click on Next
- Type the Project title and specify the Folder to create project in by clicking on the…
- Click on Next then on Finish in the window that appears
After creating the project, its name appears in the window on the left under the Project tab. If
you want to show or hide certain parts of the interface, go to the View menu and click on the
item to show or hide.

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


8

The created project contains source files; especially the one that contains the main program.
To enlarge or reduce the font size, just:
- Keep the Ctrl key pressed on the keyboard
- Use the middle mouse button to enlarge or reduce the size then release the Ctrl key.
If the mouse does not work properly, you can do otherwise as follows:
- - Go to the Edit menu and click on Special Commands
- - In the menu that appears, go to Zoom then click on In to enlarge or Out to reduce
Before writing the code, make sure the compiler is working properly. To do this, simply
execute the code in the main.c file as follows:
- Go to the Build menu
- Click on Build and run in the menu that appears
You can also execute the file by pressing the F9 key

II.7 Variables
All variables used in the program must be declared. The C language offers a syntax for the
different types of data. Simple type data are declared using the following keywords: int, float,
char, long, double.
To declare a variable, you must specify the type and name of the variable. Any instruction;
even the statement; ends with a semicolon.
Example: Declaration of 2 integers a and b is done by: int a, b ;
It is always advisable to put comments in the program to facilitate its understanding. To
comment one line, just put // at the beginning of the line to comment.
To comment on several consecutive lines, just put /* at the beginning of the first line to
comment and */ at the end of the last line of the comment.
Comments are not executed by the compiler because it considers them as explanations.
To declare an array tab of 5 integers, we write: we write: int tab [5] ;

II.8 Display and input


The C language offers functions for displaying messages and input data entered on the
keyboard. These are functions defined in the stdio library.
To display a message, we use the instruction: printf("Message");
To go to the line, the C language uses the character ‘\n’ which corresponds to the Enter key
on the keyboard.
The character ‘\t’ corresponds to the tab key which allows you to jump spaces as if you were
moving in the columns of a table.

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


9

To display the value of a variable, you must specify its format in the place where the value
will be displayed in the message, then mention the name of the variable outside the quotes.
The format depends on the type of data.
For example: %d for int, %f forr float, %c for char, %l for long and double, %x for
hexadecimal, %s for string.
Ex1. Display the addresses of variables a and i.
printf("\nL'adresse de a est %x", &a);
printf("\nL'adresse de i est %x", &i);
To get a value entered on the keyboard, you can use the instruction:
scanf("format",&variable);
Example: the instruction to enter an integer and save it in the variable a is: scanf("%d",&a);

II.9 Operators
Different types of operators are used in C language operations. These operators are classified
in the following categories:
- Arithmetic operators: +, -, *, /, %
- Relational operators (comparison): >, <, >=, <=, ==, !=
- Logical operators: &&, ||, !
- Assignment operator: =
- Address operator: &
- Increment operator: ++
- Decrement operator: --

II.10 Application exercises


Ex1: Write a program in C to display Hello
Ex.2: Write a program in C allowing to input an integer then to display the value given by the
user.
Ex3: Write a program in C allowing you to input a real and then display its triple.
Ex4 : Write a program in C allowing to input 2 integers then to calculate and display the sum
of these values
Ex5 : Write a program in C allowing to input 2 reals then to exchange their values and display
the values before and after the process.
Ex6 : Write a program in C to calculate the VAT knowing that it is equal to 18% of the price
of the product given by the user
Ex7 : Write a program in C to convert an amount from BIF given by the user in dollars
knowing that the exchange rate is 1 $ = 2750 BIF

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


10

Chapter III: CONTROL STRUCTURES


III.1 Introduction
The instructions of a program are executed line by line from the first instruction to the last. If
certain instructions can be ignored, then they must be put them in a conditional control
structure. If certain instructions are executed more than once, they must be putted in a
repetitive control structure to avoid lengthening the program size.
Control structures can be classified into 3 categories:
- Conditional control structures
- Repetitive control structures
- Connection structures allowing to move in a program.
In this chapter, we will see conditional control structures and repetitive control structures.

III.2 Conditional control structures


They are based on a condition which allows you to choose the block of instructions to execute
if the condition is verified and to ignore other blocks if the condition is not verified.
A condition is a logical expression which can be TRUE or FALSE. It is generally made up of
the comparison between a variable and another value or variable. If the condition is complex
or relates to more than one criterion, we use the logical operators to link the different parts of
the condition.
There are 2 types of conditional structures:
- Simple conditional structure: IF – ELSE
- Conditional structure with multiple choices: SWITCH – CASE

III.2.1 IF – ELSE
This structure is used to choose an instruction block to execute from 2 alternatives offered. Its
syntax is as follows:
If (condition)
Instruction(s)_if_true ;
Else
Instruction(s)_if_false ;
It is a structure which tests a condition to know the block of instructions to execute: the one
which has the condition True as value.
The Else block is optional if the treatment to be done has not been specified when the
condition is not verified.
Ex1 : Write a program in C to input a real and then say whether it is less than 10.

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


11

Ex2 : Write a program in C to check if an integer given by the user is negative or not.
Ex3 : Write a program in C to check if a real given by the user is between 10 and 20
(inclusive).

III.2.2 SWITCH - CASE


This structure makes possible to manage several choices. It is used if there are specific values
to test for a variable. It avoids the user of nested IFs. Its syntax is as follows :
switch (variable)
{
case V1 : instruction(s)_v1 ; break ;

case Vn : instruction(s)_Vn ; break ;
default : instruction(s)_Others ;
}
In this structure, V1,…, Vn are values to be tested for the variable. If it is equal to V1 then we
execute the instructions of Vi until the break instruction. The break instruction allows to stop
the switch structure. If no value from V1 to Vn corresponds to the variable, then we execute
the default block.
Ex4 : Write a program in C allowing you to type a character then display Hello if the entered
character is h, display Allo if the entered character is a and display Thanks in other cases.
Ex5 : Write a program in C to display verbatim the value of an integer given by the user if it
is between 1 and 5 (inclusive).

III.3 Repetitive control structures


They are used to manage multiple or looped operations. In IT, a loop is characterized by:
- Initialization: it is a question of assigning a starting value to the variables used in the
condition of repetition
- Repetition condition: this is the condition to test to know whether to resume the
execution of the block instructions. This condition corresponds either to the negation
of the stop condition, or to the fact of not being at the final value of a counter.
- Modification of the value of the variables used in the condition: this makes
possible to avoid an infinite loop by moving towards stopping the loop.
There are 3 types of repetitive structures which depend on whether or not the number of
executions is known:
- For : this structure is used if we know in advance the number of executions (n).
- Do-while : this structure is used if we are sure of at least one execution of the
instruction block (1;n).

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


12

- While : this structure is used if we are not sure to have even one execution if not
several executions (0;n).

III.3.1 For
This structure is used as a counter with a start value and a final stop value. Its syntax is as
follows:
For(i=0 ;i<n ;i++)
{ instructions ;}
Initialization : i = 0
Repetition condition: i < n
Modification of the value of the variables : i++
The modification may be in ascending order (++) or descending (--).
NB : The count starts with 0 in programming while it starts with 1 in algorithmic.
Ex6 : Write a program in C to display Hello 10 times.
Ex7 : Write a program in C to display the Arabic numbers.

III.3.2 Do-while
This structure is used if the number of executions is not known in advance but it is sure to
have at least one execution. Its syntax is of the form:
do
{
instruction(s);
}while (condition) ;
Initialization can be done before or inside the loop. This structure makes possible to execute
the instructions once then to test the condition to know whether or not to resume the execution
of the instructions of the block.
The repeat condition generally corresponds to the opposite of the stop condition. This
structure is often used in input control.
In this structure, one of the block instructions must modify the value of the variable used in
the condition.
NB : Instructions using the for structure can be translated into the do - while structure, but not
vice versa.
Ex8 : Write a program in C to display the Arabic numerals using do-while
Ex9 : Write a program in C allowing to input a negative integer then display the selected
value.

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


13

III.3.3 While
This structure is used if we do not know the number of executions and it is even possible not
to execute the instructions of the block. Its syntax is of the form :
while (condition)
{
instruction(s);
}
This structure first tests a condition, if its value is TRUE, it executes the instructions of the
corresponding block. Otherwise, it ignores the instruction block to continue with the program.
In this structure, initialization is done before entering the loop. To avoid an infinite loop, one
of the block instructions must modify the value of the variable used in the condition.
Ex10 : Write a program in C allowing to input a negative integer using while then display the
selected value.
Ex11 : Write a program in C allowing you to input a strictly positive integer then calculate
and display its multiples which are less than 100.

III.4 Application exercises


Ex12 : Write a program in C to check if an integer given by the user is even peer or not.
Ex13 : Write a program in C allowing to compare 2 reals given by the user.
Ex14 : Write a program in C to display the name of the day of the week corresponding to an
integer value given by the user. Display an error message if the value is invalid.
Ex15 : Write a program in C to display the month and its number of days according to the
values given by the user. The number of the month and the year are integers given by the user.
Ex16 : Write a program in C allowing to input 5 integers then to display them.
Ex17 : Write a program in C allowing you to input 50 notes (each note is a real between 0 and
20) then display those that exceed 12.
Ex18 : Write a program in C allowing to input 2 integers then calculate and display the result
of one of the operations (-1.Stop, 0. Reset, 1.Sum, 2.Difference, 3.Product, 4.Quotient and
5.Rest) chosen by the user in the proposed menu.
Ex19 : Write a program in C allowing you to input an integer greater than 100 then display
the digits that compose it, starting with the last.
Ex20 : Write a program in C to input a positive integer then calculate and display its factorial.
Ex21 : Write a program in C allowing to input a strictly positive integer then calculate and
display its divisors.

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


14

Ex22 : Write a program in C allowing to input 2 integers and to check if they are divisible one
by the other.
Ex23 : Write a program in C allowing to input an integer greater than 10 then to say if it is a
prime number or not.
Ex24 : Write a program in C allowing you to input a secret code of integer type and then
guess it without exceeding 10 attempts.
Ex25 : Write a program in C allowing you to input an integer a and a positive integer n then
compute and display the value of an.
Ex26 : Write a program in C allowing to input 2 strictly positive integers then to find their
least common multiple (‘PPCM’).
Ex27 : Write a program in C allowing to input 2 strictly positive integers then to find their
greatest common divisor (‘PGCD’).
Ex28 : Write a program in C allowing to count and display the number of occurrences of an
integer given by the user among 30 integers entered before.
Ex29 : Write a program in C to verify that an integer given by the user exists among 40
integers entered before.
Ex30 : Write a program in C to calculate the success rate of a class of 60 students knowing
that the pass mark is 10/20.
Ex31 : Write a program in C allowing you to input an integer strictly greater than 10 then
calculate and display the sum of the 3 integers directly greater than the integer entered.
Ex32 : Write a program in C allowing you to input 5 integers in ascending order (each new
value must be greater than the previous one) then display them.

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


15

Chapitre IV : FUNCTIONS ET PROCEDURES


IV.1 Introduction
The resolution of a large or complex problem involves breaking down the problem into small
sub-problems that are relatively easy to solve. Subsequently, they can be assembled in another
main program responsible for solving the global problem. It’s the principle of Divide and
conquer.
In this case, each sub-problem is solved separately by a function or a procedure which will
contribute to the resolution of part of the global problem. A function or procedure defined in a
program can be used by other functions or procedures in the same program if necessary.
The use of functions and/or procedure reduces the size of the main program and facilitates the
modularity and maintenance of the program. Functions and/or procedures are generally
defined to contain processing executed several times and sometimes by different functions
and/or procedures of the same program.

IV.2 Definitions
A function is an independent program triggered by a call, with or without parameters; from
another program that executes its instruction block and stops by returning a value to the
calling program.
A procedure is also an independent program triggered by a call; with or without parameters;
from another program that executes its instruction block and returns nothing after execution or
rather returns the void.
We can classify functions and / or procedures into 2 categories:
- Simple functions (procedures)
- Recursive functions (procedures)

IV.3 Simple Functions (procedures)


A function is defined to perform a specific and precise task in the program. This task is
assigned according to the distribution of tasks to be carried out in the general resolution of the
problem.

IV.3.1 Structure of a function (procedure)


A function is of the form :
Return-type FunctionName (parameters)
{
Instructions(s) ;
return (value) ;}
Return-type: it corresponds to the type of the value returned by the function after the
execution of the block instructions. It is generally of simple type (int, float, char, ...).

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure


16

FunctionName : this is the name of the function. It is written in one word and designates the
processing performed by the function or the expected result.
Parameters : It is one or more values provided to the function to perform its task. If a
function uses parameters, you must always specify the type and possibly the name of the
variable.
The first line of the function declaration (Return_Type, FunctionName and parameters)
constitutes its signature. It is also called the function prototype. The return statement is last
executed before exiting the function.
A procedure has the same syntax as a function with void as return_type and without having
the return statement. A procedure is of the form :
void ProcédureName (parameters)
{
Instructions(s) ;
}
The signature of a procedure is composed by void, procedureName and parameters.
NB : Even if a function or procedure has no parameters, you must always put empty
parentheses.
Ex1 : Write a procedure in C named Greeting to display Hello.
Ex2 : Write a function in C allowing to input an integer then to return the entered value.
Ex3 : Write a function in C to compute the triple of an integer given in parameters.
Ex4 : Write a function in C to compute the sum of 2 integers given in parameters.

IV.3.2 Using a function (procedure)


A function (procedure) is defined to be used by other functions (procedures). The use is made
by calling the function (procedure) specifying the name and parameters of the function
(procedure) in the calling program (function or procedure).
A program using a function or procedure is executed by following the steps:
- The calling program interrupts its execution on the arrival on the function or
procedure.
- It executes the instructions of the function or procedure called up to the return
instruction (if it is a function)
- The calling program resumes execution at the place where it stopped it.
NB :
- It is always advisable to declare a variable which will contain the result of the function
call.
- Variables declared in a function or procedure are said to be local because they are not
known outside the function or procedure.

M. Sc. Jean Sylvain BUCUMI Algorithmic, C programming and Data Structure

You might also like