Drills: check yourself
Answer yourself first, only then open the answer.
1. What does this loop print?
for (int i = 1; i <= 10; i += 3) {
printf("%d ", i);
}
printf("\n");
Answer
1 4 7 10
i is 1, 4, 7, 10. The next would be 13, and 13 <= 10 is false, so the loop ends.
2. How many times does each loop's body run?
int i = 10;
while (i < 10) {
i++;
}
int j = 10;
do {
j++;
} while (j < 10);
Answer
while: 0 times, because the condition is checked before the body, and 10 < 10 is false. do-while: once, because the body runs before the first check.
3. The program always prints "Excellent", even when the grade is 4. What do you fix?
main.c:5:9: error: suggest parentheses around assignment used as truth value [-Werror=parentheses]
5 | if (grade = 10) {
Answer
grade = 10 stores 10 in grade instead of comparing. It should be grade == 10. (Without -Werror the program would compile and always print "Excellent".)
4. When you type 10, the program prints two lines. Why?
switch (grade) {
case 10:
printf("Excellent\n");
case 9:
printf("Very good\n");
break;
}
Answer
There is no break after case 10, so execution "falls through" into case 9: it prints "Excellent" and "Very good". The course flags wouldn't even compile it: this statement may fall through.
5. Write the condition: the year m is a leap year if it divides by 4 but not by 100, or if it divides by 400.
Answer
if ((m % 4 == 0 && m % 100 != 0) || m % 400 == 0) {
"Divides by 4" in C means the remainder is zero: m % 4 == 0. Check: 2024 yes, 1900 no, 2000 yes.