This blog is under construction

Monday, 8 July 2013

C program to calculate age from date of birth

Write a C program to calculate age from date of birth.


  #include <stdio.h>
  #include <time.h>

  /* checks whether the given input is leap year feb or not */
  int lyearAndFeb(int year, int mon) {
        int flag = 0;
        if (year % 100 == 0) {
                if (year % 400 == 0) {
                        if (mon == 2) {
                                flag = 1;
                        }
                }
        } else if (year % 4 == 0) {
                if (mon == 2) {
                        flag = 1;
                }
        }
        return (flag);
  }

  int main() {
        /* date in mons */
        int datesInMon[] = {31, 28, 31, 30, 31, 30,
                           31, 31, 30, 31, 30, 31};
        int date, mon, year;
        char dob[100];
        time_t ts;
        struct tm *ct;

        /* get the date of birth from the user */
        printf("Enter your date of birth:");
        fgets(dob, 100, stdin);
        sscanf(dob, "%d/%d/%d", &date, &mon, &year);
        ts = time(NULL);
        ct = localtime(&ts);

        /* scan the year, mon and year from the input string */
        printf("Current Date: %d/%d/%d\n",
                ct->tm_mday, ct->tm_mon + 1, ct->tm_year + 1900);

        date = datesInMon[mon - 1] - date + 1;

        /* checking whether mon is leap year feb - 29 date*/
        if (lyearAndFeb(year, mon)) {
                date = date + 1;
        }

        /* calculating the no of date, years and mons */
        date = date + ct->tm_mday;
        mon = (12 - mon) + (ct->tm_mon);
        year = (ct->tm_year + 1900) - year - 1;

        /* checking for leap year feb - 29 date */
        if (lyearAndFeb((ct->tm_year + 1900), (ct->tm_mon + 1))) {
                if (date >= (datesInMon[ct->tm_mon] + 1)) {
                        date = date - (datesInMon[ct->tm_mon] + 1);
                        mon = mon + 1;
                }
        } else if (date >= datesInMon[ct->tm_mon]) {
                date = date - (datesInMon[ct->tm_mon]);
                mon = mon + 1;
        }

        if (mon >= 12) {
                year = year + 1;
                mon = mon - 12;
        }

        /* print the result */
        printf("Age: %d year %d mons and %d days\n", year, mon, date);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/lab_pgms/01_cbasics$ ./a.out
  Enter your date of birth:28/04/1989
  Current Date: 8/7/2013
  Age: 24 year 2 mons and 11 days





See Also:

No comments:

Post a Comment