Home » C programming language

Read character array and check it is palindrome or not in C language

Learn: How to read a character array one by one character and check whether entered character array is palindrome or not?

Read a character array (character by character) of valid alphabets and check whether entered character array (string) is palindrome or not. Read array until an invalid character is not entered.

In this program we are taking a character array maximum of 50 characters, reading one by one character until an invalid alphabet is not found. Here, program will consider A to Z and a to z as valid alphabets. As an invalid alphabet is found, character array reading loop will be terminated without saving that invalid alphabet.

After entering an invalid character, you have to press an enter [or press enter without entering any invalid alphabet].

#include <stdio.h>

/*function to check a palindrome string*/
int isPalindrome(char *str);

int main()
{
	char    text[50]={0};
	char    ch;	    /*to store, a single input*/
	int     cnt=0;  /*string count*/
	
	printf("Please enter a string (valid set of characters): ");
	/*run an infinite loop*/
	while(1)
	{
		ch=getchar();
		
		/*check valid alphabets*/
		if((ch>='A' && ch<='Z')||(ch>='a' && ch<='z'))
			text[cnt++]=ch;
		else
			break; /*break loop on invalid alphabet*/
	}
	text[cnt]='\0';	/*terminate string with NULL*/
	
	
	printf("Entered string is: %s\n",text);
	
	if(isPalindrome(text))
		printf("%s is a palindrome string\n",text);
	else
		printf("%s is not a palindrome string\n",text);
	
	return 0;
}


/*isPalindrome - function definition*/
int isPalindrome(char *str)
{
	int length=0;
	int i,ret=1;
	
	/*calculate length*/
	while(str[length]!='\0') length++;
	 
    for(i=0; i<length; i++)
	{
		if((str[0+i] != str[(length-1)-i]))
		{
			ret=0;
			break;
		}			
	} 	
	return ret;
}

Output

First run:
Please enter a string (valid set of characters): Hello* 
Entered string is: Hello
Hello is not a palindrome string

Second run:
Please enter a string (valid set of characters): ABCBA& 
Entered string is: ABCBA
ABCBA is a palindrome string


COMMENTS




Copyright © 2024 www.includehelp.com. All rights reserved.