简体   繁体   中英

What does the code print? Exercise in C

I am not sure why does this code print "h=13" and not "h=2". Does anyone have an idea?

#include <stdio.h>

int main() {
int j,h=1;
for(j=0;j<50;j++) {
        if(j%6==1) continue;
        h++;
        if(j==7 || j==14 || j==21)
               break;
}
printf("h=%d",h);
return 0;
}
  1. When j = 0 neither of the if statements return a value of 1, and thus h is incremented.
  2. When j = 1 in (j % 6 == 1) , 1 % 6 will give a remainder of 1 . The statement j % 6 is true and so, h is not incremented . (the '%' is a Remainder Operator)
  3. When j = 2 to j = 6 neither of the if statements return a value of 1, and thus h is incremented.
  4. When j = 7 in (j % 6 == 1) , 7 % 6 will give a remainder of 1 . The statement j % 6 is true and so, h is not incremented .
  5. When j = 8 to j = 12 neither of the if statements return a value of 1, and thus h is incremented.
  6. When j = 13 in (j % 6 == 1) , 13 % 6 will give a remainder of 1 . The statement j % 6 is true and so, h is not incremented .
  7. For j = 14 the statement j == 14 is true and thus the break statement is executed.

h will be incremented for : j = 0, j = 2 to j = 6, j = 8 to j = 12, j = 14 which is a total of 12 times.

Total of 12 + 1 ( h = 1 ) = 13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM