Home > Software design >  Cannot find a logical sense
Cannot find a logical sense

Time:06-13

i already studied c in school and during the last days i have been doing the beginner c course of codecademy. On codecademy there is an exercise in which i have to identify palindrome words and return true or false. I haven't been able to resolve it so i saw the solution and it was:

#include <iostream>

// Define is_palindrome() here:
bool is_palindrome(std::string text) {
  
  std::string reversed_text = "";
  
 

 for (int i = text.size() - 1; i >= 0; i--) {
    reversed_text  = text[i];

  }
  

  if (reversed_text == text) {
    return true;
  }
  
  return false;
  
}

int main() {
  
  std::cout << is_palindrome("madam") << "\n";
  std::cout << is_palindrome("ada") << "\n";
  std::cout << is_palindrome("lovelace") << "\n";
  
}

My only doubt is with this line:

for (int i = text.size() - 1; i >= 0; i--) {
    reversed_text  = text[i];

i know it has to do with index values but i can't understand why it has a -1. Could somebody explain this to me?

i thanks in advance whoever read this post. i'm sorry for my english or my poor using of stacksoverflow, i'm italian and that's my first time using this site.

CodePudding user response:

i know it has to do with index values but i can't understand why it has a -1.

If a string is n characters long, the characters in it are indexed from 0 to n−1.

Since the loop works with characters from the end of the string to the beginning, it starts with index text.size() - 1.

However, the solution you have shown is nominally inefficient. There is no reason to make a reversed copy of the string. It suffices merely to test whether each character in the first half of the string equals the character in the reflected position:

bool is_palindrome(std::string text)
{
    size_t e = text.size();
    for (int i = 0; i < e/2;   i)
        if (text[i] != text[e-1-i])
            return false;
    return true;
}

CodePudding user response:

for (int i = text.size() - 1; i >= 0; i--) {
    reversed_text  = text[i];

text is basically the string that you receive as input via function. size() is function that returns the size of the string i.e text.size() so in our test cases it will return

  1. 5 for madam
  2. 3 for ada
  3. 8 for lovelace

If you think about the strings as an array with exact above size then the index range will become

  1. 0-4 for madam
  2. 0-2 for ada
  3. 0-7 for lovelace

So that's why the text.size()-1 is using as the starting index of loop. text.size() will return the actual size of string and then minus 1 to get the index of last character in string.

so behind the scene, your loop iteration will look something like below

for (int i = 4; i >= 0; i--) {  //for madam
}
//aca
for (int i = 2; i >= 0; i--) {  
}
//lovelace
for (int i = 7; i >= 0; i--) {  
}

I hope it clear out your confusion.

Thanks,

  •  Tags:  
  • c
  • Related