Program opened below. You can scroll through the algorithm, Java code and output.
Program 59
Display a Monthly Calendar
Question
Accept the number of days in a month and the weekday of the first day, then display the calendar.
Algorithm
Step 1: Start the program and accept the number of days in the month.
Step 2: Accept the weekday number for the first day, using Sunday as zero and Saturday as six.
Step 3: Check that the number of days and weekday number are valid.
Step 4: Display the weekday headings in order from Sunday to Saturday.
Step 5: Print blank spaces for the weekdays before the first day of the month.
Step 6: Set the day counter to one.
Step 7: Display the current day in the next calendar position.
Step 8: Advance the day counter by one.
Step 9: If the current calendar position is Saturday, begin a new line.
Step 10: Repeat until all days of the month have been displayed.
Step 11: Print a final line break and stop.
Java program
Javaimport java.util.*;
class MonthCalendar
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Number of days in month: ");
int days = sc.nextInt();
System.out.print("First weekday (Sunday=0 ... Saturday=6): ");
int first = sc.nextInt();
if (days < 28 || days > 31 || first < 0 || first > 6)
{
System.out.println("Invalid input");
return;
}
System.out.println("Sun Mon Tue Wed Thu Fri Sat");
for (int i = 0; i < first; i++)
{
System.out.print(" ");
}
for (int d = 1; d <= days; d++)
{
System.out.printf("%3d ", d);
if ((first + d) % 7 == 0)
{
System.out.println();
}
}
System.out.println();
}
}Sample output
Input: Days = 31; first weekday = 3 (Wednesday)
Output: 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 31