TCS Coding Practice Question | Palindrome String
Last Updated :
11 Jan, 2023
Improve
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
- Java
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
Output: