Checking A Word Reversely

Hello.

I was wondering how to check if the reverse of a word equals to the word inputted. But, I couldn't translate that to a code. It just won't work for me. I've tried to use counter-- of the word's length but it doesn't work. Here's my attempt in solving it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 int main()
{
    char word[20];
    int length;
    int counter;
    bool status;
    cout<<"Enter a word: ";
    cin.get(word, 20);
    int counter2;
    int test;

    length = strlen(word);


     for(counter = length ; counter >= length; counter--)
    {
        
                cout<<word[counter];
    }
return 0;
}

I just don't know how to output the work backwards
closed account (48T7M4Gy)
Here's a start:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 #include <iostream>
 #include <string.h>
 
 int main()
{
    char word[20];
    int length;
    
    std::cout<<"Enter a word: ";
    std::cin.get(word, 20);
    length = strlen(word);
    
    for(int i = length ; i >= 0 ; i--)
    {        
                std:: cout<<word[i];
    }
return 0;
}
Last edited on
Something simple like this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
bool WordSame(char *p_word, char *p_end = nullptr)
{
	if (p_end == nullptr)
	{
		//Set this to the last character of the string
		p_end = &p_word[strlen(p_word)-1];
	}

	//Check that the characters are the same!
	if (*p_word == *p_end)
	{
		++p_word;	//Increment first char
		if (p_word == p_end)	//This catches if we have even # of letters
		{
			return true;
		}
		--p_end;	//Decrement the last char
		if (p_word == p_end)	//Tihs catches when we have odd # of characters
		{
			return true;
		}
		return WordSame(p_word, p_end);	//Try again
	}
	//If we got here, the characters didn't match each other so it's false!
	return false;
}


Then you simply call it like so:
1
2
if (WordSame("test")) { }
if (WordSame("apa")) { }
Last edited on
I tried this, but it isn't working, any advice?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<iostream>
#include<cstring>


using namespace std;

int main()
{
    char word1[20];
    int length;
    int counter;
    bool status;
    cout<<"Enter a word: ";
    cin.get(word1, 20);
    int i;
    int compare;

    length = strlen(word1);

    for( i = length - 1 ; i >= 0 ; i--)
    {
        cout<<word1[i];
    }

    cout<<endl;
    for (counter = 0; counter < length; counter++)
    {
        cout<<word1[counter];
    }

      cout<<endl;
        if (word1[counter] == word1[i])
            {
        status = true;
            }
        else if (word1[counter] != word1[i])
            {
        status = false;
            }
            if (status == true)
            {
                cout<<"yes";
            }
            else if (status == false)
            {
                cout<<"no";
            }


It evaluates true everytime. Anyone could explain? I even tried using compare, but it evaluates as false everytime.
Last edited on
What is line 32 doing?
 
    if (word1[counter] == word1[i])

At that point, both the for loops (at lines 20 and 26) have completed.
counter is looking at the character just past the end of the string (which will always be the null character). i is looking at the character just before the start of the string. We have no idea what value is there.

In any case, comparing just two characters would not be sufficient to tell us about the string, unless it consisted of just one or at most two characters.
So, what could I try to use? Here's the question:

Write a isPalindrome function (and the main() function to test it) that takes as input a word
and returns true if the word is a palindrome or false otherwise. The isPalindrome function
receives the word from the main() function, which will prompt the user whether the input
word is palindrome or not.


Using strings doesn't work here I guess, because you can't reverse a string. I am thinking of using a reference in functions. But first I am trying to reverse it in 'int main' just to know what to use in the 'isPalindrome' function.
Last edited on
Using strings doesn't work here I guess, because you can't reverse a string.

Of course you can. If the task required displaying the reversed string, you could certainly do that. But here, all you need is to find whether or not it is a palindrome.

Here's one approach.

Use two subscripts, a and b to access the first and last characters.
Set flag to true.

Loop while flag is true and a < b
Compare the word[a] with word[b].
If the pair of characters are different, set the flag to false.
else add 1 to the 'first' subscript a, subtract 1 from the 'last' subscript b and go back to start of loop.

flag now contains the result.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include<cstring>
using namespace std;

int main()
{
    char word[20];
    char a;
    char b;
    int length;
    int compare;
    bool status = true;

    cout<<"Enter a word: ";
    cin.get(word, 20);
    a = word[0];
    b = word[19];
   while (status == true && a < b)
    {
        if (a != b)
        {
            status = false;
        }
        else
        {
            a = a + 1;
            b = b - 1;
        }
    }

    cout<<status;
    return 0;
}

Where's my mistake here? Here, it it just evaluating as true everytime.
Last edited on
This is the last character of the array. It isn't the last letter in the word.
b = word[19]; // line 17


Here you should compare the characters in the word, not the subscripts.
if (a == b) // line 20


Line 24, the if is unnecessary,
 
        else if (a != b)
should be simply
 
        else



edit - sorry, I'm not thinking clearly.
a and b should be of type int, not char.

Lines 16 and 17 should set a = 0, not a = word[0]. Similarly, b should be one less than strlen(word).
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include<cstring>
using namespace std;

int main()
{
    char word[20];
    char a;
    char b;
    int length;
    int compare;
    bool status = true;

    cout<<"Enter a word: ";
    cin.get(word, 20);
    a = word[0];
    b = word[20];
    while (status == true && a < b)
    {
        if (word[a] == word[b])
        {
            status = false;
        }
        else
        {
            a = a + 1;
            b = b - 1;
        }
    }
    cout<<status;
    return 0;
}

Did I miss something?
Last edited on
Did I miss something?
Sorry, my fault. I edited my previous post as I'd missed something. Take another look and see whether the last part makes sense:

a and b should be of type int, not char.

Lines 16 and 17 should set a = 0, not a = word[0]. Similarly, b should be one less than strlen(word).


... and by the way, you changed line 17 and replaced one error with a slightly worse error.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include<cstring>
using namespace std;

int main()
{
    char word[20];
    int a;
    int b;
    int length;
    int compare;
    bool status = true;

    cout<<"Enter a word: ";
    cin.get(word, 20);
    length = strlen(word);
    a = 0;
    b = length - 1;
    while (status == true && a < b)
    {
        if (word[a] == word[b])
        {
            status = false;
        }
        else
        {
            a = a + 1;
            b = b - 1;
        }
    }
    cout<<status;
    return 0;
}

It evaluates the opposite and sometimes wrong. I typed "madam" and it evaluated false. I typed "test" it evaluated true.
Last edited on
I should add, I get the impression that you don't really understand what the code is supposed to be doing, the final output is less important than understanding each step along the way. If you don't understand, then ask for clarification, rather than just writing code which is mysterious to you.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    a = 0; // here it sets the a to the first letter, I don't understand why not a = word[0].
    b = length - 1; // similar to a, but I do get why we used length - 1. Because 20 is the null character '\0'.
    while (status == true && a < b) // keep on looping while the boolean status is true and while a is less than b. (it'll stop at false and when a meets b)
    {
        if (word[a] == word[b]) // here, it should check if word[a] , which is set to 0 of an array meaning start from 0, is equal to word[b], which is the last letter before null.
        {
            status = false; // it will set the value of the boolean to false if the first letter equals the last letter.
        }
        else // otherwise, add 1 to the letter which should read the next array for word which is word[1]. Similarly for b but backwards.
        {
            a = a + 1;
            b = b - 1;
        }
    }
    cout<<status;
    return 0;
}
Last edited on
closed account (E0p9LyTq)
Peril wrote:
Using strings doesn't work here I guess, because you can't reverse a string

Reversing a string is simple, you just have to do it yourself.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::string reverse_copy_string(std::string forward_string)
{
   std::string reverse_string;

   reverse_string.resize(forward_string.size());

   for (size_t forward_position = 0, reverse_position = forward_string.size() - 1;
        forward_position < forward_string.size();
        forward_position++, reverse_position--)
   {
      reverse_string[reverse_position] = forward_string[forward_position];
   }

   return reverse_string;
}


Creating a function to check for a string palindrome is also simple:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool is_string_palindrome(std::string input_string)
{
   int first = 0;
   int last = input_string.size() - 1;

   while (first != last)
   {
      if (input_string[first] != input_string[last])
      {
         return false;
      }
      ++first;
      --last;
   }
   return true;
}


And a test program that uses the functions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <string>

std::string reverse_copy_string(std::string forward_string);
bool is_string_palindrome(std::string input_string);

int main ()
{
   std::string forward_string = "abcdedcba";

   std::string reverse_string = reverse_copy_string(forward_string);

   std::cout << forward_string << "\n" << reverse_string << "\n";

   if (forward_string == reverse_string)
   {
      std::cout << "The string is a palindrome\n";
   }
   else
   {
      std::cout << "The string is NOT a palindrome\n";
   }

   forward_string = "abcdefghijklmnopqrstuvwxyz";
   std::cout << "\n" << forward_string << "\n";
   if (is_string_palindrome(forward_string))
   {
      std::cout << "The string is a palindrome\n";
   }
   else
   {
      std::cout << "The string is NOT a palindrome\n";
   }
}


std::string reverse_copy_string(std::string forward_string)
{
   std::string reverse_string;

   reverse_string.resize(forward_string.size());

   for (size_t forward_position = 0, reverse_position = forward_string.size() - 1;
        forward_position < forward_string.size();
        forward_position++, reverse_position--)
   {
      reverse_string[reverse_position] = forward_string[forward_position];
   }

   return reverse_string;
}

bool is_string_palindrome(std::string input_string)
{
   int first = 0;
   int last = input_string.size() - 1;

   while (first != last)
   {
      if (input_string[first] != input_string[last])
      {
         return false;
      }
      ++first;
      --last;
   }
   return true;
}


You can also rewrite the is_string_palindrome() function to simply print out an informational message if the string is a palindrome or not:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void is_string_palindrome(std::string input_string)
{
   int first = 0;
   int last = input_string.size() - 1;

   while (first != last)
   {
      if (input_string[first] != input_string[last])
      {
         std::cout << "The string is NOT a palindrome\n";
         return;
      }
      ++first;
      --last;
   }
   std::cout << "The string is a palindrome\n";
}


