Interview Question — Printing a Palindrome

May 9, 2017 at 4:35 pm | Posted in Programming | Leave a comment

This was asked recently to me in an interview. Problem is explained in the comments:

/* GlobalEdx interview Question, Real Life Practicial Code
*
* If a user enters D then write a program to print like this:
*  A B C D C B A
* If user Enters J or Z then it should print till J or Z
* like above. Program should work for every letter of English
*
*/

#include <stdio.h>

void printPalindrome(char c) ;
int getFirstLetter(char* p, char* pc);

int main(int argc, char* argv[]){
char c;
if(2 != argc) {
printf("Please provide 1 argument\n");
}
else
{
if(!getFirstLetter(argv[1], &c)) printPalindrome(c);
else printf("You did not enter a character. Enter uppercase character \n");
}
return 0;
}

/* If you get more than letter. Just pick up the first letter
*
*/
int getFirstLetter(char* p, char* pc) {
char temp = *p;

/* What if user puts an int or double, here we handle that ? */
if( ((temp >= 'A') && (temp <= 'Z')) ) {
*pc = temp;
return 0;
}
else return 1;
}

void printPalindrome(char c) {
char t;

for(t='A'; t != c; ++t) printf("%c, ", t);
for(; 'A' != t; --t)     printf("%c, ", t);
printf("%c\n", t);
}

OUTPUT:
[arnuld@arch64 programs]$ gcc -ansi -pedantic -Wall -Wextra palindrome.c
[arnuld@arch64 programs]$

[arnuld@arch64 programs]$ ./a.out BA
A, B, A
[arnuld@arch64 programs]$ ./a.out D
A, B, C, D, C, B, A

[arnuld@arch64 programs]$ ./a.out 0
You did not enter a character. Enter uppercase character

[arnuld@arch64 programs]$ ./a.out 0*
You did not enter a character. Enter uppercase character

[arnuld@arch64 programs]$ ./a.out {
You did not enter a character. Enter uppercase character
[arnuld@arch64 programs]$

Copyright © 2017 Arnuld Uttre, Hyderabd, Telangana – 500017 (INDIA)
Licensed Under Attribution-NoDerivs 3.0 United States (CC BY-ND 3.0 US)

Advertisements

Leave a Comment »

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.
Entries and comments feeds.

%d bloggers like this: