TCS Coding Practice Question | Palindrome String
Given a string, the task is to check if this String is Palindrome or not using Command Line Arguments.
Examples:
Input: str = "Geeks" Output: No Input: str = "GFG" Output: Yes
Approach:
- Since the string is entered as Command line Argument, there is no need for a dedicated input line
- Extract the input string from the command line argument
- Traverse through this String character by character using loop, till half the length of the sting
- Check if the characters from one end match with the characters from the other end
- If any character do not matches, the String is not Palindrome
- If all character matches, the String is a Palindrome
Program:
C
// C program to check if a string is Palindrome // using command line arguments #include <stdio.h> #include <stdlib.h> #include <string.h> // Function to reverse a string int isPalindrome( char * str) { int n = strlen (str); int i; // Check if the characters from one end // match with the characters // from the other end for (i = 0; i < n / 2; i++) if (str[i] != str[n - i - 1]) // Since characters do not match // return 0 which resembles false return 0; // Since all characters match // return 1 which resembles true return 1; } // Driver code int main( int argc, char * argv[]) { int res = 0; // 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 check if it is Palindrome res = isPalindrome(argv[1]); // Check if res is 0 or 1 if (res == 0) // Print No printf ( "No\n" ); else // Print Yes printf ( "Yes\n" ); } return 0; } |
Java
// Java program to check if a string is Palindrome // using command line arguments class GFG { // Function to reverse a string public static int isPalindrome(String str) { int n = str.length(); // Check if the characters from one end // match with the characters // from the other end for ( int i = 0 ; i < n / 2 ; i++) if (str.charAt(i) != str.charAt(n - i - 1 )) // Since characters do not match // return 0 which resembles false return 0 ; // Since all characters match // return 1 which resembles true return 1 ; } // 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 check if it is Palindrome int res = isPalindrome(args[ 0 ]); // Check if res is 0 or 1 if (res == 0 ) // Print No System.out.println( "No\n" ); else // Print Yes System.out.println( "Yes\n" ); } else System.out.println( "No command line " + "arguments found." ); } } |
Output:
Please Login to comment...