And checking for a string palindrome is as simple as calling the function:
1
2
3
4
5
6
int main ()
{
   std::string forward_string = "abcdefghijklmnopqrstuvwxyz";
   std::cout << forward_string << "\n";
   is_string_palindrome(forward_string);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
#include <algorithm>
#include <cstring>

// reverse a string
std::string reverse_of( const std::string& str ) { return { str.rbegin(), str.rend() } ; }

// check if a string is a palindrome
// case sensitive, does not ignore white space and punctuation
bool is_palindrome( const std::string& str )
{ return std::equal( str.begin(), str.begin() + str.size()/2, str.rbegin() ) ; }

// check if a c-style string is a palindrome (recursive version, c-style code)
// case sensitive, does not ignore white space and punctuation
bool is_palindrome( const char cstr[], unsigned int len )
{
    if( len < 2 ) return true ;
    if( cstr[0] != cstr[len-1] ) return false ;
    return is_palindrome( cstr+1, len-2 ) ;
}

bool is_palindrome( const char cstr[] ) { return cstr && is_palindrome( cstr, std::strlen(cstr) ) ; }
Last edited on
But I mean I am expected to do the code with the knowledge we learned so far, in our Subject. I am still taking the course Programming I and didn't exceed functions yet. The reverse thing with returning it, that we didn't take. I am reading it with few understanding of it. That's why I think I should use an Array because our Doctor said you could use something like this:

j = size, j --; for the reverse word.

I get the reverse word, but I don't know what to do with it like in this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main()
{
    char word[20];
    int length;
    int counter;
    bool status;
    cout<<"Enter a word: ";
    cin.get(word, 20);
    int i;
    length = strlen(word);
    for( i = length - 1 ; i >= 0 ; i--)
    {
        cout<<word[i];

    }
    cout<<endl;
     if (word[counter] == word[i])
            {
        status = true;
            }
        else if (word[counter] != word[i])
            {
        status = false;
            }

I am trying to do it in "int main" first to understand how to do it then i'll switch it to a function.

Last edited on
Let's look at an example. The array has room for 20 characters. They are numbered from 0 to 19.
When the user types the word "madam", it occupies the first six of those character positions.
  0   1   2   3   4   5   6                                          17  18  19
_________________________________________________________________________________ 
| m | a | d | a | m |\0 |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
_________________________________________________________________________________
 


We need to distinguish between the subscripts (the numbers 0 to 19) and the contents of the array (the letters "madam" and some other unknown characters).

The variables a and b are used as subscripts (or indexes). These allow the string to be examined step-by-step, one position at a time. If instead we went direct to the actual letters, there would be no way to proceed to look at the next or preceding character.
Think of the subscripts a and b as pointing (though pointers is another topic) at the current pair of characters.

char a = word[0]; would place the letter 'm' (from the word "madam") into a. But a+1 would give the letter 'n' (the next letter of the alphabet), a+2 would give the letter 'o' and so on.

int a = 0; allows us to access the first letter of the word. And after that, a+1 will be used to access the next letter of the word.

When assigning the value of b, again it is the subscript. But it cannot be 20 because word[20] is invalid, it is outside the array). Nor do we use b = 19, because the user typed "madam" and it only has five letters. So we use strlen(word) which gives the length 5, but the last letter of the word is position 4 because array numbering starts from zero, not one.

At line 5, if (word[a] == word[b]) there is a mistake, it should test for "not equal", !=, and set the status to false if the pair of characters are indeed different.

I hope that explained some of it. I'm not sure I covered it all. It's sometimes easier to talk than it is to write.


By the way, you might find it useful to go through the tutorial pages on character arrays, it is much more thorough and should make things clearer:
http://www.cplusplus.com/doc/tutorial/ntcs/
and arrays in general
http://www.cplusplus.com/doc/tutorial/arrays/


FurryGuy:

void is_string_palindrome(std::string input_string)
{
int first = 0;
int last = input_string.size() - 1;

while (first != last)
{
if (input_string[first] != input_string[last])
{
std::cout << "The string is NOT a palindrome\n";
return;
}
++first;
--last;
}
std::cout << "The string is a palindrome\n";
}

using this, I got it correct:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>
#include<cstring>


using namespace std;

void isPalindrome (char word[]);


int main()
{
    char word[15];
    cout<<"Enter a word: ";
    cin.get(word, 15);
    isPalindrome(word);


   return 0;
}
void isPalindrome(char word[])
{
   int first_letter = 0;
   int length;
   length = strlen(word);
   int last_letter = length - 1;

   while (first_letter != last_letter)
   {
      if (word[first_letter] != word[last_letter])
      {
        cout<<"The string is NOT a palindrome"<<endl;
         return;
      }
      first_letter++;
      last_letter--;
   }
   cout<<"The string is a palindrome"<<endl;
}

I still used a character array to match the amount of information I've learnt so far.
Thank you, I also understood the code now.
Last edited on
Also, thank you Chervil for explaining the point I had misunderstood. I took in a = word[0]. But, after you explained it I caught the mistake.
Topic archived. No new replies allowed.