0% found this document useful (0 votes)
8 views37 pages

Algorithm Exercises for Programming Basics

The document presents a series of exercises in algorithms and programming, addressing concepts such as the correction of algorithms, the calculation of the absolute value, the display of seasons, the verification of prime numbers, and the calculation of factorials. Each exercise includes a description of the task to be accomplished as well as a proposed algorithm to solve the problem. The exercises also cover topics such as finding divisors, calculating products, and managing strings.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views37 pages

Algorithm Exercises for Programming Basics

The document presents a series of exercises in algorithms and programming, addressing concepts such as the correction of algorithms, the calculation of the absolute value, the display of seasons, the verification of prime numbers, and the calculation of factorials. Each exercise includes a description of the task to be accomplished as well as a proposed algorithm to solve the problem. The exercises also cover topics such as finding divisors, calculating products, and managing strings.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Exercises

Algorithmics and programming

Guaranteed by:
Emna Ammar Elhadjamor
Algorithmic Exercises
1. Give all the reasons why the following algorithm is incorrect:
IncorrectAlgorithm
x,y : Entier
z : Real
Start
z x + 2
y z
x * 2 3 + z
y 5y + 3
End.
This algorithm is incorrect for several reasons:
 ine 1: the word Algorithm is spelled with an 'h' in the middle.
L
L
 ine 2: the declaration of variables starts with the word 'Var'.
L ine 5: the value of x is indeterminate.
L  ine 6: type incompatibility (a real number assigned to a variable of integer type).
L  ine 7: The left-hand side of an assignment must be a variable.
L  ine 8: you need to write 5 * y and not 5y.
2. Write an algorithm that calculates and displays the absolute value of any integer read.
on the keyboard.
Absolute Value Algorithm
Var
x, va : Entier
Début
Write("Enter an integer="), Read(x)
If (x >= 0) Then
go x
Otherwise
go -x
FinSi
Write("|",x,"|=",va)
End.
3. Write an algorithm to display the season by inputting the month number.
Season algorithm;
Var M :integer;
Start Write('Give a month number 1--12');
Repeat Read(M);
Until M>0 and M<13
according to M to do

3,4,5 : Write('The season is: SPRING');


6, 7, 8 : Write('The season is: SUMMER');
9,10,11 : Write('The season is: AUTUMN');
12,1,2 : Write('The season is: WINTER');
Finselon
End
4. Write an algorithm that reads a positive integer and checks if this number is prime or not.
A prime number is only divisible by 1 or by itself.

2
PrimeAlgorithm
Var
n,i,nb_div: Integer
Start
Write("Enter a positive integer="), Read(n)
nb_div 0/* initialization of the number of divisors */
i 1
While (i <= n) Do
If ( n Mod i = 0 ) Then
nb_div nb_div + 1 /* incrementing the number of divisors */
FinSi
i i +1
As long as
If (nb_div <= 2) Then
Write("It's a prime number")
Otherwise
Write("This is not a prime number")
End If
The End.
5. Write an algorithm with three versions that reads a positive integer n then calculates and
displays its factorial according to the formula n! = 1 x 2 x … x n.
To...Do
As long as ... Doing
Repeat... Until...
Version For... To Do
FactorialAlgorithm
Var
n,i,f : Entier
Start
Write("Enter a positive integer="), Read(n)
f 1/* initialization of the factorial to 1 since 1!=1 */
To do
f For each path, we multiply the old value of f by
i*/
End For
Write(n,"!=" , f)
End.
As long as... Do
FactorialAlgorithm
Var
n, i, f : Integer
Start
Write("Enter a positive integer="), Read(n)
f 1/* initialization of the factorial to 1 since 1!=1 */
i 2/* initialization of the counter i */
While (i ≤ n) Do
f f * i /* For each iteration, we multiply the old value of f by
i*/
i i + 1 /* incrementing the counter i */
End For

3
Write(n,"!=" ,f)
End.
VersionRepeat… Until
FactorialAlgorithm
Var
n,i,f : Integer
Start
Write("Enter a positive integer="), Read(n)
f 1/* initialization of the factorial to 1 since 1!=1 */
i 2(* initialization of the counter i *)
Repeat
f For each iteration, we multiply the old value of f by
i*/
i i + 1 /* incrementing the counter i */
Up to (i=n)
Write(n,"!=" ,f)
End.
6. Write an algorithm that reads a positive integer n and then displays all its divisors.
DivisorAlgorithm
Var
n,i : Integer
Beginning
Write("Enter a positive integer="), Read(n)
Pouride1ànFaire
If(n Mod i = 0) Then /* If the remainder of the value of n is equal to 0 */
Write
End If
End For
The End.
7. Write an algorithm that displays all perfect numbers less than 1000. A perfect number
is a number that has the property of being equal to the sum of all its divisors, except itself.
The first perfect number is 6 = 3 + 2 + 1. The perfect numbers less than 1000 are: 6,
28, 496.
Perfect algorithms
Var
i, n, s, j: Integer
Start
Pouride1 to 1000 Make
s 0
To make from (i Div 2)
If (i Mod j = 0) Then
s s + j
Fin Yes
For
End For
If (s = i) Then
Write(i, " is a perfect number")
End If
End.

4
8. Write an algorithm that searches for the minimum and maximum in a set of N
names.
MaxMin Algorithm;
Var I, N, Max, Min, X: integer;
Start Write('Give an integer N>0');
Repeat Read(N);
Until N>0; /* Read the first element, then initialize the Min and the
Max at this value Read(X)*/ ;
Max←X ;
Min←X ;
For I ←2 to N Do /* read the sequence of elements and update the Min
and the Max Read(X) */;
If Max < X Then Max ← X
If X > Min then Min ← X
Finish;
Finish;
End for;
Write('The minimum of the values is: ', Min, ' the maximum is: ', Max); End
9. Write an algorithm that calculates the product of two integers using only
the addition operation '+'.
Product Algorithm;
Var A,B,P,I :integer ;
Start
Write('Give two integers A and B');
Read(A, B);
If A=0 or B=0
So P←0
Otherwise P←0 ; /*initialize the product to 0
For I ←1 to Do
P ← P + A ;

End for
Finish;
Write('The product A*B is: ', P) ;
End.
We can optimize the solution by choosing the loop with the fewest iterations:
Product Algorithm;
Var A,B,P,I :integer ;
Start
Write('Give two integers A and B');
Read(A,B);

5
If A=0 or B=0
So P←0
Otherwise If A > B

So P←A; /*We can initialize the product to A and start the loop at
2 * /
For I ←2 to BFaire
P←P+A ;
End for
Otherwise P←B ;

For I ← 2 to A Do
P←P+B ;
End for
Finished;
Write('The product A*B is : ', P);
End
10. Write an algorithm that determines if A is divisible by B. With A and B as integers.
positives.
Algorithm AdivB;
Var A, B, R : integer;
Start
Write('Give two positive integers A, B')
Repeat Read(A,B); Until A>0 and B>0;
R←A ;
As long as R≥0 Do
R ← R - B;
As long as it lasts;

If R=0 Then Write(A, ' is divisible by ', B)


Otherwise Write(A,' is not divisible by ',B)
Finish;
End
11. Write an algorithm that calculates the sum of the digits that make up a natural integer.
N.
Algorithm SumDigit;
Var N,S,R :integer;
Start
Write('Provide a natural integer N');
Repeat Read(N);
Up to N≥0;
S←0 ; R←0 ;
As long as R > 0 Do

6
S ← S + R MOD 10;

R ← R DIV 10;
As long as;
Write('The sum of the digits that make up ', N, ' is:', S);
End.
12. Write an algorithm that reads a word (string made up only of letters)
then he reads a letter and displays the number of occurrences of the letter in the word.
Frequency Algorithm
Var
I, L, nb: Integer
Chain
Letter: Character
Start
Write("Enter a word:"), Read(word)
Write("Enter a letter:"), Read(letter)
L Long(word)(* length of the word *)
nb 0/* initialization of the occurrence counter for the searched letter
*/
Pouride1 to do
If(mot[i] = letter)Then
nb nb + 1 /* increment the number of occurrences */
End If
End For
Write(letter, " appears ", nb, " times in ", word)
End
13. Write an algorithm that reads a finite number of grades and then displays the best grade,
bad grade and the average of the grades.
Algorithm Notes
Var
n, i: Integer
note, min, max, s : Réel
Beginning
Write("Enter the number of grades=")
Lire(a) (* On suppose que n est toujours supérieur à zéro *)
s 0
min 0
max 0
For i from 1 to n Do
Write("Enter a grade="), Read(grade)
s s + note (* add the new note *)

7
If (note < min) Then
min note (* memorization of the new minimum value *)
End If
If ( note > min ) Then
max note (* memorization of the new maximum value *)
End If
End For
Write("Best grade = ", max)
Write("Bad grade = ",min)
Write("Average of grades = ", s/n)
The End.
14. Write an algorithm that reads the contents of two strings and swaps their
contents and then displays them on the screen.

Algorithm permute;
Variable a,b,aux: string
debut
Write('Give the two strings to be swapped ');
read(a,b);
aux ← a;
a←b;
b ← aux;
write(a); write(b);
end.
15. Write an algorithm that calculates the average of 3 grades.
Average algorithm;
var
moy,somme,x,y,z : entier;
debut
Give the three integer grades x, y, and z
read(x,y,z);
sum = x + y + z;
avg ← sum/3 ;
write(moy);
The End.
16. Write an algorithm that reads the value of the water temperature and then displays it.
état : GLACE si la température<0, LIQUIDE si la température>0 et <100, VAPEUR si la
temperature > 100.
Algorithm state
Variable T: real
Start

8
Please give the water temperature:
read(T)
If(T<=0) Then
The state of the water is ICE
If (T>0 and T<100) Then
The state of water is LIQUID
Otherwise
The state of water is VAPOR
Finsi
Finish Fin
[Link] an algorithm that reads a letter from the keyboard and then displays whether it is a consonant.
or a vowel. The vowels are: "A", "a", "E", "e", "I", "i", "O", "o", "U", "u", "Y"
"y".
Cons_Voy Algorithm
Var
c : Character
Start
Repeat
Write("Enter a letter:"), Read(c)(* control input of a letter *)
Until (c >= "A" AND c <= "Z") OR (c >= "a" AND c <= "z")

