Arrays and Structures
Additional Examples


PROBLEM:

Write a program which will read in a sequence of positive integers terminated by -1 to indicate 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 sequence 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 sequence 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 sequence will be entered so an array of characters larger than required is declared. The program then reads in the sequence 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 <stdio.h>
#define SIZE 100

main()
{
        int     array[SIZE];
        int     i=0, length, palindrome = 1;


        printf("Enter A sequence of positive integer numbers\n");
        printf("terminated by -1\n");

        do
        {
                scanf("%d", &array[i]);
                i++;
        }while(array[i-1] != -1 && i < SIZE);

        length = i -1; /*don't need -1*/


        for (i=0; i < length/2 && palindrome == 1 ;i++)
        {
                if (array[i] != array[length - i - 1])
                        palindrome = 0;
        }


        if (palindrome == 1)
                printf("array is a palindrome\n");
        else
                printf("array is not a palindrome\n");
}


Back to Main Page for Lecture 5