PROBLEM:
Write a program which will read in a sequence of positive intgers terminated by -1 to indictae the end of the input. These values will be read into an array and the program should then determine if the sequence is a palindrome.
A palindrome is a sequnce of number/characters/words etc which is the same when read from either direction. For example:
2 3 4 5 4 3 2
is a palindrome, since the sequnce is the same when read from left to right or from right to left.
2 3 4 5
Is NOT a palindrome.
SOLUTION:
The program does not know how big a sequnce will be entered so an array of characters larger than required is declared. The program then reads in the sequnce of integers one at a time into the array. After it has read in each integer it checks if it was a -1, if it was -1 it stops reading in. It also checks to ensure that we can't read in any more integers than the size of our array.
Once it has completed reading in the integers, the number of values read in can be determined, as i - 1 since we are not interested in the -1.
We can then search through the array comparing the 1st element with the last, the 2nd element with the 2nd last etc. As soon as we find that they don't match we can terminate the search as we know that the sequence is not a palindrome.
Note that we only have to loop for i < length/2 as we compare the first half of the array to the second half.
#include
Back to Main Page for Lecture 5