If(Upper(c) = "A") OR(Upper(c) = "E") OR(Upper(c) = "I")


IF(Upper(c) = "O") OR (Upper(c) = "U") OR (Upper(c) = "Y") Then
Write(c, " is a vowel")
Otherwise
Write(c," is a consonant")
End If
The End.
18. Write a procedure permut that allows you to swap the values of 2 integers a and b.
Procedure Permute(var a, b : Integer)
Var
integer
Start
aux a
A b
b to
End
AlgorithmTest{main program}
Var
x,y : Entier
Beginning

9
Ecrire("Entrer un entier x="), Lire(x)
Write("Enter an integer y=") , Read(y)
Permute(x,y)//call the procedure
Write(The new value of x= , x, and of y= , y)
End.
19. Write a function minimum that returns the minimum of 2 integers a and b. Test.
this function.
MinimumFunction(a, b : Integer) : Integer
Var
min : Integer
Start
If (a <= b) Then
min a
Otherwise
min b
End If
End
AlgorithmTest{main program}
Var
x,y,m : Entier
Start
Write("Enter an integer x=\
Write("Enter an integer y=") Read(y)
m Minimum(x,y)(* function call *)
Write (The minimum is = , m)
The end.
20. Write a Fill procedure for filling an array of n integers.
Procedure Fill (varT : Array; n: Integer)
Var
Integer
Start
Pouride1ànFaire
Write("T[",i,"]="), Read(T[i])
End For
End
[Link] a procedure Display to show the elements of an array of n
whole numbers.
Procedure Display (T: Array; n: Integer)
Var
Integer
Beginning
Pouride1ànFaire
Write(T[i], " ")
End For
End

10
22. Write a procedure to merge two sorted arrays A and B.
respectively n and m elements. The result is a sorted array C with (n+m) elements.
Example:

4 5
A 1 20 B 19 23 27 91
1 4

4
C 1 20 19 23 27 54 91
1

MergeProcedure (A: Array; B: Array; varC: Array; n, m: Integer; vark: Integer)


Var
i, j : Integer
Beginning
As long as (i <= n) AND (j <= m) Do
If(A[i] <= B[j])Then
C[k] A[i]
I i + 1
k k +1
End If
If(B[j] <= A[i]) Then
C[k] B[j]
j j + 1
k k +1
End If
As long as
While (i <= n) Do
C[k] A[i]
i i + 1
k k +1
As long as
While (j <= m) Do
C[k] B[j]
j j + 1
k k +1
As long as
End

23. Write the procedures or functions to solve the following problems:

1- Calculation of the sum of two integers.

2- Calculation of the factorial of N (N !).

3- Check if an integer A divides an integer B.

11
4- Calculation of the quotient and the remainder of the integer division of two integers A and B.

5- Check if a given character is a vowel (vowels: 'a', 'e', 'i', 'o', 'u', 'y').

6-Allows swapping (exchanging) the content of two real variables.

7- Given an integer A, calculate its absolute value

1- Function Sum(x,y :integer) :integer ;

Debut

Sum ← x+y ;

End;

2- Function Fact(x:integer) :integer ;

Var I, F :integer;

Debut

F←1 ; /* we can use the function name directly instead of F

For I←1 to x Do F ← F*I ;

End for ;

Fact ← F ;

End;

3- Function Divide(A, B :integer) :boolean ;

Debut

Divide ← False ;

If B mod A = 0 Then Divides ← True

Finish;

End;

4- Procedure QuotRest(E/A, B: integer; S/Q, R: integer);

Debut

Q ← 0 ; R ← A ;

12
As long as R >= B Do

R ← R mod B ;

Q ← Q+1 ;

End tank;

End;

5- Function Vowel(C :character) :boolean ;

Debut

Vowel ← False;

according to C make

'a', 'e', 'i', 'o', 'u', 'y': Voyelle ← Vrai ;

Finselon ;

End;

6- Procedure Permute(E/S/ A,B :integer);

Var C:entire:

Debut

C gets A; A gets B; B gets C;

End;

7- Function Vabs(A :integer) :integer;

Debut

Vabs ← A ;

If A<0 Then Vabs ← A End If;

End;

24. Let vector T (one-dimensional array) contain N integers (N≤100).


Write the algorithms for:
1-Determine the minimum, the maximum, and the average of the elements of an array T
2- Calculate the product of all the elements of T as well as the number of values
strictly positive.

13
3- Calculate the sum and the scalar product of two vectors (T1 and T2).
4-Determine the positions of the occurrence of a value in a vector T.
5- Reverse the contents of a vector T.
6- Delete all null values from a vector T.
7- Met les valeurs négatives au début et les valeurs positives à la fin en utilisant un seul
tableau.
1- MinMax Algorithm;
Var T :Array[1..100] of integer ;
I,N,Max,Min,S :integer ; Moy :real ;
Debut
reading the exact size
Write('Give the size of the array N≤100')
Repeat Read(N) Until N>0 and N≤100;
Reading the elements of T
For I = 1 to N Do Read(T[I]); Endfor;
Initialization
Min←T[1] ; Max←T[1] ; S←0 ;
For I←1 to N Do
If Max < T[I] Then Max ← T[I] End If;
If Min > T[I] Then Min ← T[I] End If;
S ← S + T[I] ;
Finpour;
Moy←S/N ;
Write('Maximum=', Max, ' Minimum=', Min, ' Average=', Moy);
End.
2- Prod Algorithm;
Var T :Array[1..100] of integer;
I,N,P,Nbp :integer ;
Debut
/*reading the exact size
Write('Give the size of the array N≤100')
Repeat Read(N) Until N>0 and N≤100;
Initialisation
P←1 ; Nbp←0 ;
Reading elements of T and processing at the same time
For I←1 to N Do
Read(T[I]);
If T[I] > 0 Then Nbp ← Nbp + 1 Endif;
P ← P * T[I] ;

14
Finpour;
Write('Product=', P, ' Number of positive values=', Nbp);

End.
3- Prod Algorithm;
Var T1,T2,T3 :Tableau[1..100] de entier ;
I, N, PS: integer;
Debut
reading the exact size
Write('Give the size of the array N≤100');
Repeat Read(N) Until N>0 and N≤100;
Reading elements from T1 then T2 do not read in the same
loop
For I ← 1 to N Do Read(T1[I]); End for;
For I ← 1 to N Do Read(T2[I]); End for;
PS←0 ; /*initialize scalar product to 0
The sum of T1 and T2 in T3
For I←1 to N Do
T3[I] ← T1[I] + T2[I];
PS ← PS + T1[I] * T2[I];
Finpour ;
Write('Scalar Product=', PS);
Write('Sum of the vectors');
For I←1 to N Do Write (T3[I]) ; Endfor ;
End.
4- Position Algorithm;
Var T, Pos: Array[1..100] of integer;
I,J,N,Val :integer ;
Debut
/*reading the exact size
Write('Give the size of the array N≤100');
Repeat Read(N) Until N>0 and N≤100;
For I←1 to N Do Read(T[I]) ; Endfor;
Ecrire(‘Donner Val’) ; Lire(Val) ;
Search for val and its position
J←0 ;
For I←1 to N Do
If T[I]=Val Then J←J+1; Pos[J]←I End If;
Fact;
If J=0 Then Write(Val,'not found')
Otherwise Write(Val,'found at positions :') ;

15
For I←1 to J Do Write (Pos[I]) ; Endfor ;
Finish ;
If we initialize J to 1, its incrementation occurs afterwards
the assignment and the
/*dimension of Pos becomes J-1
End.
5- Inverse Algorithm;
Var T :Array[1..100] of integer;
I, J, X, N: integer;
Debut
/*reading the exact size
Write('Give the size of the array N≤100');
Repeat Read(N) Until N>0 and N≤100;
Reading the elements of T
PourI←1 à N Faire Lire(T[I]) ; Finpour;
Inverser
I←1 ; J←N ;
As long as I<J
To do
X←T[I] ; T[I]←T[J]; T[J]←X;
I←I+1 ; J←J-1;
Finantque;
Display of the new table T
For I←1 to N Do Write(T[I]); Endfor;
The End.
6- Algorithm RemoveZero;
Var T :Array[1..100] of integer ;
I, J, N: integer;
Debut
reading the exact size
Write('Give the size of the array N≤100');
Repeat Read(N) Until N>0 and N≤100;
Reading the elements of T
For I←1 to N Do Read(T[I]) ; Endfor ;
The removal of zeros returns to shifting the non-null values
I←1 ;
As long as I ≤ N

To do
If T[I]=0
So /*shift loop

16
For J←I to N-1 Do T[J]←T[J+1];
Finpour;
N←N-1 /*change the size of the array
Finish;
I←I+1 ;
Fintantque ;
Displaying the new table T
For I←1 to N Do Write(T[I]);
Finpour ;
The End.
Solution 2 :
Algorithm RemoveZero2;
Var T :Array[1..100] of integer;
I, J, NBN, N: whole
Debut
reading the exact size
Write('Give the size of the array N≤100')
Repeat Read(N) Until N>0 and N≤100;
Reading the elements of T
For I ← 1 to N Do Read(T[I]); End for;
Removing zeros means shifting non-null values.
after 1 (without loop)
I←1 ; J←1 ; NBN←0 ;
As long as J≤NDo
If T[J]=0 Then NBN←NBN+1 /*number of null values
Otherwise /*move the element
T[I]← T[J] ; I←I+1
Finished;
J←J+1;
Fintantque;
N←N-NBN ; /*changer la taille de T
Display of the new table T
For I←1 to N Do Write(T[I]); Endfor;
End.
7- NegThenPos Algorithm;
Var T :Array[1..100] of integer;
I, J, N, X: integer;
Debut
/*reading the exact size
Write('Give the size of the array N≤100');

17
Repeat Read(N) Until N>0 and N≤100;
Reading the elements of T
For I from 1 to N do Read(T[I]); Endfor;
move the negative values to the beginning
J←1 ;
While J≤N and T[J]<0 Do J←J+1 ; Done ;
move negative values to the beginning (find the first value
positive I )
I←J ;
As long as J≤NDo
If T[J] < 0 Then /*swap
X ← T[I]; T[I] ← T[J]; T[J] ← X;
I←I+1
Finish;
J←J+1 ;
Fintantque ;
Displaying the new table T
For I←1 to N Do Write(T[I]) ; Endfor;
The End.
25. Write procedures that allow for:
Fill a matrix;
2. Display a matrix;
Return the sum of two matrices M1 and M2;
Return the product of two matrices M1 and M2;
Filling a matrix
Procedure Fill (var matrix: Mat; n, m: Integer)
Var
i, j : Integer
Start
Pouride1ànFaire
Pourjde1àmFaire
Write("Enter an integer: "), Read(T[i,j])
End for
End For
End
2. Displaying a matrix
Procedure Display (matrix: Mat; n, m: Integer)
Var
i,j : Integer
Start
Foride1ànMake
To do1àmMake
Write(T[i,j])
End For

18
Finish For
End
3. Sum of two matrices
Procedure SumMat (M1, M2: Matrix; var M3: Matrix; n, m: Integer)
Var
i, j : Integer
Start
Foride1anDo
For one to do
M3[i,j] M1[i,j] + M2[i,j]
End for
End For
End
4. Product of two matrices
ProcedureProdMat (M1, M2 : Mat; var M3 : Mat; n, m : Integer; var k :
Entire
Var
i, j : Integer
Start
Pouride1ànFaire
Pourjde1àmFaire
M3[i,j] 0
Why should I do it?
M3[i,j] M3[i,j] + M1[i,k] * M2[k,j]
End For
End For
End For
End

19
If A=0 or B=0
So P←0
Otherwise If A > B

So P←A; /*We can initialize the product to A and start the loop at
2 * /
For I ←2 to BFaire
P←P+A ;
End for
Otherwise P←B ;

For I ← 2 to A Do
P←P+B ;
End for
Finished;
Write('The product A*B is : ', P);
End
10. Write an algorithm that determines if A is divisible by B. With A and B as integers.
positives.
Algorithm AdivB;
Var A, B, R : integer;
Start
Write('Give two positive integers A, B')
Repeat Read(A,B); Until A>0 and B>0;
R←A ;
As long as R≥0 Do
R ← R - B;
As long as it lasts;

If R=0 Then Write(A, ' is divisible by ', B)


Otherwise Write(A,' is not divisible by ',B)
Finish;
End
11. Write an algorithm that calculates the sum of the digits that make up a natural integer.
N.
Algorithm SumDigit;
Var N,S,R :integer;
Start
Write('Provide a natural integer N');
Repeat Read(N);
Up to N≥0;
S←0 ; R←0 ;
As long as R > 0 Do

6
Enter a line of text (max. 200 characters)
:\n";
gets(TXT); /* Using scanf is impossible for */
/* read a sentence containing a variable number of words. */
/* a) Count the characters */
The end-of-string marker '\0' is
/* used as a stop condition. */
for (L=0; TXT[L]; L++)
;
The text is composed of %d characters.
b) Count the letters 'e' in the text
C=0;
for (I=0; TXT[I]; I++)
if (TXT[I]=='e') C++;
The text contains %d letters 'e'.
c) Display the sentence backwards
for (I=L-1; I>=0; I--)
putchar(TXT[I]); /* or printf("%c", TXT[I]); */
putchar('\n'); /* or printf("\n"); */
Invert the order of the characters
for (I=0,J=L-1 ; I<J ; I++,J--)
{
HELP=TXT[I];
TXT[I]=TXT[J];
HELP
}
puts(TXT); /* or printf("%s\n",TXT); */
return (0);
}

