Steven Rokkala
Steven Rokkala

Reputation: 19

Analyzing Code with Steps

So I know the output of the code is 8 2 but could someone show me how the value of i and j change after each step please.

Here is the link for the code:

using namespace std;

int main()
{
    int i; int j = 0;
    for ( i = 0; i < 7; i++)
    { 
        if(i % 2 == 1) 
        { 
            i = i + 2; j++;
        }
        else
        { 
            j = j + 2; 
        }
        j--;
    }

    cout << i <<" "<< j;
}

Upvotes: 0

Views: 88

Answers (2)

Ani Menon
Ani Menon

Reputation: 28257

Simplified your code by removing j++ from if-true, changing j=j+2 to j++ in if-false so that j-- after the if_else shall be removed. And also understanding code becomes easier.

int main()
{
    int i; int j = 0;
    for ( i = 0; i < 7; i++)
    { 
        if(i % 2 == 1) 
        { 
            i = i + 2;//add 2 in i for odd i
        }
        else
        { 
            j++; //add 1 in j for even i
        }

    }

    cout << i <<" "<< j;
}

Explanation :

i=0,j=0

Since, i=0 (even)
j=1 (even so j++)
i=1 (i++ for-loop)

i=3 (odd so add 2)
i=4 (i++ for-loop)
j=1 (unchanged)

i=4 (even)
j=2 (even so j++)
i=5 (i++ for-loop)

i=7 (odd so add 2)
j=2 (unchanged)
i=8 (i++ for-loop)

i=8 (i<7 for-loop exit)

i=2 & j=8

Upvotes: 0

4386427
4386427

Reputation: 44340

It will be

   int i; int j = 0;           // i==? j==0
----------------------------------------------
   for ( i = 0;                // i==0 j==0
                i < 7;         // TRUE
   if(i % 2 == 1)              // FALSE
   j = j + 2;                  // i==0 j==2
   j--;                        // i==0 j==1
                       i++)    // i==1 j==1
----------------------------------------------
                i < 7;         // TRUE
   if(i % 2 == 1)              // TRUE
   i = i + 2; j++;             // i==3 j==2
   j--;                        // i==3 j==1
                       i++)    // i==4 j==1
----------------------------------------------
                i < 7;         // TRUE
   if(i % 2 == 1)              // FALSE
   j = j + 2;                  // i==4 j==3
   j--;                        // i==4 j==2
                       i++)    // i==5 j==2
----------------------------------------------
                i < 7;         // TRUE
   if(i % 2 == 1)              // TRUE
   i = i + 2; j++;             // i==7 j==3
   j--;                        // i==7 j==2
                       i++)    // i==8 j==2
----------------------------------------------
                i < 7;         // FALSE

Upvotes: 4

Related Questions