for迴圈的語句執行順序

來源:互聯網
上載者:User

在一個技術QQ群中,試著做了一道C的題,感覺是考察for迴圈的執行流程.

原題: 在C語言中,下列代碼的輸出結果是 ( ) (選擇一項)

void main( )
{
  int i = 0, j = 10;
    for(i=0;i<j;i++,j--)
    {
        if(j==10)
        {
            printf("%d,%d ",i,j);
            j--;
        }
        j++;
    }
    printf("%d,%d ",i,j);
}

  a) 0,10
    9,9

  b) 0,10
    10,10

  c) 10,10

  d) 9,11

群裡居然有不少人都選了B,那個提問者還一直在問正確的結果。

最終的正確結果是:A.

哈哈,好基本的知識。

後來偶就順手寫了一個代碼,大家做了它可以對for迴圈的運算順序就比較清楚啦。


int print1(int i,int j)
{        
    printf(" 執行判斷條件,i=%d,j=%d ",i,j);
    return 1;
}

void main( )
{
    int i = 0, j = 10;
    
    for(i=0;((print1(i,j)) && (i<j));
        i++,j--,printf("執行for()中的第三個語句,i=%d,j=%d ",i,j))
    {
        if(j==10)
        {
            printf("%d,%d ",i,j);
            j--;
        }
        j++;
        printf("執行for迴圈體中的最後一句,i=%d,j=%d ",i,j);
    }
    printf(" %d,%d ",i,j);
}

 運行結果是:

執行判斷條件,i=0,j=10
0,10

執行for迴圈體中的最後一句,i=0,j=10
執行for()中的第三個語句,i=1,j=9

執行判斷條件,i=1,j=9
執行for迴圈體中的最後一句,i=1,j=10
執行for()中的第三個語句,i=2,j=9

執行判斷條件,i=2,j=9
執行for迴圈體中的最後一句,i=2,j=10
執行for()中的第三個語句,i=3,j=9

執行判斷條件,i=3,j=9
執行for迴圈體中的最後一句,i=3,j=10
執行for()中的第三個語句,i=4,j=9

執行判斷條件,i=4,j=9
執行for迴圈體中的最後一句,i=4,j=10
執行for()中的第三個語句,i=5,j=9

執行判斷條件,i=5,j=9
執行for迴圈體中的最後一句,i=5,j=10
執行for()中的第三個語句,i=6,j=9

執行判斷條件,i=6,j=9
執行for迴圈體中的最後一句,i=6,j=10
執行for()中的第三個語句,i=7,j=9

執行判斷條件,i=7,j=9
執行for迴圈體中的最後一句,i=7,j=10
執行for()中的第三個語句,i=8,j=9

執行判斷條件,i=8,j=9
執行for迴圈體中的最後一句,i=8,j=10
執行for()中的第三個語句,i=9,j=9

執行判斷條件,i=9,j=9

9,9
--------------

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.