3. Write a program that reads a TXT text (of less than 200 characters) and removes all
the appearances of the character 'e' by packing the remaining elements. Changes will be made
in the same variable TXT.

#include <stdio.h>
main()
{
/* Declarations */

char TXT[201]; /* given string */


int I,J; /* current indices */
Data entry
Enter a line of text (max. 200 characters)
:\n");
gets(TXT);
/* Remove the letter 'e' and compress : */
Copy characters from I to J and increment J.
/* only for characters different from 'e'. */
for (J=0,I=0 ; TXT[I] ; I++)
{
TXT[J] = TXT[I];
if (TXT[I] != 'e') J++;

21
}
End the string !!
TXT[J]='\0';
/* Editing the result */
puts(TXT);
return (0);
}
Example:
This line contains some letters e.
Cut the length content quality letters.

4. Write a program that calculates the average of grades provided from the keyboard with a dialogue
of what type:

note 1 : 12
note 2: 15.25
note 3 : 13.5
note 4 : 8.75
note 5 : -1
average of these 4 grades: 12.37
The number of notes is not known in advance and the user can provide as many as they wish.
To signal that he has finished, it is agreed that he will provide a fictitious negative note. This must not
naturally not to be taken into account in the calculation of the average.
#include <stdio.h>
main()
float note, /* current note */
sum, /* sum of the grades */
average ; /* average of the grades */
int num; /* current note number */
som=0 ; num=0 ;
while ( printf("note %d : ", num + 1),
scanf("%f", &note), note >= 0)
num++;
som += note ;
}

