Ask your own question, for FREE!
Computer Science 20 Online
OpenStudy (anonymous):

{ int sum1, sum2; sum1 = sum2 = 0; for ( int i =1 ; i < = 10 ; i++) if (1 % 2 = = 0) sum1+ = i ; else sum2+ = i ; please make me understand the meaning of line line 2 and line 4 question is to write a programme that wil calculate sum of even numbers 1 to 10

OpenStudy (anonymous):

Line 2 initializes the value of variables sum1 and sum2 to zero whereas line 4 will never execute the if part ie sum1 will always be 0 as 1%2=1 and 1 is never equal to zero(0). So if statement is always false so only sum2 will be incremented not sum1 it remains same '0'.

OpenStudy (rsmith6559):

Maybe phrasing it different will help: int sum1 = 0; int sum2 = 0; for( int i = 1; i <= 10; i++ ) { if( i % 2 == 0 ) sum1 += i; else sum2 += i; } I cleaned it up too, I hope.

OpenStudy (anonymous):

biggest problem is the typo if (1 % 2 = = 0) instead of if (i % 2 = = 0) as rsmith has already corrected. % is the modulo operator; a % b results in the remainder when you (integer-) divide a by b. e. g. 1 % 2 is 1 (1 / 2 is 0 remainder 1), 3 % 2 is also 1 (3 / 2 is 1 remainder 1), 9 % 3 is 0 (because 9 / 3 leaves no remainder). so what the line does is, is switches between numbers that are divisible without remainder by 2, and those that aren't. I. e. even and odd numbers.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!