Wonderful example 2 of C language: Please write the function fun. The function of the function is: determine whether the string is a palindrome? If so, the function returns 1

1. Question

Please write the function fun. The function of the function is: determine whether the string is a palindrome? If so, the function returns 1

2. Program analysis

A palindrome is a string that is the same when read forward or backward. For example, the string LEVEL is a palindrome, but the string 123312 is not a palindrome.

Problem-solving ideas:

Since a palindrome refers to a string that is the same when read forward and backward, you can use the middle character as the symmetry point and use a loop to determine whether the characters at the symmetrical positions in the string are the same. If they are the same, it is a palindrome, otherwise it is not.

3. Program source code

#include<stdio.h>

#define MAX 100
int fun(char*s)
{
	int i,n=0,flag=1;
	char*p=s;
	while(*p)
	{
		n++;
		p++;
	}
	for(i=0;i<n/2;i++)
		if(s[i]==s[n-1-i]);
	else
	{
		flag=0;
		break;
	}
	return flag;
}
int main()
{
	char str[MAX];
	FILE*out;
	char*t[]={"121","123","asa","abc"};
	int i;
	printf("Enter a string: ");
    fgets(str,MAX,stdin);
	printf("\n\n");
	puts(str);
	if(fun(str))
		printf("  YES\n");
	else
		printf("  NO\n");
	out=fopen("outfile.dat","w");
	for(i=0;i<4;i++)
		if(fun(t[i]))
			fprintf(out,"YES\n");
	else
		fprintf(out,"NO\n");
	fclose(out);
}

4. Input and output

8dd36cf7a201437493599179f299cebc.png

 d08f784e72564c94b9cf5b02abc536d0.png

 

 

 

Guess you like

Origin blog.csdn.net/T19900/article/details/129508030