for(int j=0;j<p;j++)
{
if(a[j]!=b[j])
{
printf("not pal");
return 0;
}
}
printf("string is Palindrome");
return 0;
palindrome just using loops in C
-
29-08-2022 - |
Question
I used following code..but i am looking for proper condition to put. please help me out with it.
int main(){
int k = 0;
char a[9] = {'\0'}, b[9] = {'\0'};
printf("enter string \n");
gets(a);
int p = strlen(a);
for(int i = p-1; i >= 0; i--){
b[k] = a[i];
k = k+1;
}
for(int j = 0; j < p; j++){
if(a[j] == b[j]){
continue;
}else
printf("not pal");
break;
}
return 0;
}
La solution
Autres conseils
here is code..
int main(){
int k=0, flag;
char a[9]={'\0'},b[9]={'\0'};
printf("enter string \n");
gets(a);
int p = strlen(a);
for(int i=p-1;i>=0;i--){
b[k]=a[i];
k=k+1;
}
for(int j=0;j<p;j++){
if(a[j]==b[j]){
flag=0;
}else
flag=1;
break;
}
if(flag==0)
printf("yes");
else
printf("no");
return 0;
}
No need to copy the string. The code below uses the size of the whole string to copy the mirrored letter and checks for equality. Complexity is O(N/2)
(if that even exists :-p
.
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
bool is_palindrome(const char* s)
{
const size_t len = strlen(s);
size_t i=0;
while(i<len/2-1)
{
if(s[i] != s[len-i-1])
return false;
++i;
}
return true;
}
int main()
{
const char* s1 = "palindrome";
const char* s2 = "palindromemordnilap";
if(is_palindrome(s1))
printf("uhoh");
if(is_palindrome(s2))
printf("yay!");
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow