Program that tells if a date is valid in C I'm reading a book about C programming, at the end of each chapter it has some training exercise and one of them was to make a program that tells if a date is valid or not, the code below is what I did and I would like to know if it can be improved?

#include &lt;stdio.h&gt;

int main(){
int dd,mm,yy;

printf("write a date(day/month/year):");
scanf("%d/%d/%d",&amp;dd,&amp;mm,&amp;yy);

int bissextile=(yy%4==0)?1:0;

if (dd&gt;31 || dd&lt;1 || mm&gt;12 || mm&lt;1)
    printf("Invalid date.\n");
    else
        if((mm==2 &amp;&amp; dd&lt;30 &amp;&amp; bissextile) || (mm==2 &amp;&amp; dd&lt;29 &amp;&amp; bissextile==0))
            printf("valid date.\n");
            else
                if((mm==4 || mm==6 || mm==9 || mm==11)&amp;&amp; dd&lt;31)
                    printf("valid date.\n");
                    else
                        if(dd&lt;31 &amp;&amp; mm!=2)
                            printf("valid date.\n");
                            else
                                printf("Invalid date.\n");
}
Validation is a specific task, distinct from receiving input, so it deserves to have its own function.

The code suffers from excessive nesting, which could be improved by putting else if at the same indentation level. However, another problem is that some of the checks are affirmative and some of them are negative, which makes the code harder to follow.

Since the validation depends mostly on the month, I'd write it this way, with a switch:

int isValid(int dd, int mm, int yy) {
    if (dd &lt;= 0) return 0;
    switch (mm) {
      case 1: case 3: case 5: case 7:
      case 8: case 10: case 12:
        return dd &lt;= 31;
      case 4: case 6: case 9: case 11:
        return dd &lt;= 30;
      case 2:
        return dd &lt;= 28 + (yy % 4 == 0);
      default:
        return 0;  /* invalid month */
    }
}


Then, in main():

if ( 3 == scanf("%d/%d/%d",&amp;dd,&amp;mm,&amp;yy) &amp;&amp;
     isValid(dd, mm, yy) ) {
    puts("Valid date");
} else {
    puts("Invalid date");
}


Note that validating the return value from scanf() is important too.

The code doesn't handle the Gregorian correction properly, such as for year 1900.