Search code examples
c++printingpalindrome

Printing all palindrome numbers in a given range


I'm trying to write a program that would print all palindrome in range [a, b]. I've written this so far, but nothing is printed after I input the values for a, b. What is missing?

#include "stdafx.h"
#include <iostream>
using namespace std;

int t = 0, rmd, z, a, b;

int reverse() {
    while (z != 0) {
        rmd = z% 10;
        t = t * 10 + rmd;
        z/= 10;
        }

    return t;
}

int palin() {
    if (a == reverse()) {
        return 1;
    }
    else 
        return 0;

}

int main() {

    cout << "a: "; cin >> a;
    cout << "b: "; cin >> b;

    while (a <= b) {
        z = a;
        if (palin()) 
            cout << a << endl;
        a++;
    }
    system("pause");
    return 0;
}

Solution

  • Your use of variables is what is confusing you. The actual issue is not setting t to zero every time you call reverse, but you should think about how you use variable scoping and what functions actually do. Right now you have 2 procedures, that perform actions on global data. Instead try to formulate the problem using functions that accept arguments, and return a result.

    #include <iostream>
    
    using namespace std;
    
    int reverse(int z) {
        int t = 0;
    
        int rmd;
        while (z != 0) {
            rmd = z % 10;
            t = t * 10 + rmd;
            z/= 10;
        }
    
        return t;
    }
    
    int palin(int z) {
        return z == reverse(z);
    }
    
    int main() {
        int a, b;
    
        cout << "a: "; cin >> a;
        cout << "b: "; cin >> b;
    
        while (a <= b) {
            if (palin(a)) {
                cout << a << endl;
            }
            a++;
        }
        system("pause");
        return 0;
    }