Search code examples
javapalindrome

System.out.println is not printing output?


I am trying to have the list for palindrome but it doesn't give any kind of output. But it works when I am checking for palindrome.

public class Main {
    public static void main(String[] args) {
        int num=0 ,org=0 , rem = 0,rev=0 ,a=0;
        for(num=12 ; num<=101; num++) {
            org=num ;

            while(num>0) {
                rem = num % 10 ; 
                num = num /10 ;
                rev= (10*rev)+rem;
            }

            if(rev==org)
                System.out.println(org);
        }
    }
}

Why am I not getting any output?


Solution

  • You have two errors :

    1. You should reset rev to 0 in each iteration (otherwise, rev would only be correct in the first iteration).
    2. You should add num=org; at the end of each iteration, to restore the value of your loop variable. Otherwise, the loop may never terminate, since you are messing with the loop variable inside the body of the loop.

    It should look like this :

    for(num=12 ; num<=101; num++) {   
        org=num ;   
        rev = 0; // added
        while(num>0) {
          rem = num % 10 ; 
          num = num /10 ;
          rev= (10*rev)+rem;
        }
        if(rev==org)
            System.out.println(org);
        num = org; // added
    }
    

    Output :

    22
    33
    44
    55
    66
    77
    88
    99
    101