0% found this document useful (0 votes)
6 views7 pages

Conditional Instructions in Programming

Uploaded by

Zaki Bechani
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)
6 views7 pages

Conditional Instructions in Programming

Uploaded by

Zaki Bechani
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

Algorithmique et structures de données 1 Chapitre 3 : Instructions conditionnelles

Chapter 3: Conditional Instructions

1. Introduction
A program consists of instructions. Most of these instructions are executed in the order in which they
appear. Once an instruction is executed, it moves to the next instruction (sequential). Instructions are often
separated by a semicolon ";". However, some instructions modify the program flow, known as control
structures. For example: conditional structures, loops, function calls, and unconditional jump instructions. The
conditional structure comes in three types: the simple conditional structure (if then), the complex conditional
structure (if then else), and the multiple-choice structure (switch).
2. The Simple Conditional Structure "if then"
In programming, we often encounter cases where we need to decide whether an instruction should be
executed or not based on whether a condition is true or false. For example, in a dessert recipe, you might find
instructions like: If you have almonds, add them to the recipe, or if you like lemons, add a little more. The
program's execution flow will change as the input changes. To express conditions in programming, we use the
if...then test, which is the simplest conditional instruction. It consists of two parts:
 Condition: A Boolean expression with a value of either true or false.
 Block of instructions: executed if the condition is true, or ignored if the condition is false.
2.1. Syntax:
Algorithm C
if Condition then if (Condition)
Block of instructions {
EndIf Block of instructions
The rest of the instructions }
The rest of the instructions
The words "if," "then," and "EndIf" (or "fi") are reserved words in the algorithm. The same applies to
"if" in C. In the algorithm, the condition is always between "if" and "then," while in C, it is always enclosed
in parentheses (). To build the condition, we use comparison operations (>, <, =, ≠, ...) and logical operations
(and, or, not, ...).
Instructions belonging to the "if" in C are enclosed in curly braces {} which can be omitted if they
contain only one instruction. (Optional {}). If we find a set of instructions after the "if," and we don't find the
curly braces, then only the first instruction is associated with the condition, and the rest of the instructions will
always be executed regardless of the condition. However, if there is more than one instruction inside the curly
braces {}, then both curly braces are mandatory.
Note:
In C, the Boolean type is represented by an int. False is represented by 0, and true is any number other
than 0.
 There is no ";" after }.
2.2. Flowchart

yes Cond
Inst Bloc ?

No

inst

2.3. Execution
The execution process of the conditional instruction is performed by evaluating the condition, which
results in a Boolean logical value. If the result is true, the block of instructions between "then" and "EndIf" in
Algorithmique et structures de données 1 Chapitre 3 : Instructions conditionnelles

the algorithm, or between {} in C, is executed, followed by the rest of the program instructions. If the result
is false, the instructions between "then" and "EndIf" are ignored, and the rest of the program instructions are
executed directly.
2.4. Example
Write a program that reads an integer, then displays a warning if it's negative, and finally shows its square.
Algorithm C screen
algorithm root #include <stdio.h>
var x : integer int main()
begin {
write ("Enter a number: ") int x ;
read (x) printf("Enter a number: \n") ;
If x<0 then scanf("%d", &x) ;
write ("nbr is negative ") if ( x<0 )
End If {// can be removed
write ("the square is " , x*x) printf("nbr is negative
end \n") ;
}
printf("the square is %d" ,
x*x) ;
}

3. The Complex Conditional Structure "if then else"


In a simple conditional, "if" specifies what to do if the condition is true, but not what to do if it's false.
However, sometimes it's necessary to decide what to do in both cases. This leads to the "if else" (if...then...else)
structure, which is an extension of the simple "if." The complex conditional structure "if else" consists of three
parts:
 Condition: A Boolean expression with a true or false value.
 First block of instructions: executed if the condition is true, or ignored if false.
 Second block of instructions: executed if the condition is false, or ignored if true.
3.1. Syntax:
Algorithm C
If Condition then if (Condition)
instruction block 1 {
else instruction block 1
instruction block 2 }
End If else
The rest of the instructions {
instruction block 2
}
The rest of the instructions
The word "Else" is a reserved word in the algorithm. The same applies to "else" in C. In C, {} can be omitted
if it contains only one instruction. If there is a set of instructions after "if" or after "else," and curly braces are
not found, it means that only the first instruction is related to "if" or "else."
3.2. Flowchart
no
yes Con
Inst Bloc d? Inst Bloc2

inst

3.3. Execution
3.3. Execution The conditional instruction is executed by evaluating the condition, which results in a Boolean
value. If the result is true, the first block of instructions between "then" and "else" in the algorithm, or between
Algorithmique et structures de données 1 Chapitre 3 : Instructions conditionnelles

{} before "else" in C, is executed, followed by the rest of the program instructions. If the result is false, the
second block of instructions between "else" and "EndIf" in the algorithm, or between {} after "else" in C, is
executed, followed by the rest of the program instructions.
3.4. Example
Write a program that calculates the absolute value of an integer and displays it on the screen.
Algorithm C screen
algorithm absolute #include <stdio.h>
var x, y : integer int main(){
begin int x, y ;
write ("Enter a nbr: ") printf("Enter a nbr:\n") ;
read (x) scanf("%d", &x) ;
if x>=0 than if ( x>=0 )
yx { // can be deleted
if ( x>=0 )
else y=x ;
} y=x ;
y-x else
End If else
{ // can be deleted y=-x ;
write ("|" , x ,"|=",y)
end y=-x ;
}
printf(("|%d|=%d", x, y)) ;
}
3.5. Conditional assignment in C
If we have a variable v takes one of the values v1 or v2 depending on condition b, i.e. :
if (b)
v=v1 ;
else
v=v2 ;
In this case, the “? : ” can be used and its syntax is as follows:
condition ? expression_true : expression_false
 condition is a Boolean condition
 expression_true The expression returned if the condition is true.
 expression_false The expression returned if the condition is false
Example
v=b ? v1 :v2 ;
result = average >=10 ? " Admitted" : " Adjourned" ;
3.6. If-else extension
" If-else" can be used to test multiple conditions and to select the appropriate treatment for each case.
For instance: to determine whether a student is accepted or not, there are several cases. Either they are accepted
without compensation, or they are accepted with compensation, or they are accepted but with debts, or they
are postponed. To determine this, one must examine the averages of the first and second semesters (s1 and
s2), the annual average (MA), and the total earned credits (Crd).
The solution
Algorithm C
algorithm absolute #include <stdio.h>
var s1, s2, MA: real int main(){
Crd : integer float s1, s2, MA ;
begin int Crd ;
write ("Enter first and second printf("Enter first and second semester
semester averages ") averages \n") ;
read (s1,s2) scanf("%f%f", &s1, &s2) ;
write ("Enter annual average ") printf("Enter annual average \n") ;
read (MA) scanf("%f", &MA) ;
write ("Enter total credits ") printf("Enter total credits \n") ;
read (Crd) scanf("%d", &Crd) ;
If s1>=10 and s2>=10 then if ( s1>=10 && s2>=10 )
Algorithmique et structures de données 1 Chapitre 3 : Instructions conditionnelles

write("admitted without compensation printf("admitted without


") compensation") ;
else else if ( MA>=10 )
if MA>=10 then printf("admitted with compensation") ;
write("admitted with else if ( Crd>=45 )
compensation") printf("admitted with debts ") ;
else else
if Crd>=45 then printf("adjourned ") ;
write ("admitted with debts ") }
else
write ("adjourned ")
end if
end if
end if
end
4. The Multiple-Choice Conditional Structure "switch"
To choose an action among multiple options, we use the "switch" statement. However, when dealing with
more than two options, nested "if" statements can be used, resulting in nested "if" statements for each choice.
This can make the program harder to read. The "switch" test is a special case of nested "if else" statements. It
determines which block of code to execute based on the value of the tested variable. It is used when we have
multiple outcomes and the condition is tested multiple times using the same variable. The "switch" statement
is more readable and consists of:
 The expression to test, typically a variable.
 The values to test with corresponding blocks of instructions.
 An optional default block if there is no match with any value.
4.1. Syntax
Algorithm C
case expression of switch ( expression ) {
val_1 : instruction block 1 case val_1 :
val_2 : instruction block 2 instruction block 1
… break ;
val_n : instruction block n …
else case val_n :
another instruction block instruction block n;
End case break ;
The rest default:
another instruction block
}
The rest
The words "Case" "else" and "End Case" (or " EndCase") are reserved words in the algorithm. The same
applies to "switch" "case" and "default" in C.
 Expression: An expression that calculates an integer or character value. It's typically a variable.
 val_1, ..., val_n : Values or constants of the same type as the expression.
 Block of instructions: One or more instructions executed if the expression value matches Value_i.
Note: switch is used instead of nested “if” we're going to test a single instruction or variable, of integer or
character type, several times with constant values.
4.2. Rules regarding switch
 The curly braces {} of the switch and the parentheses () are necessary and cannot be omitted.
 Each Value_i must be different from the others. For example, writing "case 1" twice is illegal.
 Value_i can be placed in any order. However, it's recommended to order them in ascending order for
better readability.
 A block of instructions can contain any number and type of instructions.
Algorithmique et structures de données 1 Chapitre 3 : Instructions conditionnelles

 The "break;" statement is optional. It's used to exit a switch immediately, moving the program flow
out of the switch.
 The default block is optional. If no Value_i matches, the execution context will move to the default
block. It should be the last case.
4.3. Flowchart

yes exp=
inst Bloc 1 val1

no

yes exp=
inst Bloc 2 val2

no

yes exp=
inst Bloc n val n

no
Other inst bloc

insts

4.4. Execution
The "switch" statement is executed by evaluating the expression, then jumping to the block of
instructions corresponding to the matched Value_i. After that block is executed, the execution will continue
until it encounters a "break;" statement or reaches the end of the switch. If there is no match, the execution
will move to the default block (if present), then continue with the rest of the program instructions.
The execution of "switch" in C slightly differs from the algorithm's "case" In C, after executing the
block for Value_i, if no "break;" statement is encountered, the execution will continue with the subsequent
block until a "break;" statement is reached. The execution will then move to the rest of the instructions outside
the switch.
To make "switch" equivalent to "case algo" a "break;" statement should be added at the end of each
block.
If multiple values share the same block of instructions, the algorithm can use a comma. In C, the first
value should not have instructions or a "break;" statement. Assuming values 7 and 9 have the same treatment:
Algorithm:
algorithm C
7 ,9 : instruction block case 7 :
case 9 :
instruction block
break ;
4.5. Example
Write a program that reads an integer less than 10 and displays the corresponding English word on the screen.
Algorithm C The display
Algorithmique et structures de données 1 Chapitre 3 : Instructions conditionnelles

algorithm conversion #include <stdio.h>


var nb : integer int main(){
begin int nb ;
write ("enter a nbr ") printf("enter a nbr \n") ;
read (nb) scanf("%d", &nb ) ;
case nb of switch ( nb ) {
0 : write ("zero") case 0 : printf("zero") ;
1 : write ("one") break ;
2 : write ("two") case 1 : printf("one") ;
… break ;
9 : write ("nine") …
else case 9 : printf("nine") ;
write ("not treated") break ;
End case default:
end printf("not treated") ;
}
return 0 ;
}
5. Branching Instructions
Branching is the process of moving between executed program instructions by the processor, where it
performs a "jump" to a specific address instead of continuing to execute instructions sequentially. There are
four instructions in C that can unconditionally modify the execution flow of a program: break, goto, continue,
and return.
5.1. Break Statement
We've already seen it with "switch," where it ends the "switch" instruction, moving the flow to the first
instruction after "switch." In the case of a nested "switch," it only exits the immediate enclosing "switch." It's
also used to exit loops (covered in the next lesson). In this case, "break;" is usually within an "if."
Example
switch (grade){
case ‘A’ :
case ‘a’ : printf("excellent\n") ;
break ;
case ‘b’ : printf("good\n") ;
case ‘c’ : printf("you can do better\n") ;
break ;
default : printf("try again\n") ;
}
 If grade contains the letter a or A, excellent.
 If it contains b ،it will appear good and you can do better
 If it contains the letter c, it only shows that you can do better.
 If it contains another character, try again.
5.2. Goto Statement
It transfers the program execution to a named instruction. This name, or "label," is preceded by a colon
":". Any instruction can be named with a valid identifier followed by a colon.
Label syntax: label : instruction;

where label is a valid identifier. Such as:


here : printf("zero") ;
Syntax for calling: To access this instruction from anywhere, use the following syntax:
goto label ;
where "label" is the name of the instruction, e.g.: To access the instruction "here" from anywhere, use:
goto here ;
Note:
Algorithmique et structures de données 1 Chapitre 3 : Instructions conditionnelles

 "case" and "default" are special naming methods used within a "switch."
 Goto can be used to repeat instructions without the need for loops.
 It's advisable not to use "goto" and labels extensively, as it makes the program difficult to understand
and maintain for humans.
Example:
again :

goto again ;
5.3. continue Statement
It's used with loops to move the flow to the end of the loop and directly to the next iteration, without
completing the loop instructions. It's typically within an "if."
Syntax continue ;

5.4. Return Statement


It's used to exit functions and return a result. (semester 2)
Syntax: return expression ;

Example: return 0 ;

As commonly used at the end of the main() function

You might also like