# How to find day from date in C++

In this article, we will see how to find the day of the week corresponding to a given date in C++.

For finding the day from a given date, we have a formula, i.e.,

*(d+m+y+[y/4]+c ) mod 7*

Here, * d* stands for the day,

*stands for the month,*

**m***stands for the year and*

**y***stands for the century number.*

**c**### How the algorithm works:

The derivation of this formula holds on few points like –

- Some months start on the same day (like Jan and Oct, Feb Mar and Nov, April and July –
**during non-leap years**and Jan Apr and July, Feb and Aug, Mar and Nov –**during leap years)** - We make an array containing the first days of all the months corresponding to the first day of January i.e. {0,3,3,6,1,4,6,2,5,0,3,5}. We derived this array by taking mod of the number of days with the number of weeks to get the number of days left. For exp, If we assume that January 1st was on Sunday, then to know the day of February 1st: 7*4+3 (total 31 days in Jan). So the day on 1st Feb will be 3 days followed by the first day of Jan, i.e. Wednesday.
- We mathematically adjust for the leap year. Adding the extra one day after every 4th year except the 100th year(as it is not a leap year) and adding the 400th year(as it is a leap year) gives (1/4 – 1/100 + 1/400).
- The actual array used while calculating the day is {0,3,2,5,0,3,5,1,4,6,2,4}. Here, we have subtracted 1 from each month following February (2nd month) to adjust the gap that is formed due to the addition of an extra day during the leap year.

## Find day from date in C++

The C++ program for calculating the day of the week from the given date is:

#include<iostream> using namespace std; int day_of_week(int y, int m, int d) { static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; y -= m < 3; return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7; } int main(){ int y,m,d; cout<<"Enter the date(1-31): "; cin>>d; cout<<"Enter the month(1-12): "; cin>>m; cout<<"Enter the year(yyyy): "; cin>>y; switch(day_of_week(y,m,d)){ case 0: cout<<"\nSunday\n"; break; case 1: cout<<"\nMonday\n"; break; case 2: cout<<"\nTuesday\n"; break; case 3: cout<<"\nWednesday\n"; break; case 4: cout<<"\nThursday\n"; break; case 5: cout<<"\nFriday\n"; break; case 6: cout<<"\nSaturday\n"; break; } return 0; }

Output:

Enter the date(1-31): 21 Enter the month(1-12): 02 Enter the year(yyyy): 2020 Friday

Hope this helps!!

Also read:

How to validate aadhaar card number in C++

## Leave a Reply