if (num > 0)
{ moy = som/num ;
average of these %d grades: %5.2f
}
--- no grade provided ---
}

5. Write a program that asks for the user's first name and last name and
which then displays the total length of the name without counting spaces. Use the function
strlen.

#include <stdio.h>
#include <string.h>
main()
{

22
char NAME[40], FIRSTNAME[40];
Enter your first name and last name:
scanf("%s %s", NAME, FIRSTNAME);
Hello %s %s !
Your name consists of %d letters.
strlen(FIRST_NAME) + strlen(LAST_NAME);

or else
Your name consists of %d letters.
strlen(strcat(NAME,SURNAME));
*/
return (0);
}

6. By multiplying a matrix A of dimensions N and M with a matrix B of dimensions M and


We obtain a matrix C of dimensions N and P:
A(N,M) * B(M,P) = C(N,P)

Write a program that performs the multiplication of two matrices A and B. The result of
The multiplication will be stored in a third matrix C which will then be displayed.
#include <stdio.h>
main()

{
/* Declarations */
int A[50][50]; /* given matrix */
int B[50][50]; /* given matrix */
int C[50][50]; /* result matrix */
int N, M, P; /* dimensions of the matrices */
int I, J, K; /* current indices */
Data entry
*** Matrix A ***
Number of lines of A (max. 50) :
scanf("%d", &N );
printf("Number of columns in A (max.50) : ");
scanf("%d", &M);
for (I=0; I<N; I++)
for (J=0; J<M; J++)
{
Element[%d][%d] :
scanf("%d", &A[I][J]);

23
}
*** Matrix B ***\n
Print number of lines of B: %d
printf("Number of columns of B (max.50) : ");
scanf("%d", &P);
for (I=0; I<M; I++)
for (J=0; J<P; J++)
{
Element[%d][%d] :
scanf("%d", &B[I][J]);
}
Displaying matrices
Given matrix A:
for (I=0; I<N; I++)
{
for (J=0; J<M; J++)
printf("%7d", A[I][J]);

}
Given matrix B:
for (I=0; I<M; I++)
{
for (J=0; J<P; J++)
printf("%7d", B[I][J]);
printf("\n");
}
/* Assignment of the multiplication result to C */
for (I=0; I<N; I++)
for (J=0; J<P; J++)
{
C[I][J]=0;
for (K=0; K<M; K++)
C[I][J] += A[I][K]*B[K][J];
}
/* Edit the result */

Matrix result C:
for (I=0; I<N; I++)
{
for (J=0; J<P; J++)
printf("%7d", C[I][J]);

}
return (0);
}

