Pascal-if-then-else-statement

提供:Dev Guides
移動先:案内検索

パスカル-if then elseステートメント

*if-then* ステートメントの後にオプションの *else* ステートメントを続けることができます。これは、ブール式が *false* の場合に実行されます。

構文

if-then-elseステートメントの構文は-

if condition then S1 else S2;

ここで、 S1S2 は異なるステートメントです。 文S1の後にセミコロンが続かないことに注意してください。 if-then-elseステートメントでは、テスト条件が真の場合、ステートメントS1が実行され、S2はスキップされます。テスト条件が偽の場合、S1はバイパスされ、ステートメントS2が実行されます。

例えば、

if color = red then
   writeln('You have chosen a red car')

else
   writeln('Please choose a color for your car');

ブール式 condition がtrueと評価されると、if-thenコードブロックが実行されます。そうでない場合、elseコードブロックが実行されます。

Pascalは、ゼロ以外およびnil以外の値をすべてtrueと見なします。ゼロまたはnilの場合、false値と見なされます。

流れ図

パスカルif-then-elseステートメント

概念を説明する完全な例を試してみましょう-

program ifelseChecking;
var
   { local variable definition }
   a : integer;

begin
   a := 100;
   ( *check the boolean condition* )
   if( a < 20 ) then
      ( *if condition is true then print the following* )
      writeln('a is less than 20' )

   else
      ( *if condition is false then print the following* )
      writeln('a is not less than 20' );
      writeln('value of a is : ', a);
end.

上記のコードをコンパイルして実行すると、次の結果が生成されます-

a is not less than 20
value of a is : 100

if-then-else if-then-elseステートメント

if-thenステートメントの後にオプションのelse if-then-elseステートメントを続けることができます。これは、単一のif-then-else ifステートメントを使用してさまざまな条件をテストするのに非常に便利です。

if-then、else if-then、elseステートメントを使用する場合、留意すべき点はほとんどありません。

  • if-thenステートメントには0個または1個のelseを含めることができ、else ifの後に来る必要があります。
  • if-thenステートメントは、他のifのゼロから多数まであり、elseの前に来る必要があります。
  • else ifが成功すると、残りのelse ifまたはelseはテストされません。
  • 最後のelseキーワードの前にセミコロン(;)を指定しませんが、すべてのステートメントを複合ステートメントにすることができます。

構文

Pascalプログラミング言語のif-then-else if-then-elseステートメントの構文は次のとおりです-

if(boolean_expression 1)then
   S1 ( *Executes when the boolean expression 1 is true* )

else if( boolean_expression 2) then
   S2 ( *Executes when the boolean expression 2 is true* )

else if( boolean_expression 3) then
   S3 ( *Executes when the boolean expression 3 is true* )

else
   S4; ( *executes when the none of the above condition is true* )

次の例は、概念を示しています-

program ifelse_ifelseChecking;
var
   { local variable definition }
   a : integer;

begin
   a := 100;
   ( *check the boolean condition* )
   if (a = 10)  then
      ( *if condition is true then print the following* )
      writeln('Value of a is 10' )

   else if ( a = 20 ) then
      ( *if else if condition is true* )
      writeln('Value of a is 20' )

   else if( a = 30 ) then
      ( *if else if condition is true * )
      writeln('Value of a is 30' )

   else
      ( *if none of the conditions is true* )
      writeln('None of the values is matching' );
      writeln('Exact value of a is: ', a );
end.

上記のコードをコンパイルして実行すると、次の結果が生成されます-

None of the values is matching
Exact value of a is: 100