Menu
Topics Index
...
`

Nested For loop output808


If you need explanation Read this topic

If you need Answer Take test on this topic

Nested For loop output808
What will be the output of the following program?
class NestedForloop
{
    public static void main(String s[])
    {
        int sum = 5;        
        int i = 1;
            
        for( ; i < 4; )
        {
            for(int j = 1; j < 4; )
            {
                for(int k = 1; k < 4; k++)
                {
                    sum = (i * j);
    
                    i++;
                    j++;
                    k++;
                }
            }
        }
        System.out.println("Sum = " + sum);
    }
}

A. Sum = 35
B. Sum = 576
C. Sum = 16
D. Compilation Error
E. Runtime Error
Topic: Nested for Loop In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

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

c sum =16 .....with each k loop increment the values of i, j k are also incrememted... as sum =i*j.. each time a new value of I and j is multiplied and stored in sum without taking into account the previous value of sum i.e previous value of sum is lost everytime in each iteration.. now the final vaalue of sum will be based upon the final values of I and j... wich are 4,4 hence final sum value =16

Posted by Asma Mujtaba Khan    2014-12-15 04:17:18


ans c.

in this program nested for loop concept is used.
A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes.

initially sum is initialized with 5 and i with 1.

outer for loop condition satisfied i<4==1<4
thn j=1;j<4 true so control goes 2nd inner  for loop.

k=1,1<4,k++ here sum=1*1=1
all i,j,k postincremented by 1,
k two times incremented.aft this i=2,j=2,k=3
k=3,3<4,k++ nw sum=2*2=4
thn postincrement i,j,k
aft this i=3,j=3,k=5
for loop condition faild so 1st inner for loop gets control.
j=3,j<4

2nd inner for loop gets control here
k=1,k<4,k++ passed,sum=3*3=9

thn postincremnt .aft i=4,j=4,k=3

k=3,3<4 condition satisfied so sum=4*4=16

aft post++ i=5,j=5,k=5
condition failed for all the loops.

so control goes out of outer for loop

sop prints sum=16

Posted by Maheshwari Natarajan    2014-12-15 08:22:02


This dose is now closed and the winners are Asma Mujtaba Khan,  for 'First Correct Comment', Sai Ram,  for 'Best Comment' and Sai Ram for the 'Popular Comment'. The 'lucky liker' is Shashanka Mogaliraju. 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    2014-12-16 03:02:02


© meritcampus 2019

All Rights Reserved.

Open In App