7. Write a program that displays a rectangle of length L and height.


H, formed of asterisks '*' :

24
#include <stdio.h>
main()
{
/* Prototypes of the functions called by main */
void RECTANGLE(int L, int H);
/* Declaration of local variables in main */
int L, H;
/* Treatments */
printf("Enter the length (>= 1): ");
scanf("%d", &L);
Enter the height (>= 1):
scanf("%d", &H);
Display a rectangle of stars
RECTANGLE(L,H);
return (0);
}
For the function to be executable by the machine, it still needs to specify the
function
RECTANGLE :
void RECTANGLE(int L, int H)
{
/* Function prototypes called */

void LINE(int L);


/* Declaration of local variables */
int I;
Treatments
Display H lines with L stars
for (I=0; I<H; I++)
LINE(L);
}
For the RECTANGLE function to be executable by the machine, it is necessary to
specify the
LINE function:
void LINE(int L)
{
Displays a line with L stars on the screen
/* Declaration of local variables */
int I;
/* Treatments */
for (I=0; I<L; I++)
printf("*");

25
8. Write a program using a function AVERAGE of type float to display the
arithmetic average of two real numbers entered from the keyboard.

#include <stdio.h>
main()
{
/* Prototypes of the called functions */
float AVERAGE(float X, float Y);
/* Local variables */
float A,B;

/* Treatments */

Enter two numbers:

scanf("%f %f", &A, &B);

printf("The arithmetic mean of %.2f and %.2f is %.4f\n",

A, B

AVERAGE(A,B));

return (0);

float AVERAGE(float X, float Y)

(X+Y)/2;

9. Write a MIN function and a MAX function that determine the minimum and maximum
of two real numbers. Write a program using the MIN and MAX functions to
determine the minimum and the maximum of four real numbers entered via the keyboard.

#include <stdio.h>
main()
{
/* Prototypes of the called functions */
double MIN(double X, double Y);
double MAX(double X, double Y);
/* Local variables */
double A, B, C, D;
/* Treatments */
printf("Enter 4 real numbers: ");
scanf("%lf %lf %lf %lf", &A, &B, &C, &D);
printf("The minimum of the 4 reals is %f \n",
MIN( MIN(A,B), MIN(C,D))
);
printf("The maximum of the 4 reals is %f \n",

26
MAX( MAX(A,B), MAX(C,D))
);
return (0);
}
double MIN(double X, double Y)
{
if (X<Y)
return X;
else
return Y;
}
double MAX(double X, double Y)
{
if (X>Y)
return X;
else
return Y;
}
or else
/*
double MIN(double X, double Y)
{
return (X<Y) ? X : Y;
}

double MAX(double X, double Y)


{
return (X>Y) ? X : Y;
} «
*/

10. Write a C function that displays the area of a triangle whose base and height are
parameters passed. Write the main program that inputs the base and the height
of a triangle and displays the area of the triangle.

void area(float base, float height)


{
Area = %f
}
int main(void)
{
float b, h;
Enter the base and height of the triangle:
scanf("%f %f", &b, &h);
air(b, h);
return 0;
}

[Link] a function that calculates the factorial n! of an integer n passed as a parameter.

(Reminder: n! = 1 × 2 × · · · × n)

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

[Link] a program that inputs two int type variables, which swaps their
contenu et qui affiche les nouvelles valeurs des variables.
On se propose de refaire la question a) en réalisant l’échange de valeurs à l’intérieur d’une
Function. Write a function that swaps the contents of two variables passed by address.
Write the main program that inputs two variables, swaps them by calling the function
and display the new content of the variables.

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

28
13. Write a function that calculates the sum and the product of the elements of an array passed in
parameter. Write the main program that initializes the array by input; calculates and
displays the sum and the product of the elements

#define NB_ELEM_MAXI 100


void calculate(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 > MAX_ELEMENTS)
{
printf("Enter the number of elements: ");
scanf("%d", &size);
}
Please enter the elements of the array

for (i=0 ; i<size ; i++)


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

14. Write a program that sets the elements of the main diagonal of a matrix to zero.
square A given.

#include <stdio.h>
main()
{
/* Declarations */
int A[50][50]; /* square matrix */
int N; /* dimension of the square matrix */
int I, J; /* current indices */
Data entry
Print the dimension of the square matrix (max. 50):
scanf("%d", &N);
for (I=0; I<N; I++)
for (J=0; J<N; J++)

29
{
Element[%d][%d] :
scanf("%d", &A[I][J]);
}
/* Display of the matrix */
Given matrix:
for (I=0; I<N; I++)
{
for (J=0; J<N; J++)
printf("%7d", A[I][J]);

}
Resetting the main diagonal
for (I=0; I<N; I++)
A[I][I]=0;

/* Editing the result */


Result matrix:
for (I=0; I<N; I++)
{
for (J=0; J<N; J++)
printf("%7d", A[I][J]);

}
return (0);
}

15. Write a program that creates and displays a unit square matrix U of dimension N.
A unitary matrix is a matrix such that:
1 if i=j
uij =
0 if ij

#include <stdio.h>
main()
{
/* Declarations */
int U[50][50]; /* unit matrix */
int N; /* dimension of the unit matrix */
int I, J; /* current indices */
Data entry
printf("Dimension of the square matrix (max.50): ");
scanf("%d", &N);
Construction of the unit square matrix
for (I=0; I<N; I++)
for (J=0; J<N; J++)
if (I==J)
U[I][J]=1;
else
U[I][J]=0;
/* Editing the result */

30
Unit matrix of dimension %d:
for (I=0; I<N; I++)
{
for (J=0; J<N; J++)
printf("%7d", U[I][J]);
printf("\n");
}
return (0);
}
Note:
The operation:
if (I==J)
U[I][J]=1;
else
U[I][J]=0;
can be simplified by
U[I][J] = (I==J);

16. Write a program that uses a function to calculate the average of five values.
float type, data provided by the user.

/* Calculation of the average of the five numbers entered by the user */


#include <stdio.h>
#include <stdlib.h>
float v, w, x, y, z, response;
float average(float a, float b, float c, float d, float e);
int main()
{
puts("Enter five numbers:");
scanf("%f%f%f%f%f", &v, &w, &x, &y, &z);
reponse = moyenne(v, w, x, y, z);
The average is %f.
exit(EXIT_SUCCESS);
}
float average(float a, float b, float c, float d, float e)
{
return((a+b+c+d+e)/5);
}

17. Write a C function that calculates the average of three numbers passed as parameters. Write
the main program that inputs three numbers from the keyboard and displays their average.

floataverage(floata, floatb, floatc)


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

31
return 0;
}

