I tried making a small program that would detect if you typed in a palindrome but for some reason, it just loops
ps I'm a beginner
#include <stdio.h>
#include <string.h>
int main(void)
{
char arr[100], arr1[100];
int i;
printf("type in a string\n\n");
gets(arr);
strrev(arr) == arr1;
for (i=0; arr==arr1; i++)
{
printf("%c is a palindrome\n", arr);
}
for (i=0; arr!=arr1; i++)
{
printf("%c is not a palindrome\n", arr);
}
return 0;
}
arr and arr1 are base address of the two arrays respectively which would be different.One simple Code is here
#include <stdio.h>
#include <string.h>
int main(void)
{
char arr[100], arr1[100];
int i;
printf("type in a string\n\n");
gets(arr);
int len=strlen(arr);
strcpy(arr1,arr);
strrev(arr);
for(i=0;i<len;i++){
if(arr1[i]!=arr[i]){
printf("Not palindrome");
return 1;
}
}
printf("Palindrome");
return 0;
}
Use fgets instead of gets.
The first character could be compared to the last character. Then move the indexes toward the center for subsequent comparisons.
#include <stdio.h>
#include <string.h>
int main(void) {
char arr[100] = "";
int first = 0;
int last = 0;
printf ( "type in a string\n\n");
if ( !fgets ( arr, sizeof arr, stdin)) {
printf ( "fgets problem\n");
return 0;
}
arr[strcspn ( arr, "\n")] = '\0';//remove newline
for ( first = 0, last = strlen ( arr) - 1; first <= last; first++, last--) {
if ( arr[first] != arr[last]) {
printf("%s is not a palindrome\n", arr);
return 0;
}
}
printf ( "%s is a palindrome\n", arr);
return 0;
}
Related
I try to learn C Language and something is not clear to me.
I want to write IndexOf function that search for char inside string and return the Index number.
I am running this under ubuntu and compile using this:
test1: test.c
gcc -g -Wall -ansi -pedantic test.c -o myprog1
This is what i have try:
int c;
int result;
printf("Please enter string: ");
scanf("%s", str1);
printf("Please enter char: ");
scanf("%d", &c);
result = indexof(str1, c);
printf("Result value: %d\n", result);
And this is my function:
int indexof(char *str, int c)
{
int i;
for (i = 0; i < strlen(str); i++)
{
if (str[i] == c)
return i;
}
return -1;
}
So my problem is that my function return -1 all the time
scanf("%c",&c)..you are getting input a character.
Working copy would besomethign like:-
char c; // you want to find the character not some integer.
int result;
printf("Please enter string: ");
scanf("%s", str1);
printf("Please enter char: ");
scanf("%d", &c);
result = indexof(str1, c);
printf("Result value: %d\n", result);
Working example:-
#include <stdio.h>
#include <string.h>
int indexof(char *str, char c)
{
int i;
for (i = 0; i < strlen(str); i++)
{
if (str[i] == c)
return i;
}
return -1;
}
int main()
{
char c;
int result;
char str1[100];
printf("Please enter string: ");
scanf("%s", str1);
printf("Please enter char: ");
scanf(" %c", &c);
result = indexof(str1, c);
printf("Result value: %d\n", result);
}
Since c is int:
int indexof(char *str, int c)
{
int i;
for (i = 0; i < strlen(str); i++)
{
if ((str[i]-'0') == c) // convert char to int
return i;
}
return -1;
}
write IndexOf function that search for char inside string and return the Index number.
You might like to have a look at the strchr() function, which can be used as shown below:
/* Looks up c in s and return the 0 based index */
/* or (size_t) -1 on error of if c is not found. */
#include <string.h> /* for strchr() */
#include <errno.h> /* for errno */
size_t index_of(const char * s, char c)
{
size_t result = (size_t) -1; /* Be pessimistic. */
if (NULL == s)
{
errno = EINVAL;
}
else
{
char * pc = strchr(s, c);
if (NULL != pc)
{
result = pc - s;
}
else
{
errno = 0;
}
}
return result;
}
You could call it like this:
size_t index_of(const char *, char);
#include <stdlib.h> /* for EXIT_xxx macros */
#include <stdio.h> /* for fprintf(), perror() */
#include <errno.h> /* for errno */
int main(void)
{
result = EXIT_SUCCESS;
char s[] = "hello, world!";
char c = 'w';
size_t index = index_of(s, 'w');
if ((size_t) -1) == index)
{
result = EXIT_FAILURE;
if (0 == errno)
{
fprintf("Character '%c' not found in '%s'.\n", c, s);
}
else
{
perror("index_of() failed");
}
}
else
{
fprintf("Character '%c' is at index %zu in '%s'.\n", c, index, s);
}
return result;
}
My program in C which is Palindrome has an error in its function. My function is not comparing the 2 characters in my string. When I type a single character it answers palindrome but if it is two or more always not palindrome.
Code:
int IntStrlength=strlen(StrWord);
int IntCtr2=0;
int IntCtr=1, IntAnswer;
while(IntCtr<=(IntStrlength/2)){
printf(" %d %d\n", IntCtr2,IntStrlength);
if(StrWord[IntStrlength] != StrWord[IntCtr2]){
IntAnswer=0;
printf(" %d=Not Palindrome", IntAnswer);
exit (0);
}//if(StrWord[IntCtr2]!=StrWord[IntStrlength]) <---------
else{
IntCtr2++;
IntStrlength--;
}// else <--------
IntCtr++;
}//while(IntCtr<IntStrlength/2) <-----------
IntAnswer=1;
printf(" %d=Palindrome", IntAnswer);
return ;
}
Single character:
Two or more characters:
Why not write it like this
int wordLength = strlen(StrWord);
for (int i=0;i<(wordLength/2);i++) {
if (StrWord[i] != StrWord[wordLength-i-1]) {
return 0;
}
}
return 1;
For words with an even length (say 8) the counter will go from 0 to 3, accessing all letters. For uneven words (say 7) the c ounter will go from 0 to 2, leaving the middle element unchecked. This is not necessary since its a palindrome and it always matches itself
#include<stdio.h>
int check_palindrom(char *);
int main()
{
char s1[20];
printf("Enter the string...\n");
gets(s1);
int x;
x=check_palindrom(s1);
x?printf("Palindrom\n"):printf("Not Palindrom\n");
}
int check_palindrom(char *s)
{
int i,j;
for(i=0;s[i];i++);
for(i=i-1,j=0;i>j;i--,j++)
if(s[i]!=s[j])
return 0;
if(s[i]==s[j])
return 1;
}
Enter the string...
radar
Palindrom
I've seen this algorithm before in a interview book called "Cracking the Coding Interview".
In it the author shows a very simple and easy implementation of the code. The code is below: Also here is a video explaining the code.
#include<stdio.h>
#include<string.h> // strlen()
void isPalindrome(char str[]);
int main(){
isPalindrome("MOM");
isPalindrome("M");
return 0;
}
void isPalindrome(char str[]){
int lm = 0;//left most index
int rm = strlen(str) - 1;//right most index
while(rm > lm){
if(str[lm++] != str[rm--]){
printf("No, %s is NOT a palindrome \n", str);
return;
}
}
printf("Yes, %s is a palindrome because the word reversed is the same \n", str);
}
You can do this like this:
#include <stdio.h>
#include <string.h>
int check_palindrome(char string []);
int main()
{
char string[20];
printf("Enter the string...\n");
scanf ("%s", &string);
int check;
check = check_palindrome (string);
if (check == 0)
printf ("Not Palindrome\n");
else
printf ("Palindrome\n");
return 0;
}
int check_palindrome (char string [])
{
char duplicate [];
strcpy (string, duplicate);
strrev (string);
if (strcmp (string, duplicate) == 0)
return 1;
else
return 0;
}
This uses the strcmp and strrev function.
Take a look at this code, that's how I have implemented it (remember to #include <stdbool.h> or it will not work):
for(i = 0; i < string_length; i++)
{
if(sentence[i] == sentence[string_lenght-1-i])
palindrome = true;
else
{
palindrome = false;
break;
}
}
Doing that it will check if your sentence is palindrome and, at the first occurence this is not true it will break the for loop. You can use something like
if(palindrome)
printf(..);
else
printf(..);
for a simple prompt for the user.
Example :
radar is palindrome
abba is palindrome
abcabc is not palindrome
Please , pay attention to the fact that
Abba
is not recognized as a palindrome due to the fact that ' A ' and 'a' have different ASCII codes :
'A' has the value of 65
'a' has the value of 97
according to the ASCII table. You can find out more here.
You can avoid this issue trasforming all the characters of the string to lower case characters.
You can do this including the <ctype.h> library and calling the function int tolower(int c); like that :
for ( ; *p; ++p) *p = tolower(*p);
or
for(int i = 0; str[i]; i++){
str[i] = tolower(str[i]);
}
Code by Earlz, take a look at this Q&A to look deeper into that.
EDIT : I made a simple program to do this, see if it can help you
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
void LowerCharacters(char *word, int word_lenth);
int main(void){
char *word = (char *) malloc(10);
bool palindrome = false;
if(word == 0)
{
printf("\nERROR : Out of memory.\n\n");
return 1;
}
printf("\nEnter a word to check if it is palindrome or not : ");
scanf("%s", word);
int word_length = strlen(word);
LowerCharacters(word,word_length);
for(int i = 0; i < word_length; i++)
{
if(word[i] == word[word_length-1-i])
palindrome = true;
else
{
palindrome = false;
break;
}
}
palindrome ? printf("\nThe word %s is palindrome.\n\n", word) : printf("\nThe word %s is not palindrome.\n\n", word);
free(word);
return 0;
}
void LowerCharacters(char *word, int word_length){
for(int i = 0; i < word_length; i++)
word[i] = tolower(word[i]);
}
Input :
Enter a word to check if it is palindrome or not : RadaR
Output :
The word radar is palindrome.
This code may help you to understand the concept:
#include<stdio.h>
int main()
{
char str[50];
int i,j,flag=1;
printf("Enter the string");
gets(str);
for(i=0;str[i]!='\0';i++);
for(i=i-1,j=0;j<i;j++,i--)
{
str[i]=str[i]+str[j];
str[j]=str[i]-str[j];
str[i]=str[i]-str[j];
}
for(i=0;str[i]!='\0';i++);
for(i=i-1,j=0;j<i;j++,i--)
{
if(str[i]==str[j]){
flag=0;
break;
}
}if(flag==0)
{
printf("Palindrome");
}else
{
printf("Not Palindrome");
}
}
I have solution for this
char a[]="abbba";
int i,j,b=strlen(a),flag=0;
for(i=0,j=0; i<b; i++,j++)
{
if(a[i]!=a[b-j-1])
{
flag=1;
break;
}
}
if(flag)
{
printf("the string is not palindrum");
}
else
{
printf("the string is palindrum");
}
This may works for you
#include <stdio.h>
#include <stdlib.h>
int main(void) {
setbuf(stdout,NULL);
int i,limit;
char string1[10];
int flag=0;
printf("enter a string");
scanf("%s",string1);
limit=strlen(string1);
for(i=0;i<limit;i++){
if(string1[i]!=string1[limit-i-1]){
flag=1;
break;
}
} if(flag==1){
printf("entered string is not palindrome");
}else{
printf("entered string is palindrome");
}
return EXIT_SUCCESS;
}
I am passing a 2D char array to a function. If I print it in the calling function, I see it is filled with some elements. If I print it in the called function, only the first element is filled:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int compareTopString(char * string1, char * string2){
printf("%s %s\n", string1, string2);
return 5;
}
int getMaxTopics(int numP, int numTop, int * subject[][1000]){
for(int k = 0;k < numP;k++){
printf("%s\n", subject[k]);
}
return 0;
}
int main() {
int numP;
int numTop;
char subject[1000][1000];
scanf("%d", &numP);
scanf("%d", &numTop);
for (int i = 0; i < numP; i++){
scanf("%s", subject[i]);
}
printf("%d", getMaxTopics(numP, numTop, &subject));
for(int k = 0;k < numP;k++){
printf("%s\n", subject[k]);
}
return 0;
}
You are mixing char and int. Are you sure that compiled without warnings?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 24
void rez(char **c, char *s, int n, int ks);
void rez(char **c, char *s, int n, int ks)
{
int t = 0, j = 0;
char *p;
p = strtok(s," ");
t = t + strlen(p);
if (strlen(p)>N) *(c+j)=(char*)malloc((strlen(p)+1)*sizeof(char));
else *(c+j)=(char*)malloc((N+1)*sizeof(char));
while(p!=NULL)
{
if (t>N)
{
*(*(c+j)+t) = '\0';
t = strlen(p) + 1;
j++;
if (t>N) *(c+j)=(char*)malloc(strlen(p)+1);
else *(c+j)=(char*)malloc(N+1);
}
strcat(*(c+j), p);
c[j][t]=' ';
p = strtok(NULL, " ");
t=t+strlen(p)+1;
}
c[j][t]='\0';
for(j=0; j<ks; j++)
{
printf("\n %s", *(c+j));
}
}
int main(void)
{
FILE *fin;
int n, ks;
char s1[2048], filename[256];
char **c;
printf("Enter the file name->");
scanf("%s", filename);
fin=fopen(filename,"r");
if (!fin)
{
printf ("Error\n");
return -1;
}
while (fscanf(fin, "%[^\n]", s1)==1)
{
fscanf(fin, "%*[ \n]");
printf("\n String: %s \n", s1);
n=strlen(s1);
ks=n/(N-1)+1;
c=(char **)malloc(ks*sizeof(char*));
rez(c, s1, n, ks);
}
fclose(fin);
return 0;
}
This code should cut long strings into some shorter, but it gives "core dumped" in gcc. It doesn't exit from while in void rez().
In my mind, strtok() works incorrectly.
This is wrong:
char r[1]=" ";
because the string literal " " is TWO characters! It is both a space and a NULL-terminator (which is at the end of every string in C. But you explicitly said it should only be a 1 character array.
I am having a few issues with my code. First: when I try to compile, I get error: too few arguments to function 'strcmp'. I have looked all over and made multiple changes and am still unable to get it to work. Second: when my code does compile (if I remove the strcmp part), it will not complete the count functions correctly. Can anyone please assist? Thank you!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int count(char array[], int size);
int stringLen(char array[]);
int convert(char ch);
int value, n;
int main()
{
//char * str;
//char s;
char a[100];
char b[100];
char c[100];
int charCount = stringLen(a);
int lCount = count(a, charCount);
printf("Enter your string: \n");
scanf("%s \n", a);
printf("Enter your string: \n");
scanf("%s \n", b);
printf("Enter your string: \n");
scanf("%s \n", c);
printf("The count is %d, length is %d\n", lCount, charCount);
int i;
for(i = 0; i < charCount; i++)
{
char c = a[i];
printf("Char %s = %d \n", &c, value);
}
n = strcmp(char string1[], char string2[], char string3[]);
printf("The first string in the alphabet is: %d \n", n);
return 0;
}
int stringLen(char array[])
{
char count;
int index;
while(array[index] !=0)
{
count++;
index++;
}
return count;
}
int count(char array[], int size)
{
int count;
int i;
for(i = 0; i < size; i++)
{
if(array[i] == 'a')
{
count ++;
}
else if(array[i] == 'A')
{
count ++;
}
}
return count;
}
This is not right way to use strcmp.
n = strcmp(char string1[], char string2[], char string3[]);
strcmp is used for compararison of string. See doc
int result = strcmp (string1,string2)
If strings are same, function will return 0.