for loop question? | Sololearn: Learn to code for FREE!

+1

for loop question?

int i=0; for(;i<4;i+=2){ i=i*i; } cout<<i%4; Why it has a output of 2??

10/27/2021 6:46:49 AM

Lalit Upadhyay

9 Answers

New Answer

+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

0

Didn't get you,what you mean?

0

Okay that's alright and what about i=i*i;how to solve that

-1

Alright, thank you

-1

See,basics are going on,and sometime as a beginner doubts are there,so just advice if you can!!