Palindrome Array checker + Functions

I've been trying to solve this question, but I can't figure out why its not doing what its supposed to do, which is checking if a given array is palindromic or not.

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
#include<iostream>
using namespace std;
bool pal(int [],int);
void main()
{
        int a[100];
        int flag=0;
        int size;
        cout<<"Enter size of array: ";
        cin>>size;
        cout<<"Fill array: "<<endl;
        for(int i=0;i<size;i++)
                cin>>a[i];
        if(pal(a,size)==true)
                cout<<"The array is a palindrome"<<endl;
        else
                cout<<"The array is not a palindrome"<<endl;
}
bool pal(int a[],int size)
{
        for(int i=0;i<(size/2);i++)
                if(a[i]==a[size-i-1])
                        return true;
                else
                        return false;
}




I am pretty sure that the problem lies in the loop of the function, where it will check that the first two are equal and return true. What I don't know to implement is how to keep it checking until it has completely verified that all cell values are equal to their opposite counterpart...




UPDATE: I modified it so it could work, but I feel that my solution is kind of sloppy and inefficient. I would really appreciate it if someone could help me implement this with a for loop...

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
#include<iostream>
using namespace std;
bool pal(int [],int);
void main()
{
	int a[100];
	int flag=0;
	int size;
	cout<<"Enter size of array: ";
	cin>>size;
	cout<<"Fill array: "<<endl;
	for(int i=0;i<size;i++)
		cin>>a[i];
	if(pal(a,size)==true)
		cout<<"The array is a palindrome"<<endl;
	if(pal(a,size)==false)
		cout<<"The array is not a palindrome"<<endl;
}
bool pal(int a[],int size)
{
	int i=0;
	int flag=0;
	while(flag==0 && i<size){
		if(a[i]==a[size-i-1]){
			flag=0;
			i++;
		}

		else{
			flag=1;
		}
	}
	if(flag==0)
		return true;
	else
		return false;
}
Last edited on
You are supposed to implement bool pal() using recursion. Try to search for some sample code of recursion.
After looking at recursion examples, We weren't taught to use it, and questions are usually given to us with specific requirements so I assume that I can't use recursion even if it was a solution...
Have a count in your function to count how many are equal. Then compare the count with the size/2. This will work if you're checking if the whole array is a palindrome.
Topic archived. No new replies allowed.