Lowest price ever! Learn Generative AI for 48% less!
Get my discount+ 8
Lalit
It is 6 % 4 = 2
Loop execution
I = 0
Inside for loop
I = I * I => 0 because I = 0
I = I+2 => I = 2 increment
I < 4 Yes
I = I * I => I = 2 * 2 => I = 4
I = I + 2 => I => 6 increment
cout << I % 4
=> cout << 6 % 4
=> cout << 2
OUTPUT: 2
+ 6
Here is what's happening:
(i=0) i = 0
(i<4) 0 < 4? True
(i=i*i) i = 0*0
(i+=2) i = 0+2
(i<4) 2 < 4? True
(i=i*i) i = 2*2
(i+=2) i = 4+2
(i<4) 6<4? False
(i%4) 6/4 is 1 with reminder 2
+ 3
Adding some printouts helps
#include <iostream>
int main()
{
int i = 0;
for( ; i < 4; i += 2, std::cout << "\nAdd 2 to i => " << i << "\n\n")
{
std::cout << "Before multiplication i = " << i;
i *= i;
std::cout << "\nAfter multiplication i = " << i;
}
std::cout << "i is now " << i << "\n"
<< i << " % 4 = " << ( i % 4 ) << std::endl;
return 0;
}
+ 2
% is the modulo operator.
It returns the reminder when a is divided by b
So 6 % 4 = 2 (reminder)
+ 2
2