info@meritcampus.com    +91-85006-22255
...
`

Print Formation
What will be the output of the following program?
`class PrintFormation {    public static void main(String[] args)     {        for (int i = 0; i < 5; i++)         {            for (i = 0; i < 4; i++)             {                System.out.print(i + " ");            }        }    }}`

 A. 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 B. 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 C. 0 1 2 3 D. Compilation Error E. Goes into infinite loop
Topic:

### User comments below.All of them might not be correct.

ans is A as print statment is in the inner loop and every time i values gets updated with the recent iterartion i=0 to i=3 when i=4 condition fails and gets out of the  loop and i=2 and again prints the elements of inner block itreatively untill i=5 where the outer block condition fails,,,,

Posted by Sai Veerendra    2015-01-30 09:03:35

ans c....... it will print 0123 .....lets see how..... here we have nested loop.... in the outer loop -> initialy i=0 .....loop condition met so it will enter into the loop.... -> inside outer loop thrre is another loop MAKING i=0 ..here agn loop cndtn met so it will enter into inner loop and performs execution by printng i,as 0 1 2 3..... wen i=4 in inner loop den condition fails and exit the inner loop...... now after exit it will execute i (plus) (plus)  of the outrloop... and I will be incrmntd to 5 .....as now i=5 condition of outr loop fails.... so it will exit frm outr loop too.....

Posted by Asma Mujtaba Khan    2015-01-30 10:23:09

ANS IS C (0 1 2 3)

--Here,Iterative Statement i.e. "NESTED FOR LOOP" is used.

--In above program,Nested for loops are used with same
counter "i".

--Outer loop runs from 0 to 5 and inner from 0 to 4.

Iteration 1:
In outer loop,i=0,0<5(true) control goes to inner FOR loop
i=0 and 0<4 (true)
Print is used to print the value of i
0
i++ --> i=1 ---> 1<4(true)
1
i++ --> i=2 ---> 2<4(true)
2
i++ --> i=3 ---> 3<4(true)
3
i++ --> i=4 ---> 4<4(false)
control goes out from inner loop and iteration of outer
loop continues i.e. i++,so i=5 and 5<5 (false).Therefore
control moves out of the outer FOR loop.

--so, 0 1 2 3 will get printed.

Posted by Mânïshå Mùlchåndânï    2015-01-30 18:31:00

B

Posted by Goutham Singarapu    2015-01-31 03:28:10

This dose is now closed and the winners are Asma Mujtaba Khan,  for 'First Correct Comment', Mânïshå Mùlchåndânï,  for 'Best Comment' and Mânïshå Mùlchåndânï for the 'Popular Comment'. The 'lucky liker' is Ammad Islam. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2015-02-02 06:29:48