Question #49269

Could you explain how this code works.

for (int i = 0; i < 300; i++)

{

if ( i % 12 == 0)

{

cout << "i = " << i << endl;

}

Why it keeps adding by 12?

so int i is initialized to zero so i % 12 is 0

so it outputs

#: 0

so it goes back again and checks if i is less than 300

i % 12 is zero again but what's happening is it keeps adding by 12

it output like hits

#: 0

#: 12

#: 24

#: 48 and so on.

i becames 12?? does the 12 assigns to i?

for (int i = 0; i < 300; i++)

{

if ( i % 12 == 0)

{

cout << "i = " << i << endl;

}

Why it keeps adding by 12?

so int i is initialized to zero so i % 12 is 0

so it outputs

#: 0

so it goes back again and checks if i is less than 300

i % 12 is zero again but what's happening is it keeps adding by 12

it output like hits

#: 0

#: 12

#: 24

#: 48 and so on.

i becames 12?? does the 12 assigns to i?

Expert's answer

for(int i = 0; i < 300; i++)

{

if ( i == 0)

{

cout << "i = " << i << endl;

}

}

dividend %divisor - Returns the remainder of oneexpression divided by another.

i

0=0, if(0==0){i=0}//Outputs 0 because the condition is fulfilled

1=1 //1 is not equal to0

2=2 //2 is not equal to0

3=3 //3 is not equal to0

4=4 //4 is not equal to0

….

12=0, if(0==0){i=12} //Outputs 12 because the condition is fulfilled

……

24=0, if(0==0){i=24} //Outputs 24 because the condition is fulfilled

``

Learn more about our help with Assignments: C++

## Comments

## Leave a comment