Hello C++ nerds,
I am trying to do a palindrome using a dynamic array but before I spend 6 hours on this, is it possible to do it this way?
As you can see the user will input how many characters he wants in the array, then proceed to enter the chars one by one.
I have several questions regarding my code:
1) I learned how to declare a dynamic array from the tutorials, yet, I don't understand the use of (notthrow) in my code. Line 10. Can someone explain what it means?
2) Am I doing the right thing when I equalize p[0] = left and p[n] = right? my initial thought was that I would set those values first then I will decrease p[n] - 1 and increase p[0] + 1 and compare them, if they're equal then it's a palindrome. The problem with this approach is when I reach the middle, I don't know what to do.
3) There is some conditions that need to be addressed, what is the best way to test this program? what are some common ways that, if I follow, will instantly increase my testing ability?
This is one of the conditions that returns true although it's not a palindrome:
1 2 3 4 5 6 7
|
How many letters would you like to type? 4
Enter letter:a
Enter letter:s
Enter letter:a
Enter letter:a
true
Press any key to continue . . .
|
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
|
#include <iostream>
using namespace std;
void isPalidrome()
{
int i, n; // i = number of elements, n = global variable in the function.
char left, right;
char * p;
cout << "How many letters would you like to type? ";
cin >> i;
p = new (nothrow) char[i];
if (p == nullptr)
{
cout << "Error: memory could not be allocated";
}
else
{
for (n = 0; n < i; n++)
{
cout << "Enter letter:";
cin >> p[n];
}
}
left = 0, right = n - 1;
// testing if isPalindrome
if (left == right)
{
while (left < right)
{
if (p[left++] != p[right--])
{
cout << "not a palindrome";
}
}
}
else
{
cout << "true" << endl;
}
}
int main()
{
isPalidrome();
system("PAUSE");
return 0;
}
|