Get the App
SLTechnology News&Howtos  ›  Development  › 

How to print the calendar of a certain year in C language

Shulou Source: shulou.com Published: 2022-06-01 01:35:44 10月04日 Update

This article mainly explains "how to print out the calendar of a certain year in C language". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "C language how to print out a calendar for a certain year"!

Enter a year (after 1970) and print the calendar for that year in 2 / 6 format.

Main idea: traverse the date, mark what each line should print according to the date, store it in an array, and then traverse the array and print it line by line according to the contents of the array. The code is as follows:

/ print calendar # define _ CRT_SECURE_NO_WARNINGS#include char month [12] [10] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; / / calculate the date of the year int day_in_year (int y, int m, int d) {int r_day = 0 Int m_days [] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 31, 30, 31}; / / the number of days per month m_days [1] + = y% 400 = = 0 | y% 4 = = 0 & y% 100! = 0; for (int I = 0; I < m-1; + + I) {r_day + = m _ days [I];} r_day + = d; } / / calculate the day of the week int getWeek (int y, int m, int d) {/ / first calculate the number of days from Thursday, January 1st, 1970, int days = 0; / / the day of the day int res; / / the day of the week if (y = 1970) {days = day_in_year (y, m, d);} else {for (int I = 1970; I < y) + + I) {days = days + 365 + (I% 400 = = 0 | I% 4 = = 0 & & I% 100! = 0);} days + = (day_in_year (y, m, d)-1); / / because the distance is calculated in how many days, you need to subtract one} / / then calculate the day of the week res = (days + 4)% 7; return res } / / print calendar void displayCalendar (int y) {int m_days [] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31}; / / number of days per month m_days [1] = 28 + (y% 400 = = 0 | y% 4 = = 0 & y% 100! = 0); the first day of the month on the left of int week_l;// is the day of the week for on the right side of the month (int m = 0) M < 6; + + m) {/ m controls the month, which is 1 / / smaller than the actual month. The header of the printed calendar printf ("%-12s%-12s\ n", month [m], month [m + 6]) Printf ("-\ n"); printf ("Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat\ n"); week_l = getWeek (y, m + 1,1) / find out what day the first day of the month on the left is week_r = getWeek (y, m + 7,1); / / find out what day the first day of the month on the right is int date_l = 1; int date_r = 1; while (date_l

Tags: Date calendar month content tag space language output line right number of days pointer array week actual year find learn input practical Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Linux Huawei Shulou Technology NVidia