Check if a word is palindrome with string.h - c

I must do a program that tells me if a string is palindrome or not using the library string.h . I wrote the following code but the output is always "palindrome"
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char a[100],b[100];
int i,k;
printf("Type the string \n");
gets(a);
k=strlen(a);
for(i=0;i<strlen(a);i++)
{
a[i]=b[k];
k--;
} //at the end of this code the string "b" should be the reverse of "a"
k=strcmp(a,b);
if (k!=0) //here I check if a=b or not
{printf("palindrome");}
else
{printf("not palindrome");}
getch();
return 0;
}
Example: When my input is "non" the output should be "palindrome", if the input is "ship" the output should be "not palindrome". Could anyone help me to find what is wrong?

I think it's the line
a[i]=b[k];
Doesn't this put the contents of b[k] (which you have not initialized) into a[i] (which you have populated with the get)? This overwrites the test value in a with blanks, (or whatever was in b's memory) Shouldn't you do the opposite?
But better is not to do it at all - you can just compare the characters in place in the a array.
k=strlen(a);
for(i=0; i<k/2; i++)
if(a[i] != a[k-i])
return "Not Palindrome";
return "Palindrome";

/**
** Name: palindrome.c
** Description: This program checks if a word is palindrome or not
** Aldo Núñez Tovar
**/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int
isPalindrome ( char* str )
{
char* str2 = str + strlen ( str) - 1;
while ( str < str2 )
{
if ( *str++ != *str2-- )
{
return 0;
}
}
return 1;
}
int
main ( void )
{
char* str = "racecar"; /* level, civic, rotor, racecar */
printf ( "Is %s palindrome? %s\n", str, isPalindrome ( str )? "Yes": "No" );
return 0;
}

I fixed it for you, please note the comments:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char a[100],b[100];
int i;
int stringLen;
printf("Type the string \n");
gets(a);
stringLen = strlen(a);
for(i=0; i < stringLen; i++)
{
//First you want to copy to B not A...
//second, you need to remove "1" from the size cause array start from "0".
b[stringLen-1-i] = a[i];
}//at the end of this code the string "b" should be the reverse of "a"
if (strcmp(a,b) == 0) //0 mean equal !
{
printf("palindrome");
}
else
{
printf("not palindrome");
}
getch();
return 0;
}

strcmp() returns zero value when both strings are equal.
It must be something like this:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char a[100],b[100];
int i,k;
printf("Type the string \n");
gets(a);
k=strlen(a)-1;
for(i=0;i<strlen(a);i++)
{
b[i]=a[k]; //assign to b not to a
k--;
}
b[strlen(a)]='\0';//terminate the string with null character
//at the end of this code the string "b" should be the reverse of "a"
k=strcmp(a,b);
if (k==0) //here I check if a=b or not
{printf("palindrome");}
else
{printf("not palindrome");}
getch();
return 0;
}

Your code says this:
k=strlen(a);
Fix this like
k=strlen(a)-1;
This is because if the length is 15, then array index 0 to 14 equals 15.
So, reverse it from 14. That means length-1.
Got it?

Related

C Program to Check for Palindrome String

I wrote two sample programs to check for a palindrome string. But in both I am getting output like, its not a palindrome number. What I am missing?
I strictly assume somehow code is executing my if statement and put flag in to 1. May be because of that length calculation. Anyone has a better idea?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
int main(void) {
setbuf(stdout,NULL);
char name[100];
int i,length,flag=0,k;
printf("Enter your name");
/*scanf("%s",name);*/
gets(name);
length=strlen(name);
for(i=0;i<=length-1;i++)
{
for(k=length-1;k>=0;k--)
{
if(name[i]!=name[k])
{
flag=1;
break;
}
}
}
if(flag==0)
{
printf("Give word is a palindrome");
}
if(flag==1)
{
printf("This is NOT a palindrome word");
}
return 0;
}
and
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
int main(void) {
setbuf(stdout,NULL);
char name[100];
int i,length,flag=0;
printf("Enter your name");
/*scanf("%s",name);*/
gets(name);
length=strlen(name);
for(i=0;i<=length/2;i++)
{
if(name[i]!=name[length-1])
{
flag=1;
}
}
if(flag==0)
{
printf("Give word is a palindrome");
}
if(flag==1)
{
printf("This is NOT a palindrome word");
}
return 0;
}
First Algorithm
The algorithm you are using in the first program involves comparing each letter to every other letter which does not help in determining if the number is a palindrome and it does not seem fixable.
Second Algorithm
The problem with the second approach, however, is you are always comparing name[i] to name[length]. Instead change it to length-i-1. This will start comparing from length-1 and decrement the length of the character by 1 for every next iteration:
for(i = 0;i <= length / 2;i++)
{
if(name[i] != name[length-i-1])
{
flag=1;
break;
}
}
gets() and buffer overflow
Do not use gets. This method is susceptible to a buffer overflow. If you enter a string longer than 100 characters, it will result in undefined behavior. Use fgets instead for deterministic behavior:
fgets(name, sizeof(name), stdin);
This takes in the size of the buffer and only reads up to sizeof(name) characters.
Full code
Ideally, you should consider wrapping the logic to check if the string is a palindrome in a function:
int is_palindrome(char*);
int main(void)
{
char name[100];
setbuf(stdout,NULL);
printf("Enter your name");
fgets(name, sizeof(name), stdin);
if(is_palindrome(name))
{
printf("The given word is a palindrome");
}
else
{
printf("This is NOT a palindrome word");
}
return 0;
}
int is_palindrome(char* name)
{
int length = strlen(name);
int flag = 0, i;
for(i = 0;i <= length / 2; i++)
{
if(name[i]!=name[length-i-1])
{
return 0;
}
}
return 1;
}
There is plenty wrong with both your attempts. I strongly suggest using a debugger to investigate how your code works (or doesn't).
Your first attempt performs length2 (incorrect) comparisons, when clearly only length / 2 comparisons are required. The second performs length / 2 comparisons but the comparison is incorrect:
name[i] != name[length-1] ;
should be:
name[i] != name[length - i - 1] ;
Finally you iterate exhaustively when you could terminate the comparison as soon as you know they are not palindromic (on first mismatch).
There may be other errors - to be honest I did not look further than the obvious, because there is a better solution.
Suggest:
#include <stdbool.h>
#include <string.h>
bool isPalindrome( const char* str )
{
bool is_palindrome = true ;
size_t rev = strlen( str ) - 1 ;
size_t fwd = 0 ;
while( is_palindrome && fwd < rev )
{
is_palindrome = (str[fwd] == str[rev]) ;
fwd++ ;
rev-- ;
}
return is_palindrome ;
}
In use:
int main()
{
const char* test[] = { "xyyx", "xyayx", "xyxy", "xyaxy" } ;
for( size_t t = 0; t < sizeof(test)/sizeof(*test); t++ )
{
printf("%s : %s palindrome\n", test[t],
isPalindrome( test[t] ) ? "Is" : "Is not" ) ;
}
return 0;
}
Output:
xyyx : Is palindrome
xyayx : Is palindrome
xyxy : Is not palindrome
xyaxy : Is not palindrome
Try this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char text[100];
int begin, middle, end, length = 0;
printf("enter the name: ");
scanf("%s",text);
while ( text[length] != '\0' ){
length++;}
end = length - 1;
middle = length/2;
for ( begin = 0 ; begin < middle ; begin++ ) {
if ( text[begin] != text[end] ) {
printf("Not a palindrome.\n");
break;
}
end--;
}
if( begin == middle )
printf("Palindrome.\n");
return 0;
}
The problem with the first piece of code is you are comparing it more than required, compare it with length-i-1.
The main problem with the second code is you are comparing it with only the last letter of a word.
Hope you understood your mistake

C Program to calculate the length of the string using functions and character array

I am writing a c program to caculate the length of the string using functions and character arrays.I had defined a function to calculate the length of a string. it returns the output as an int type. But i am getting the output as 0.
#include<stdio.h>
#include<string.h>
int stringLength(char);//function to calculate and return the string length
int main()
{
char input[100],ch;
int noCh,i=0;
printf("\nEnter the string:\n");
scanf("%s",input)
for(i=0;i<100;i++)
noCh=stringLength(input[i]);/*Passing each string character as input parameter to the function*/
printf("\nThe number of characters in the string \"%s\" is %d.",input,noCh);
return 0;
}
int stringLength(char output)
{
int num=0;
if(output ==" ")
num--;
else
num++;
if(output == EOF)
return num;
}
/*output code*/
[Output code][1]
[1]: https://i.stack.imgur.com/pwvqQ.png
Sorry, but I didn't understand your function. I have written a much simpler code for this.
The first thing which I felt is wrong about your code is that you are passing a character as your function argument for calculating the no of characters in the string.
You should pass the entire array as an argument to the function.
int stringLength(char *);//function to calculate and return the string length
int main()
{
char input[100],ch;
int noCh,i=0;
printf("\nEnter the string:\n");
scanf("%s",input);
/*
for(i=0;i<100;i++)
noCh=stringLength(input[i]);/*Passing each string character as input parameter to the function*/
noCh = stringLength(input);
printf("\nThe number of characters in the string \"%s\" is %d.",input,noCh);
return 0;
}
int stringLength(char * output)
{
/*
int num=0;
if(output ==" ")
num--;
else
num++;
if(output == EOF)
return num;
*/
int count = 0;
char *ch = output;
while(*ch!='\0')
{
count = count +1;
ch++;
}
return count;
}
Please have a look in this link No of characters in string for better understanding.
Kindly have a look on this site how arrays are passed in function as well.
Hope this will help you.
Your code does not make sense and will not compile.
Investigate this program.
#include <stdio.h>
size_t stringLength( const char *s )
{
size_t n = 0;
while ( s[n] != '\0' ) ++n;
return n;
}
int main( void )
{
enum { N = 100 };
char input[N];
printf( "Enter a string: " );
fgets( input, sizeof( input ), stdin );
size_t n = stringLength( input );
if ( input[n-1] == '\n' ) input[--n] = '\0';
printf( "\nThe number of characters in the string \"%s\" is %zu.\n", input, n );
}
Its output might look like
Enter a string: Hello Km Shrikanth!
The number of characters in the string "Hello Km Shrikanth!" is 19.

strings to arrays then print in c

I am trying to take a user inputted string and look at each code to see if it appears in another string of strings. So far my code works.
If the word is successfully found then the alpha representation is to be added to an array that will eventually be printed, but only if all codes were found.
I am having issues with what gets stored in my array that is going to be printed.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef char *string;
typedef char *alpha;
int main(void)
{
string morse[4]={".-", "-...","----.", ".."};
string alpha[4]={"A", "B", "9", "I"};
char prntArr[50];
char *input;
char *hold;
input = malloc(200);
hold = malloc(50);
int i=0;
int j=0;
int ret;
int x;
int w=0;
int z=0;
printf("please enter a string\n");
scanf("%[^\n]",input);
do{
if (input[i] !=' ')
{
hold[j] = input[i];
j++;
}
else
{
hold[j]='\0';
for (x=0;x<4;x++)
{
printf("value of x %d\n",x);
ret = strcmp(morse[x], hold);
if (ret==0)
{
printf("%s\n",alpha[x]);
prntArr[w]=*hold;
w++;
x=4;
}
else
{
ret=1;
printf("invalid Morse code!");
}
}
j = 0;
}
i++;
}while(input[i] !='\0');
for (z=0;z<50;z++)
{
printf("%c",prntArr[z]);
}
return 0;
free(input);
}
The problem you asked about is caused by the way prntArr is used in the program. It really should be an array of character pointers into the alpha array. Instead, it's manipulated as an array of characters into which the first character of each morse code element is stored. And when it's printed, the variable that tracks how much of the array is used is simply ignored.
Another problem is that your code uses spaces to break the codes but there won't necessarily be a space at the end of the line so a code might get missed. In the program below, I switched out scanf() for fgets() which leaves a newline character on the end of the input which we can use, like space, to indicate the end of a code.
Other problems: you print the invalid Morse code message at the wrong point in the code and you print it to stdout instead of stderr; you remember to free input but forget to free hold; you put code after return that never gets called.
Below is a rework of your code that addresses the above problems along with some style issues:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main(void)
{
char *morse[] = {".-", "-...", "----.", ".."};
char *alpha[] = {"A" , "B" , "9" , "I" };
char *print_array[50];
int print_array_index = 0;
char hold[50];
int hold_index = 0;
char input[200];
int i = 0;
printf("please enter a string: ");
fgets(input, sizeof(input), stdin);
while (input[i] !='\0') {
if (input[i] ==' ' || input[i] == '\n')
{
hold[hold_index] = '\0';
bool found = false;
for (int x = 0; x < sizeof(morse) / sizeof(char *); x++)
{
if (strcmp(morse[x], hold) == 0)
{
print_array[print_array_index++] = alpha[x];
found = true;
break;
}
}
if (!found)
{
fprintf(stderr, "invalid Morse code: %s\n", hold);
}
hold_index = 0;
}
else
{
hold[hold_index++] = input[i];
}
i++;
}
for (int x = 0; x < print_array_index; x++)
{
printf("%s ", print_array[x]);
}
printf("\n");
return 0;
}
SAMPLE RUNS
> ./a.out
please enter a string: ----. -... .- ..
9 B A I
>
> ./a.out
please enter a string: .- --- ..
invalid Morse code: ---
A I
>

Logical error in recursive function

