+ 2
This java code reverse any integer,but i don't understand how it works since rev=0; rev*10 in a while loop shouldn't be zero?
import java.util.Scanner; public class H { public static void main(String[] args) { int no, rev = 0, r; Scanner s = new Scanner(System.in); System.out.println("Enter any no.: "); no = s.nextInt(); while (no > 0) { r = no % 10; rev = rev * 10 + r; no = no / 10; } System.out.println("Reverse: " + rev); } }
3 Answers
0
Dessie Bahiru Don't forget that the loop will continue to run while (no > 0)
So even if 'rev = 0' after the first run through the loop, as long as (no > 0) the loop will continue to run
Which means the value of 'rev' could change after each iteration
Edit to your code below isn't perfect, but I find it helps to print each iteration to see the changes, what's going on behind the scenes
Hope that helps š
https://code.sololearn.com/cZl46p5S91I9/?ref=app
0
Write print statement after rev=rev*10+r; or last statement in while loop to look how the values are changing..
by printing variable values...you find it easily.. like
System.out.println(r+" "+rev+" "+no);