Question 2
Back to Exercise
Using an initialised array of month lengths, print the number of days in each quarter of a non-leap year.
Solution
#include <stdio.h>
static const int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int main(void) {
for (int q = 0; q < 4; q++) {
int sum = 0;
for (int m = q * 3; m < q * 3 + 3; m++)
sum += days[m];
printf("Q%d: %d days\n", q + 1, sum);
}
return 0;
}
Q1: 90 days Q2: 91 days Q3: 92 days Q4: 92 days
A static const table is initialised once, before the program starts, and cannot be modified by accident. Quarter q covers months 3q to 3q + 2.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!