Pascal - if-then 語句



if-then 語句是控制語句中最簡單的形式,通常用於決策制定和更改程式執行控制流。

語法

if-then 語句的語法如下 −

if condition then S

其中,condition 是一個布林值或關係條件,S 是一個簡單或複合語句。if-then 語句的示例如下 −

if (a <= 20) then
   c:= c+1;

如果布林表示式 condition 計算結果為真,則 if 語句內的程式碼塊將得以執行。如果布林表示式計算結果為假,則 if 語句結束後的第一組程式碼(在封閉的 end;之後)將得以執行。

Pascal 將任何非零且非空值視為真,而如果它為零或空,則視為假。

流程圖

Pascal if-then statement

示例

我們嘗試一個完整的示例來說明該概念 −

program ifChecking;

var
{ local variable declaration }
   a:integer;

begin
   a:= 10;
   (* check the boolean condition using if statement *)
   
   if( a < 20 ) then
      (* if condition is true then print the following *) 
      writeln('a is less than 20 ' );
   writeln('value of a is : ', a);
end.

編譯並執行以上程式碼時,它將產生以下結果 −

a is less than 20
value of a is : 10
pascal_decision_making.htm
廣告