TCS Coding Practice Question | Checking Leap Year
Given a number N, the task is to check if N is a Leap Year or not using Command Line Arguments.
Examples:
Input: N = 2000 Output: Yes Input: N = 1997 Output: No
Approach:
- Since the number is entered as Command line Argument, there is no need for a dedicated input line
- Extract the input number from the command line argument
- This extracted number will be in String type.
- Convert this number into integer type and store it in a variable, say N
- Now check for the below conditions:
- if N is multiple of 400 and
- if N is multiple of 4 and not multiple of 100
If both of the above conditions are true, then N is a leap year, else not
Program:
C
// C program to check if N is a leap year// using command line arguments #include <stdio.h> #include <stdlib.h> /* atoi */ // Function to check// if year is a leap year or notint isLeapYear(int year){ // Return 1 if year is a multiple // 0f 4 and not multiple of 100. // OR year is multiple of 400. if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) return 1; else return 0;} // Driver codeint main(int argc, char* argv[]){ int n; // Check if the length of args array is 1 if (argc == 1) printf("No command line arguments found.\n"); else { // Get the command line argument and // Convert it from string type to integer type // using function "atoi( argument)" n = atoi(argv[1]); // Check if n is a leap year if (isLeapYear(n) == 1) printf("Yes\n"); else printf("No\n"); } return 0;} |
Java
// Java program to check if N is a leap year// using command line arguments class GFG { // Function to check // if year is a leap year or not public static int isLeapYear(int year) { // Return 1 if year is a multiple // 0f 4 and not multiple of 100. // OR year is multiple of 400. if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) return 1; else return 0; } // Driver code public static void main(String[] args) { // Check if length of args array is // greater than 0 if (args.length > 0) { // Get the command line argument and // Convert it from string type to integer type int n = Integer.parseInt(args[0]); // Check if n is a leap year if (isLeapYear(n) == 1) System.out.println("Yes"); else System.out.println("No"); } else System.out.println("No command line " + "arguments found."); }} |
Output:
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.