18. Write a program that allows you to store different values entered from the keyboard and to
les réafficher dans l’ordre où elles ont été saisies. Le nombre de valeurs, ou nombre
the elements of the table is set at 15.

#include<stdio.h>
#define NB_ELEM 15 /* Number of elements in the array */
/* ******** Display Function ********** */
/* Displays a table */
void Display(float array[NB_ELEM])
{
you
for (i=0 ; i<NB_ELEM ; i++)
{
printf("the element number %d is worth %f\n", i, array[i]);
}
}
/* ********* Main function ********** */
/* Reads an array and displays it */
intmain()
{
index;
float tableau[NB_ELEM]; /* declaration of the array */
for (i=0 ; i<NB_ELEM ; i++)
{
printf("Enter element %d: ", i);
scanf("%f", &tableau[i]); /* reading an element */
}
Display(table);/* Display the table */
return 0;
}

19. Write a program that also allows reading elements from the keyboard and redisplaying them.
but this time the number of elements is read from the keyboard. However, this number of elements must
to remain below a fixed maximum constant value.

#include<stdio.h>
#defineNB_ELEM_MAXI 100 /* Maximum number of elements */
of the table
/* ******** Display Function ********** */
/* Displays an array of size n */
void Display(float array[], int n)
{
you
for (i=0 ; i<n ; i++)
{
printf("the element number %d is worth %f\n", i, array[i]);
}
}

