OverIQ.com

C Program to print the date in legal form

Last updated on September 24, 2020


The following is a C program to print the date in legal format:

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/******************************************
 Program to print the date in legal form
 * 
 * Enter date(MM/DD/YYY): 05/25/2018
 * 25th May, 2018
 ******************************************/

#include<stdio.h> // include stdio.h library

int main(void)
{       

    int day, mon, year;

    char *months[] = {
                        "January", "February", "March", "April",
                        "May", "June", "July", "August", 
                        "September", "October", "November", "December",
                      };

    printf("Enter date(MM/DD/YYY): ");
    scanf("%d/%d/%d", &mon, &day, &year);

    printf("%d", day);

    // if day is 1 or 21 or 31, add the suffix "st"
    if(day == 1 || day == 21 || day == 31)
    {
        printf("st ");
    }

    // if day is 2 or 22, add the suffix "nd"
    else if(day == 2 || day == 22)
    {
        printf("nd ");
    }

    // if day is 3 or 23, add the suffix "rd"
    else if(day == 3 || day == 23)
    {
        printf("rd ");
    }

    // for everything else add the suffix "th"
    else
    {
        printf("th ");
    }    

    printf("%s, %d", months[mon - 1], year);

    return 0;
}

Try it now

Expected Output: 1st run:

1
2
Enter date(MM/DD/YYY): 10/21/2005
21st October, 2005

2nd run:

1
2
Enter date(MM/DD/YYY): 04/23/2012
23rd April, 2012

How it works #

In informal writing, numbers in a date are usually separated by / or -. For example:

05/11/15
05-11-2015

However, In legal and formal documents, dates are written in full. For example:

\(21^{st}\) Dec 2012
December \(21^{st}\), 2012

Here is how the above program works:

  • The body of the program starts by defining three variables: day, mon and year.
  • In lines 16-20, we have defined an array of character pointers containing the name of the months we would like to display.
  • Next, we ask the user to enter a date.
  • The if-else statement in lines 27-49, prints the day suffix (i.e "st", "nd", "rd" or "th")
  • Finally, the print statement in line 51 prints month and year.

Recommended Reading: