
Learn to write a C program for a leap year through various methods like loops, if-else statements, switch statements, conditional operators, and more. Firstly, let us know about what is a leap year. Generally, a leap year comes every four years and consists of one extra day.
PW Skills Lab is a online compiler available for free. Practice programming, save your progress and code anywhere. Let us learn to write a C program using various methods.
|
C Program for A Leap Year Using If-Else Method |
| #include <stdio.h> int main() { int year; printf ("Enter a year: "); //Display message on the screen scanf ("%d", &year); if (year % 400 == 0) { //If-else condition printf("%d is a leap year.\n", year); } else if (year % 100 == 0) { printf("%d is not a leap year.\n", year); } else if (year % 4 == 0) { printf("%d is a leap year.\n", year); } else { printf("%d is not a leap year.\n", year); } return 0; } |
|
C Program for A Leap Year Using Switch Method |
| #include <stdio.h> int main() { int year; printf("Enter a year: "); scanf("%d", &year); switch (year % 400 == 0) { case 1: printf ("%d is a leap year.\n", year); break; case 0: switch (year % 100 == 0) { case 1: printf ("%d is not a leap year.\n", year); break; case 0: switch (year % 4 == 0) { case 1: printf ("%d is a leap year.\n", year); break; case 0: printf ("%d is not a leap year.\n", year); break; } break; } break; } return 0; } |
|
C Program for A Leap Year Using Ternary Operator |
| #include <stdio.h> int main() { int year; printf("Enter a year: "); scanf("%d", &year); (year % 400 == 0) ? printf("%d is a leap year.\n", year) : (year % 100 == 0) ? printf("%d is not a leap year.\n", year) : (year % 4 == 0) ? printf("%d is a leap year.\n", year) : printf("%d is not a leap year.\n", year); return 0; } |
|
C Program for A Leap Year Using Ternary Operator |
| #include <stdio.h> int main() { int startYear, endYear; printf("Enter start year: "); scanf("%d", &startYear); printf("Enter end year: "); scanf("%d", &endYear); for (int year = startYear; year <= endYear; year++) { if (year % 400 == 0) { printf("%d is a leap year.\n", year); } else if (year % 100 == 0) { printf("%d is not a leap year.\n", year); } else if (year % 4 == 0) { printf("%d is a leap year.\n", year); } else { printf("%d is not a leap year.\n", year); } } return 0; } |
|
C Program for A Leap Year Using Ternary Operator |
| #include <stdio.h> int isLeapYear(int year) { if (year % 400 == 0) { return 1; } else if (year % 100 == 0) { return 0; } else if (year % 4 == 0) { return 1; } else { return 0; } } int main() { int year; printf("Enter a year: "); scanf("%d", &year); if (isLeapYear(year)) { printf("%d is a leap year.\n", year); } else { printf("%d is not a leap year.\n", year); } return 0; } |
| Method | Time Complexity | Space Complexity |
| If-Else method | O(1) | O(1) |
| Switch Statement | O(1) | O(1) |
| Ternary Operator | O(1) | O(1) |
| Using Loop | O(n) | O(1) |
| Using Function | O(1) | O(1) |