32
/* ********* Main function ********** */
/* Reads an array and displays it */
int main()
{
intn, i; /* number of elements and index */
float tableau[NB_ELEM_MAXI]; /* declaration of the array */
Enter the number of items to type:

/* reading the number of elements from the keyboard (variable) */


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

20. Write a function that takes an array of size NB_MAX as a parameter, its number
of elements n < NB_MAX, an integer i ≤ n, and an integer m. The function must insert the element
m in position i in the table (without removing any element).

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

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

21. Write a function that initializes all the values of an array to 0. Write the program.
The principal that declares the array, calls the function, and displays the elements of the array.

#define NB_ELEM_MAXI 100


void clear(int *array, int size)
{
int i;
for (i = 0; i < size; i++)
t[i] = 0;
}

33
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]);
initialize(tab, NB_ELEM_MAXI);
for (i = 0; i < MAX_ELEMENTS; i++)
printf("tab[%d] = %d\n", i, tab[i]);
return 0;
}

22. What is the order of precedence of the different operators in the following expression:
((3 * a) - x ^ 2) - (((c - d) / (a / b)) / d)

23. Calculate the sum, product, and average of a sequence of non-zero digits entered at
keyboard, knowing that the sequence ends with zero. Keep only the digits (0, 1 ... 9)
when entering the data and produce a sound signal if the data goes out of this
domain.

#include <stdio.h>
main()
{
int X; /* The current number */
int N=0; /* The data counter */
int SOM=0; /* The current sum */
long PROD=1; /* The current product - Type long to */
/* because of the magnitude of the result. */
*/
do
{
/* Data entry (for perfectionists) */
printf("Enter the %d%s digit: ", (N+1), (N)?"e" : "");
:"er");
scanf("%d", &X);
if (X<0||X>9)
printf("\a");
else if (X)
{
N++;
SOM+=X;
PROD*=X;
}
else if (!X && N > 0)
Only if at least one digit has been accepted
*/

34
printf("The sum of the digits is %d \n", SOM);
printf("The product of the digits is %ld\n", PROD);
printf("The average of the numbers is %f \n",
(float)SOM/N);
}
}
while (X);
return (0);
}

24. Display an isosceles triangle made of stars with N lines (N is provided via keyboard):
Number of lines: 8

*
***
*****
*******
*********
***********
*************
***************

#include <stdio.h>
main()
{
int LIG; /* number of lines */
int L; /* line counter */
int ESP; /* number of spaces */
int I; /* character counter */
do

{
Number of lines:
scanf("%d", &LIG);
}
while (LIG<1 || LIG>20);
for (L=0; L<LIG; L++)
{
ESP = LIG-L-1;
for (I=0 ; I<ESP ; I++)
putchar(' ');
for (I=0 ; I<2*L+1 ; I++)
putchar('*');
putchar('\n');
}
return (0);
}

35
25. Write a program that reads two strings CH1 and CH2 and copies the
first half of CH1 and the first half of CH2 into a third chain CH3.
Display the result.
#include <stdio.h>
#include <string.h>
main()
{
/* Declarations */
char CH1[100], CH2[100]; /* given strings */
char CH3[100]=""; /* result string */
Data entry
Enter the first string:
gets(CH1);
Enter the second string:
gets(CH2);
/* Treatments */
strncpy(CH3, CH1, strlen(CH1)/2);
strncat(CH3, CH2, strlen(CH2)/2);
/* Displaying the result */
Half "%s" plus half "%s" gives "%s"
CH1, CH2
CH3);
return (0);
}

26. Write a function that takes an array of integers as a parameter and calculates the maximum of
all the elements of the table.
#define NB_ELEM_MAXI 100
int max(int t[NB_ELEM_MAXI])
{
int i;
int max = t[0];
for (i = 1; i < MAX_ELEMENTS; i++)
{
if (max < t[i])
max = t[i];
}
return max;
}
27. Write a function that takes an array of integers as a parameter and calculates the sum of
elements.
#define NB_ELEM_MAXI 100
int sum(int t[NB_MAX_ELEMS])
{
int i;
int sum = t[0];
for (i = 1; i < MAX_ELEMENTS; i++)
sum += t[i];

36
return sum;
}
28.A) Write a program that takes two int type variables and exchanges their
content and displays the new values of the variables.
B) We propose to redo question a) by carrying out the exchange of values internally.
Function pass by value. Write a function that swaps the contents of two passed variables.
by address. Write the main program that inputs two variables, exchanges them by calling
the function and displays the new content of the variables.
a)
int main()
{
int a = 14, b = 5;
int t;
a = %d; b = %d
t = a;
a = b;
b = t;
a = %d; b = %d\n
return 0;
}
b)
void exchange(int *a, int *b)
{
int t;
t = *a;
*a = *b;
*b = t;
}
int main()
{
int a = 14, b = 5;
a = %d; b = %d
exchange(&a, &b);
a = %d; b = %d
return 0;
}

37

You might also like