LearnFrenzy
Sign in Take a free test

Declarations and Initializations · Declaration Programs · Question 2

Days in each quarter from an initialised array in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
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
main.c
#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;
}

Output Verified by compiling and running

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links