need explination !

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ayman723
    New Member
    • Sep 2006
    • 40

    need explination !

    I have this code and can't understand the result

    code

    # include < iostream >
    using std::cout;
    int main()
    {

    for ( int x=1; x<= 10; x+=3 )
    {
    if ( x<5)
    continue;
    cout << x*x <<" ";
    }

    }

    why do I get 49 and 100 , can anyone explain in plain english please.


    thanks
  • tyreld
    New Member
    • Sep 2006
    • 144

    #2
    Originally posted by ayman723
    I have this code and can't understand the result

    code

    # include < iostream >
    using std::cout;
    int main()
    {

    for ( int x=1; x<= 10; x+=3 )
    {
    if ( x<5)
    continue;
    cout << x*x <<" ";
    }

    }

    why do I get 49 and 100 , can anyone explain in plain english please.


    thanks

    First, lets look at what the continue keyword does. The continue keyword stops the current iteration of a loop and returns control at the begining of the loop.

    Now lets walk through the loop execution.

    First iteration. x = 1
    1< 5 so we hit the continue statement

    Second iteration x = x + 3 = 4
    4<5 so again we hit the continute statement

    Third iteration x = x + 3 = 7
    7>5 so we print x*x which = 49

    Fourth iteration x = x + 3 = 10
    10>5 so we print x*x which = 100

    Fifth iteration x = x + 3 = 13 (13 > 10 so the loop terminates)

    Comment

    • ayman723
      New Member
      • Sep 2006
      • 40

      #3
      thnks a million, that was easy :)

      thanks again for your quick responce

      Comment

      Working...