0% found this document useful (0 votes)
5 views16 pages

Control Strctres (Test)

Uploaded by

kboudjemline05
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)
5 views16 pages

Control Strctres (Test)

Uploaded by

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

Chapter 2

Control structures

33
Dr. Samir FENANIR Chapter 2 : Control structures

1 Introduction
In the previous chapter, we saw that the execution of an algorithm is carried out sequentially,
that is to say instruction after instruction (in order). Sometimes it is necessary not to execute
all the instructions or to repeat the same instructions several times. This chapter explains
how, in an algorithm, we can:

• To not execute a portion of the instructions, that is, to make a jump in the algorithm
using conditional structures.

• To go back and execute the same part of an algorithm multiple times in a row, using
repetitive structures.

2 Conditional structures
Conditional structures or alternatives are used to choose between the execution of two
different blocks based on a certain condition.

2.1 Tests simples


A simple test contains a single block of instructions. Based on a condition (logical expression),
the block of instructions is either executed or not executed. If the condition is true, the block
is executed; otherwise, it is not executed. The syntax of a simple test is as follows:
Syntax :

• The condition is a logical expression that can be true or false.

• If the condition is true, the block of instructions is executed.

• If the condition is false, we go directly to endIf.

34
Dr. Samir FENANIR Chapter 2 : Control structures

• The instruction block is made up of one or more instructions.

• In C, if there is only one statement in the if block, the use of curly braces { } is optional.

• For the readability of the program, some of its parts are indented compared to others,
this is called indentation. This allows you to quickly show the start and end of
instruction blocks as well as the start and end of the program.

Example : Write an algorithm and a C program that ask the user for an integer A, test if this
number is positive (A ≥ 0), and display “positive”.

Algorithm Positive_num #include <stdio.h>


Variable A : integer int main( )
Begin {
1. read(A) int A ;
2. If (A ≥ 0) then scanf("%d", &A) ;
3. write ("positive") if (A >= 0)
4. EndIf printf("positive") ;
End }

• Instruction 1 asks the user to enter a value, then, instruction 2 tests the condition
(A ≥ 0) ;
• For example, if the value entered by the user is equal to 5, then the condition is true,
and instruction 3 will be executed, displaying ’positive’ on the screen.;
• For example, if the entered value is equal to −8, the condition is false, so we move
directly to EndIf.

Note : "In this example, the ’If’ block consists of only one instruction, which is why we
omitted the curly braces."

Exercise 1: Write an algorithm that calculates the inverse of an integer.


Solution:

35
Dr. Samir FENANIR Chapter 2 : Control structures

Algorithm inverse
Variable A : integer
Begin
read (A)
If (A ̸= 0) then
write ("The inverse of ", A, "is : ", 1/A)
EndIf
End

Exercise 2: Write an algorithm and its C translation that calculates the absolute value of
an integer.
Solution:

Algorithm Absolute #include <stdio.h>


Variable x : real int main( ) {
Begin float x ;
read (x) scanf("%f", &x) ;
If (x < 0) then if (x < 0)
x ← −x x = −x ;
EndIf printf("The absolute value is : %f ", x);
write ("The absolute value is : ", x) return 0 ;
End }

Exercise 3: Write an algorithm that sorts the values of three variables A, B, and C in
ascending order. Provide the execution trace with the values 5, 6, and 2.

Solution:

36
Dr. Samir FENANIR Chapter 2 : Control structures

2.2 Alternative test


An alternative test contains two blocks of instructions. If the condition is true, the first block
is executed; otherwise, the second block is executed. The syntax of an alternative test is as
follows:

Syntax:

• If the condition is true, block of instructions 1 will be executed.

• If the condition is false, instruction block 2 will be executed.

• In C, curly braces {} are not necessary when instruction blocks have only one instruc-
tion.

37
Dr. Samir FENANIR Chapter 2 : Control structures

Example : Write an algorithm using both forms of tests to read a student’s average, then
display whether the student is Admitted or deferred.

It is notable that the second version of the algorithm using the alternative test is better than
the version using the simple test. Indeed, the first version performs two tests to determine
whether the student is accepted or deferred, while the second version performs only one test.
compound conditions A compound condition is a condition formed by several simple
conditions connected by logical operators: And, Or, Not.
Examples :

• x is between 2 and 6 : (x ≥ 2) and (x ≤ 6) ; it is true if both conditions are true.

• n divisible by 3 or by 2 : (n mod 3=0) ou (n mod 2=0); it is false if both conditions are


false.

• The age is between 30 and 40 Or the Salary ≤ 20000 : ((Age ≥ 30) And (Age ≤ 40))
Or (Salary ≤ 20000)

• The opposite of the last condition: Not (((Age ≥ 30) And (Age ≤ 40)) Or (Salary
≤ 20000)) ⇐⇒ ((Age < 30) Or (Age > 40)) And (Salary > 20000)

Exercise 1: Write an algorithm that reads an integer and checks whether it is even or odd.
Translate it into C.

Solution:

38
Dr. Samir FENANIR Chapter 2 : Control structures

Algorithm Even_Odd #include <stdio.h>