I'm writing a program to check whether a string is palindrome or not using recursion.Palindrome string is the one that can be read backwards just the same as reading it forward. However following is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
printf("Enter the number of characters in your string\n");
scanf("%d",&num);
char string[num];
char string2[num];
int i;
printf("Enter your string\n");
for (i=0;i<num;i++)
{
scanf("%c",&string[i]);
}
fillString(string,string2,num);
int palin = isPalind(string,string2,num);
if (palin) printf("The string you entered is palindrome");
else printf("The string you entered is not palindrome");
return 0;
}
int isPalind(char string[],char string2[],int num)
{
int i=0;
while (i<num)
{
if (string[i]!=string2[i])
{
i++;
return 0;
}
else{
i++;
return 1*isPalind(string,string2,num);
}
}
}
void fillString(char string[],char string2[],int num)
{
int i;
for (i=1;i<num;i++)
string2[i-1]=string[num-i];
}
I have a logical error, the program compiles fine and executes but it always gives out "The string is not palindrome"
In the fillString the loop is iterating num-1 times (i is from 1 to num-1), so not the whole string is copied. The first character of the original string is omitted. You should do
for (i=1;i<=num;i++) ...
As for the recursive function, it is not really recursive. In recursive call modified input should be passed, but in your case exactly the same input is passed. So in case of true palindrome, it's likely you will get stack overflow due to non-termination. I would propose another approach, to work with single string recursively:
1) Base case: String is a palindrome if of length 0 or 1
2) Recursion step: String is a palindrome if the first character equals to the last and the string without first and last characters is palindrome.
Is your fillString() function reversing your string as expected? It looks like the first letter of string1 is not getting added into the last position of string2 because the for loop stops when i < num fails. Try switching it to i <= num and seeing if that helps.
Double-check this example:
Given: String1 = "Hello". String2 = null for now. num = 5.
void fillString(char string[],char string2[],int num)
{
int i;
for (i=1;i<num;i++)
string2[i-1]=string[num-i];
}
When i = 4, you have string2 = 'olle'. When i = 5, the for loop condition fails, so it doesn't populate string2[4] = 'H'.
updated:
void fillString(char string[],char string2[],int num)
{
int i;
for (i=1;i<=num;i++)
string2[i-1]=string[num-i];
}
The both functions are wrong. They can be written the following way
int isPalind( const char string[], const char string2[], int num )
{
return ( num == 0 ) ||
( string[0] == string[--num] && isPalind( string + 1, string2, num ) );
}
void fillString( const char string[], char string2[], int num )
{
int i;
for ( i = 0; i < num; i++ ) string2[i] = string[num-i-1];
}
If you need not necessary a recursive function then you could use simply standard function memcmp that to determine whether two strings are equal.

Problems with simple c task

So after a few years of inactivity after studying at uni, I'm trying to build up my c experience with a simple string reverser.
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
*
*/
int main(int argc, char** argv) {
reverser();
return(0);
}
int reverser(){
printf("Please enter a String: ");
//return (0);
int len;
char input[10];
scanf("%s",&input);
int quit = strcmp(input,"quit");
if(quit == 0){
printf("%s\n","Program quitting");
return(0);
}
len = strlen(input);
printf("%i\n",len);
char reversed[len];
int count = 0;
while (count <= (len-1)){
//printf("%i\n",(len-count));
reversed[count] = input[(len-1)-count];
count++;
}
//printf("%s\n",input);
printf(reversed);
printf("\n");
reverser();
}
When I input "hello", you would expect "olleh" as the response, but I get "olleh:$a ca&#",
How do I just get the string input reversed and returned?
Bombalur
Add a '\0' at the end of the array. (as in, copy only chars until you reach '\0' - which is the point at array[strlen(array)], then when you're done, add a '\0' at the next character)
Strings are conventionally terminated by a zero byte. So it should be
char reversed[len+1];
And you should clear the last byte
reversed[len] = (char)0;
you forgot the \0 at the end of the string
This is because you are creating an array with size 10. When you take in some data into it (using scanf) and the array is not filled up completely, the printf from this array will give junk values in the memory. You should iterate for the length of the input by checking \n.
must have a size + 1 to string length so that you can have a \0 at the end of string that will solve your problem
The following is a (simple and minimal implementation of) string reverse program (obviously, error conditions, corner cases, blank spaces, wider character sets, etc has not been considered).
#include <stdio.h>
int strlen(char *s)
{
char *p = s;
while (*p)
p++;
return p - s;
}
char * strrev(char a[])
{
int i, j;
char temp;
for (i=0, j=strlen(a)-1 ; i<j ; i++, j--) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return a;
}
int main()
{
char str[100];
printf("Enter string: ");
scanf("%s", str);
printf("The reverse is %s \n", strrev(str));
return 0;
}
Hope this helps!

Resources