Professional Documents
Culture Documents
Cch s dng
2.1
Mi trng algorithmic
1:
2:
3:
Kt qu:
for all i such that 0 i 10 do
carry out some processing
end for
2.2
Kt qu
S0
2. Lnh if-then-else
\IF{<condition>} <text> \ENDIF
\IF{<condition>} <text1> \ELSE <text2> \ENDIF
\IF{<condition1>} <text1> \ELSIF{<condition2>} <text2> \ELSE <text3> \ENDIF
V d:
\begin{algorithmic}
\IF{C1}
\STATE B1
\ELSIF {C2}
\STATE B2
\ENDIF
\end{algorithmic}
Kt qu:
if C1 then
B1
else if C2 then
B2
end if
3. Lnh for
\FOR{<condition>} <text> \ENDFOR
\FORALL{<condition>} <text> \ENDFOR
V d:
\begin{algorithmic}[1]
\FORALL{$i$ such that $0\leq i\leq 10$}
\STATE carry out some processing
\ENDFOR
\end{algorithmic}
Kt qu:
1: for all i such that 0 i 10 do
2:
carry out some processing
3: end for
C thm TO
\begin{algorithmic}
\FOR{$i=0$ \TO $10$}
\STATE carry out some processing
\ENDFOR
\end{algorithmic}
for i = 0 to 10 do
carry out some processing
end for
4. Vng lp while
\begin{algorithmic}
\IF{\NOT ($year \bmod 400$ \XOR $year \bmod 100$ \XOR $year \bmod 4$)}
\STATE $year$ does not represent a leap year.
\ENDIF
\end{algorithmic}
if not (year mod 400 xor year mod 100 xor year mod 4) then
year does not represent a leap year.
end if
8. Lnh tr v gi tr v gi tr ng sai
\RETURN <text>
V d:
\begin{algorithmic}
\IF{$n$ is odd}
\RETURN \TRUE
\ELSE
\RETURN \FALSE
\ENDIF
\end{algorithmic}
if n is odd then
return true
else
return false
end if
9. Cc lnh khc
\PRINT <text>
\begin{algorithmic}
\PRINT \texttt{Hello, World!}
\end{algorithmic}
print Hello, World!
\COMMENT{<text>}
\begin{algorithmic}
\STATE do something \COMMENT{this is a comment}
\end{algorithmic}
do something {this is a comment}
10. V d tng hp
\begin{algorithmic}
\REQUIRE $n \geq 0$
\ENSURE $y = x^n$
\STATE $y \leftarrow
\STATE $X \leftarrow
\STATE $N \leftarrow
\WHILE{$N \neq 0$}
\IF{$N$ is even}
\STATE $X \leftarrow
\STATE $N \leftarrow
1$
x$
n$
X \times X$
N / 2$
\ELSE[$N$ is odd]
\STATE $y \leftarrow y \times X$
\STATE $N \leftarrow N - 1$
\ENDIF
\ENDWHILE
\end{algorithmic}
Require: n 0
Ensure: y = xn
y1
Xx
N n
while N 6= 0 do
if N is even then
X X X
N N/2
else {N is odd}
y yX
N N 1
end if
end while
2.3
Ty chn v t li cu hnh
2. return i
Mi trng algorithms
\end{algorithmic}
\end{algorithm}