adplus-dvertising
Coders Packet

Check whether a given date is valid and add 'N' days to it (using C++)

By Sangeetha Prabhu

Through this program, we check if a given date is valid and add the 'N' number of days to the given date.

In this tutorial, we learn to check whether a given date is valid or not. And then we add 'N' number of days.

The user provides a date and first, we check if the date is valid or not. If the given date is valid then we add 'N' number of days to the given valid date. If the date is invalid then we display the output as Invalid date.

To understand the working of the program one should know about structures and functions. 

Source code:

#include <bits/stdc++.h>
using namespace std ;
struct  date
{
    int d,m,y;
} ;
int DateValid (date);
date Addays(date & , int);
int main()
{
   
    date d1;
    int n ;
    cout<<" PROGRAM TO CHECK WHETHER A GIVEN DATE IS VALID "<<endl;
    cout<<"ENTER THE DATE";
    cin>>d1.d;
    cout<<"ENTER THE  MONTH ";
    cin>>d1.m;
     cout<<"ENTER THE  YEAR";
    cin>>d1.y;
    if(!DateValid(d1))
    cout<<"THE GIVEN DATE IS INVALID";
    else
    {
        date t =d1;
        cout<<"ENTER THE NO. OF DAYS YOU WANT ADD";
        cin>>n;
        d1= Addays(date &d1, n )
        cout<<"ORGINAL DATE IS :"<<t.d<<" . "<<t.m<<" ."<<t.y;
        cout<<"UPDATED DATE IS :"<<d1.d<<" . "<<d1.m<<" ."<<d1.y;
    }//else
    getch();
    return 0 ;
}//main
 int DateValid(date d1)
 {
   if(d1.d<1|| d1.d>31)
    return 0;
   else
     if (d1.m<1|| d1.m>12)
      return 0;
     else 
        if ((d1.m==4||d1.m==6||d1.m==9||d1.m==11) && d1.d>30)
            return 0;
            else 
                if(d1.m==2&& d1.d>29)
                   return 0;
                    else((d1.y%4!=0|| (d1.y%100 && d1.y==400)) && d1.m==2&& d1.d==29))
                       return 0;
                       else 
                          return 1;
     

 }//date valid
 date AdDays(date &d1 ,int n)
 {
   for(int i = 1 ; i<= n ; i++)
    d1.d++;
    if(d1.d>31)
    {
     d1.d=1;
     d1.m ++;
    }//31
    else
     if(d1.d>30&&( d1.m==2|| d1.m==4||d1.m==6|| d1.m==9||d1.m==11))
     {   d1.m++;
         d1.d=1;
     }
    else
     if(((d1.m==2 && d1.d==29)&& d1.y % 100 ==0 && d1.y%400==0 )|| ((d1.m==2 && d1.d==29) && d1.y%4==0))
     d1.d=29;
     else
       if(d1.d>28 && d1.m==2)
       {
           d1.d=1;
           d1.m=3;
       }//normal feb
 }//Addays


And the output is given below:

 

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Sangeetha Prabhu (BuzzingBee)

Download packets of source code on Coders Packet