# C Program Find The Days in February

by Dinesh Thakur Category: Control Structures

The if-else statement given below uses the leap year test to determine the number of days in February.

if (yy % 4 == 0 && yy%100 != 0 || yy % 400 == 0) /* leap year test */

days = 29;

else days = 28;

We can rewrite this code using a conditional expression as shown below.

(yy % 4 == 0 && yy % 100 != 0 || yy % 400 == 0) ? days = 29 : days=28;

However, the code is concise and more readable when we first determine the desired value and then assign it to days as shown below:

days = ( (yy % 4 == 0 && yy % 100!= 0 || yy % 4 00 == 0 )? 2 9 : 2 8 ) ;

We can verify, by applying the operator precedence rules, that the parentheses in the above statement are not essential but are useful as they improve the readability. The above statement can thus be written by removing the redundant parentheses as shown below.

days = (yy % 4 == 0 && yy % 100 != 0 || yy % 400 == 0) ? 29 : 28;

days = yy % 4 == 0 && yy % 100 != 0 ||yy % 400 == 0 ? 29 : 28;

Let us now use another approach to determine the number of days in February. We can use a simple if statement to determine days as follows:

days = 28;

if (yy % 4 == 0 && yy % 100 != 0 || yy % 400. == 0)

days++;

Here the value of days is first initialized to 28 and then incremented by 1 only if the given year yy is a leap year. This code can be written concisely using the conditional expression as

days= 28 + (yy % 4 == 0 && yy % 100 != 0 || yy % 400 == 0? 1 : 0);

Here, depending on whether the given year is leap or not, we add either 1 or 0 to 28. Although the addition of 0 is meaningless, it cannot be avoided as both the alternative expressions must be specified in a conditional expression. Also, observe that the parentheses cannot be omitted. Finally, let us see one more variation of this statement. We know that the value of a Boolean expression is 1 if it is true and 0 otherwise. This is exactly what is required in the ·above conditional expression. Thus, we can omit the conditional expression operator and simply add the value of Boolean expression to 28 as shown below.

days = 2 8 + (yy % 4 == 0 & & yy % 100 != 0 || yy % 400 == 0) ;

Observe that this statement is bit difficult to understand and that the parentheses surrounding the Boolean expression cannot be omitted.

#include<stdio.h>

#include<conio.h>

void main()

{

int yy;

clrscr();

printf("Enter a Year : ");

scanf("%d",&yy);

if (yy % 4 == 0 && yy%100 != 0 || yy % 400 == 0) /* leap year test */

{

printf("Days in February are 29");

}

else

{

printf("Days in February are 28");

}

getch();

}  Dinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles