私が入力を与えると、11
それは最終的に11 - 1 = 10
どのように論理を放棄するの if(c == n) { printf("%d", n);
でしょうか?
for ループの条件を正しく理解するようになりました。
for ( c = 2 ; c <= n - 1 ; c++ )
^^^^^^^^^^^^
2 <= 11 - 1 -> True // {for block executes }
3 <= 11 - 1 -> True // {for block executes }
:
:
9 <= 11 - 1 -> True // {for block executes }
10 <= 11 - 1 -> True // {for block executes }
11 <= 11 - 1 -> False breaks //{And Now for block NOT executes}
if (c == n)
^^^^^^
11 == 11 -> True // {if block executes}
for ループ条件 に従って、 value が と等しくなるとc <= n - 1
ループが中断されます。したがって、is equals to ループ条件が true の場合、各反復で(インクリメントを使用して)が1 ずつインクリメントされると、条件が false になり、ループが中断されます。c
n
n
11
c = 2
c = 10
c
c++
c
11
n
c <= n - 1
if 条件 (for ループの後) のc
値を と比較しn
ます。あれは:
if ( c == n )
// 11 == 11 that is true
for n
=11
となり、and c
= 11
if condition が true と評価されprintf()
、if が実行される場合に関連付けられます。
c = n
また、for ループは for が素数の場合にのみ終了することを理解することも重要ですn
が、 が素数でないと仮定すると、for ループ内のネストされたブロック内の ステートメントにより、 for ループは以下の値でn
中断します。c
n - 1
break;
if
for( c = 2; c <= n - 1; c++ )
{
if(n % c == 0)<=="for Non-prime `n`, if condition will be true for some `c < n - 1`"
{ ^^^^^^^^^^^ True
printf("%d is not prime.\n", n);
break; <== "move control outside for-loop"
} // |
} // |
// <---------+ // if break; executes control moves here with c < n - 1
if (c == n)<== "this condition will evaluates FALSE"
^^^^^^^^ False
たとえば、if n = 8
then の for ループの最初の反復で、値c = 2
if 条件が== = Trueif(n % c == 0)
として評価され、 ifブロック内のステートメントが制御を for ループの外に移動します (図に示すように)。 if(8 % 2 == 0)
if( 0 == 0)
break;
この時間の for ループは条件により終了していませんが、外側の for ループの値よりも小さいため c <= n - 1
にブレーキがかけられているため 、False と評価されます。if(n % c == 0)
c
n
if (c == n)