Cours 4
Cours 4
FACULTY of TECHNOLOGY
Technical Sciences Engineers Department
Computer Science 1
Lesson 04: Control Statements
Example 1
Write a pseudo-code that decides whether an integer is
positive
Algorithm positive ;
Variables :
A : integer ;
Start
Input (A) ;
If ( A > 0 )
Output(A, ’is positive’) ;
EndIf ;
End.
Example 2
Write a flowchart and the pseudo-code to read two
integers A and B then puts the biggest number in B and
the smallest one in A
Algorithm max ;
Variables :
A, B, C : integer ;
Start
Input (A,B) ;
If ( A > B )
C ← A;
A ← B;
B ← C;
EndIf ;
Output(A,B) ;
End.
Example
Write a flowchart then a pseudo-code that calculate the
average of two semesters and then print out if the student
has succeeded or not
if (condition)
Block of statements ;
If the block of statements contains more than one
instruction, we use the braces ({ and })to limit the block
Example
Write a pseudo-code then a C program to calculate the
magnitude of an integer
Algorithm v_absolue ;
Variables : #include<stdio.h>
A : integer ; int main(){
Start int A;
Input (A) ; scanf("%d", &A);
If ( A < 0 ) if (A<0)
A ← -A ; A=-A;
EndIf ; printf("%d", A);
Output(A) ; return 0;
End. }
Example 2
Write a C program that reads two integers A and B then
puts the biggest number in B and the smallest one in A
Algorithm MaxA ;
Variables : #include<stdio.h>
A, B, C : integer ; int main(){
Start int a, b, c;
Input (A,B) ; scanf("%d%d", &a, &b);
If ( A > B ) if (a<b)
C ← A; {c=a;
A ← B; a=b;
B ← C; b=c;}
EndIf ; printf("%d %d", a,b);
Output(A,B) ; return 0;
End. }
If ( condition )
Instructions
Else
Instructions
EndIf ;
if ( condition )
Instruction1 ;
else
Instruction2 ;
Example
Write a C program to calculate the average of two
semesters and then print out if the student has succeeded
or not
Algorithm moyenne ;
Variables : #include<stdio.h>
N1, N2, Moy : real ; int main(){
Start float N1, N2, Moy;
Input(N1,N2) ; scanf("%f%f", &N1, &N2);
Moy ← (N1 + N2)/2 ; Moy = (N1+N2)/2;
If ( Moy >= 10 ) if (Moy>=10)
Output(’Success’) ; printf("Success");
Else else
Output(’Failure’) ; printf("Failure");
EndIf ; return 0;
End. }
What if N = 100 ?
Problem
Redundancy and too long algorithms
Solution
Use loops, called also repetitive or iterative statements
Example
Write a C program to calculate the power x n (x a none
null real and n > 0 a none null integer)
#include <stdio.h>
int main () {
int i, j;
for (i=0; i<4; i++) {
printf("\n Loop i, i is %d\n",i);
for (j=3; j>0; j--)
printf(" Loop j, j is %d\n",j);
}
return 0;
}
#include <stdio.h>
int main () {
int i, j;
for (i=0; i<=5; i++){
for (j=0; j<=i; j++)
{printf("O");}
printf("K\n");
}
return 0;
}