A string of characters w is a square if there is a string u such that w=uu (for example "bonbon" is square). Write a function that returns 1 if the string passed as a parameter is a square, otherwise 0 (remember that the strlen function returns the number of characters in a character string, not counting the end character).


Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#include <string.h>

int square(char s[]) 
{
  	int l=strlen(s);
  	int i=0;
	// we loop ont he first half and check with the second half
  	while ((i<l/2) && (s[i]==s[i+l/2])) 
		i++;

	// if the length is odd or we exit the loop before the middle, 
	// the string is not a square
  	if (l%2==0 && i==l/2) 
		return 1;
  	else 
		return 0;
}

void main()  
{
  	char s[20];
  	printf("enter the word :");
  	scanf("%s",s);

  	if (square(s)) 
		printf("%s is a square word\n",s);
  	else 
		printf("%s is not a square word\n",s);
	getch();
}

 

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Number of occurrence of a string into another one