user3358064 user3358064 - 1 month ago 6
C++ Question

I am not understanding how this for loop is working c++

#include <iostream>

using namespace std;

int main()
{
int x = 0;
for int (i=0; i<100; i++)
if (i%9 == 0) x = i;
else x = -1;
cout << x;
return 0;
}


This snippet of code returns the value 99.

When i read it line by line I understand it like this.


  1. Declare a variable x, assign it the value 0.

  2. For i = 0, i is less than 100, increment i by 1.

  3. if the remainder of i/9 is equal to 0, assign the value of i to x.

  4. If it isn't set x to be equal to -1

  5. Print out x



In the first step of the for loop i is assigned the value 0. 0 divided by 9 is equal to 0 which mets the conditions of the if statement so why would it not print out that x is equal to 0 instead of 99?

Answer

Line By Line

Ok lets go this over line by line as you said.

1) Declare a variable x, assign it the value 0.

#include <iostream>
int main()
{
    int x=0;
}

2) For i = 0, i is less than 100, increment i by 1.

#include <iostream>
int main()
{
    int x=0;
    for(int i=0; i<100; i++) {};
}

3) if the remainder of i/9 is equal to 0, assign the value of i to x.

#include <iostream>
int main()
{
    int x=0;
    for(int i=0; i<100; i++)
    {
        if(i%9==0)
        {
            x = i;
        }
    };
}

4) If it isn't set x to be equal to -1:

#include <iostream>
int main()
{
    int x=0;
    for(int i=0; i<100; i++)
    {
        if(i%9==0)
        {
            x = i;
        }

        else
        {
            x = -1;
        }
    };
}

5) Print out x

 #include <iostream>
int main()
{
    int x=0;
    for(int i=0; i<100; i++)
    {
        if(i%9==0)
        {
            x = i;
        }

        else
        {
            x = -1;
        }
    };
    std::cout << x << std::endl;
}

DEMO of last one.

References to more C++ Fun Activities

worldbestlearn

WikiBooks

course

Comments