0 votes
43 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);

}
}

}
asked Jul 15, 2015 in Computer Science - IT by nagini s (82 points)
edited May 27, 2016 by slow_learner | 43 views

1 Answer

+1 vote
Best answer

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 kevin (337 points)
edited May 27, 2016 by slow_learner
Superb :-):-):-) and if it is like --n ...it will work fine