Variable A : integer int main( )
Begin { int A ;
read (A) scanf("%d", &A) ;
If (A mod 2 = 0) then if (A % 2 == 0)
write (A, " is even") printf("%d is even", A) ;
else else
write (A, " is odd") printf("%d is odd", A) ;
EndIf return 0;
End }

Exercise 2: Write an algorithm that, after asking the user for a day, month, and year,
determines whether it is a valid date or not.

Solution:

Exercise 3: Write an algorithm that allows determining the sign of a product of two
numbers without performing any calculation.

Solution:

39
Dr. Samir FENANIR Chapter 2 : Control structures

Exercise 4: Write an algorithm that calculates the largest and smallest among three real
values. Provide the execution trace using the values: 4, 1, and 9.

Solution: The idea of this algorithm is to determine the min and max between two numbers
A and B, then compare them with the third number C.

2.3 Nested tests


Tests can have any degree of nesting (one included within another), meaning the instructions
to execute after ’if’ and/or ’else’ can themselves be tests.
Example 1:

40
Dr. Samir FENANIR Chapter 2 : Control structures

• To execute instructions A: condition1 = True and condition2 = True

• To execute instructions B: condition1 = True and condition2 = False

• To execute instructions C: condition1 = False and condition3 = True

Example 2: Using the two forms of tests: simple and nested. Write two versions of an
algorithm that asks the user for a number and informs them whether the number is positive,
negative, or zero.

41
Dr. Samir FENANIR Chapter 2 : Control structures

The first version is easier to write and more readable. However, it requires the computer
to evaluate three successive tests even though they all concern the same thing (the value of
the variable n), which affects the computer’s execution time. Indeed, with the second version,
if n is less than zero, it immediately writes "This number is negative" and proceeds directly
to the end without being slowed down by evaluating the other possibilities.

Exercise 1: Write an algorithm that solves a first-degree equation: AX +B = 0. Graphically


represent the tests.

Solution:

42
Dr. Samir FENANIR Chapter 2 : Control structures

Exercise 2: Write an algorithm that solves a second-degree equation: AX 2 + BX +C = 0


(assuming that A ̸= 0). Graphically represent the tests.

Solution:

43
Dr. Samir FENANIR Chapter 2 : Control structures

Exercise 3: Write an algorithm that calculates the net pay, such as: the company makes:

• A 10% discount if the total amount exceeds 10,000 DA.

• A 20% discount if the total amount exceeds 20,000 DA."

Solution:

Exercise 4: We want to read a student’s average and then display their grade (Very good if
Avg ≥ 16, Good if Avg ≥ 14, and Fair if Avg ≥ 12). Write two versions of an algorithm
using both forms of tests: simple and nested."
Solution:

44
Dr. Samir FENANIR Chapter 2 : Control structures

2.4 Multiple-choice tests


This structure allows choosing the instructions to execute based on the value of an expression
and is a more advantageous replacement for a series of nested if structures.

45
Dr. Samir FENANIR Chapter 2 : Control structures

Syntax:

• The selector is an expression of scalar type (integer, character, or boolean).

• The "else" part is optional.

• If the block of instructions is the same for a set of values, then you can group them
together separated by commas or in the form of an interval (Vi ,V j orVi ..V f ).

• In C, the "break" statement allows you to exit the "switch" structure after executing the
corresponding block of instructions; otherwise, all subsequent blocks of instructions
will be executed.

Exercise 1: Write an algorithm that reads the number of a month and displays the corre-
sponding month’s name.

Solution:

46
Dr. Samir FENANIR Chapter 2 : Control structures

Exercise 2: Write an algorithm that reads the number of a month and displays the corre-
sponding season.

Solution:

Exercise 3: Write an algorithm that reads a character and then displays whether it is an
uppercase or lowercase letter.
Solution:

Algorithm Letter
Variable L : character
Begin
read (L)
Case L of
‘a’..’z’: write ("lowercase")
‘A’..’Z’: write ("uppercase")
else
write ("Error")
endCase
End

47
Dr. Samir FENANIR Chapter 2 : Control structures

Exercise 4: Write a C program that allows you to create a menu simulating a calculator.
The menu should be presented to the user as follows:
**************** MENU *******************
1 : ———-Sum ———————
2 : ———-Product ———————-
3 : ———-Subtraction—————-
*****************************************
Enter your choice?

Solution:

#include <stdio.h>
int main( )
{ int A, B, C;
printf("Give two integers");
scanf("%d %d", &A, &B);
printf("*****Menu*****\n");
printf("1:—–Sum——-\n)";
printf("2:—–Product——-\n)";
printf("3:—Subtraction–\n");
printf("Enter your choice?");
scanf("%d", &C);
switch (C) {
case 1: printf("%d", A+B); break;
case 2: printf("%d", A*B); break;
case 3: printf("%d", A-B); break;
default: printf("Error");
}
}

3 Repetitive Structures (Loops)


Loops are used to repeat the execution of a block of instructions a certain number of times
based on the value of a condition. There are 03 types:

• The While Loop

• The For Loop

48

You might also like