Monday, May 24, 2010

C programming question....?

Using the text below, write a program to determine if a year is a leap year by using a set of conditionals.








/*


author:





date:





purpose: Determine if a year is a leapyear.





NOTES: The #define statement is necessary to turn off Visual Studio's


warnings for using scanf().


*/





#define _CRT_SECURE_NO_DEPRECATE


#include %26lt;stdio.h%26gt;





int main( void )


{


int year;





/* prompt the user for a year to check */


printf("Enter a year: ");


scanf("%d", %26amp;year);


/* put your code below here */

C programming question....?
This is handled in standard C libraries, but:





A year is a leap year if it is divisible by 4 and not 100 unless it is divisible by 400 as well.





1998 is divisible by 4 without a remainder and is not divisible by 100 so it is a leap year.





1900 is divisible by 4 but also 100 but not 400 without a remainder. It is not a leap year.





2000 is divisible by 4 and 100 without a remainder, but it's also divisible by 400 so it is a leap year.





Here's a start for 4 and one case of 100. Add the other case for 100 and the case for 400 and you're done. Use the modulus operator in C:





if(year % 4){ /* has a remainder */


printf("Not\n");


}else if (year % 100){ /* 4 passed 100 failed */


printf("Is\n");


}
Reply:I believe every leap year is divisible by 4 without having a remainder. So basically you would have to divide the year


by four and store in "X". Then do the same but take the


absolute value (forced to NO REMAINDER) and store in "Y".





Then subtract Y from X. If it is ZERO then it is a leap year... otherwise it is not.





-JP


No comments:

Post a Comment