How to print a one-month calendar of user choice using for loop in C?

A one-month calendar can be printed in C using for loops by positioning the first day correctly and then printing all days in a week-by-week format. The key is to add proper spacing before the first day and break lines after every 7 days.

Syntax

for(i = 1; i < firstDay; i++)
    printf("   ");  // Add spaces before first day

for(i = 1; i <= daysInMonth; i++) {
    printf("%3d", i);
    if((firstDay + i - 1) % 7 == 0)
        printf("<br>");  // New line after every 7 days
}

Parameters

  • daysInMonth − Total number of days in the month (28-31)
  • firstDay − Day of the week the month starts on (1=Sunday, 2=Monday, ..., 7=Saturday)

Example: Monthly Calendar Generator

This program takes user input for the number of days and the starting day of the week, then displays a formatted calendar −

#include <stdio.h>

int main() {
    int i, daysInMonth, firstDay;
    
    printf("Enter number of days in the month: ");
    scanf("%d", &daysInMonth);
    
    printf("Enter first day of the month (1=Sun, 2=Mon, ..., 7=Sat): ");
    scanf("%d", &firstDay);
    
    printf("\nSun Mon Tue Wed Thu Fri Sat<br>");
    printf("---------------------------<br>");
    
    /* Print spaces for days before the first day */
    for(i = 1; i < firstDay; i++) {
        printf("    ");
    }
    
    /* Print all days of the month */
    for(i = 1; i <= daysInMonth; i++) {
        printf("%3d ", i);
        if((firstDay + i - 1) % 7 == 0) {
            printf("<br>");
        }
    }
    
    printf("<br>");
    return 0;
}
Enter number of days in the month: 30
Enter first day of the month (1=Sun, 2=Mon, ..., 7=Sat): 4

Sun Mon Tue Wed Thu Fri Sat
---------------------------
              1   2   3   4 
  5   6   7   8   9  10  11 
 12  13  14  15  16  17  18 
 19  20  21  22  23  24  25 
 26  27  28  29  30 

How It Works

  1. First Loop − Adds spaces to position the first day correctly in the week
  2. Second Loop − Prints each day number with proper formatting
  3. Modulo Operation(firstDay + i - 1) % 7 == 0 detects when to start a new line after 7 days
  4. Formatting%3d ensures each number takes 3 spaces for proper alignment

Key Points

  • The calendar starts with proper spacing based on the first day of the week
  • Each week is displayed on a separate line using the modulo operator
  • Day numbers are right-aligned in 3-character width for neat formatting

Conclusion

Using for loops with proper spacing and modulo arithmetic, we can create a well-formatted monthly calendar in C. The key is calculating when to break lines and positioning the first day correctly.

Updated on: 2026-03-15T13:44:49+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements