47 views

Why is this code... running infinitely..... ? Though I m  decrementing the n value, it  is running infinitely ?

public class Prog {

public static void main(String[] args) {
printIt(2, "Welcome");
}
public static void printIt(int n, String m) {
while (n > 1) {
System.out.println(m);
printIt(n--, m);

}
}

}
Category
asked Jul 15, 2015
edited May 27, 2016 | 47 views

+1 vote

Here the output will be Welcome indefinitely because the value of n is not changing it is 2 and n-- will not immediately decrement the value to 1.The program can be defined as below :

System.out.println("Welcome ");
while (2 > 1) {
System.out.println("Welcome ");
while (2 > 1) {
System.out.println("Welcome ");
while (2 > 1) {
System.out.println("Welcome ");
while (2 > 1) {
System.out.println("Welcome ");
while (2 > 1) {
System.out.println("Welcome ");

So obviously the output will be "Welcome" !
answered Jul 16, 2015 by
edited May 27, 2016
Superb :-):-):-) and if it is like --n ...it will work fine