Menu
Topics Index
...
`

Loops


If you need explanation Read this topic

If you need Answer Take test on this topic

Loops
What will be the output of the following program?
public class Printstatment14
{
    public static void Elements(int[] arr)
    {
        for (int i = 0; i < arr.length; i++)
        {
            boolean isValid = false;
            for (int j = 0; j < i; j++)
            {
                if (arr[i] == arr[j])
                {
                    isValid = true;
                    break;
                }
            }
            if (!isValid)
            {
                System.out.print(arr[i] + " ");
            }
        }
    }
    public static void main(String a[])
    {
        int[] nums = {5, 2, 7, 2, 4, 7, 8, 2, 3};
        Printstatment14.Elements(nums);
    }
}

A. 5 2 7 4 8 3
B. 2 7
C. 4 7 8 2
D. 2
E. Compilation Error or Runtime Error
Topic: Unknown

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.

Answer is A...GIven program prints the unique elements in the array...Outer for loop is to iterate across every element in the array...In the inner for loop,we see if the element at a particular index location (arr[i]) is already present at any of the locations in the array before to that index location...if the number is present,then is valid is true and we dont print the element.....if the number is not present,that means it is the unique number among the numbers that are traversed so far and prints the number on the console.

Posted by Shashanka Mogaliraju    2014-12-25 13:06:31


ANS IS A
Above program logic is used to "remove the duplicate numbers" from the given Array.

--static fumction "Elements" is called by passing the array of integers.

--Two loops are used :
1.first loop runs till the length of array
2.second loop runs till the counter value of outer loop at particular instance

first loop is used to check whether particular element i.e. arr[i] is present  in the array before that index 'i'.if that element is present before that index then loop is broken with the help of "BREAK" keyword and "isvalid=TRUE".

Element is printed if isvalid is FALSE.

So,Duplicate Element will not get printed.

Posted by Mânïshå Mùlchåndânï    2014-12-25 15:22:29


This dose is now closed and the winners are Shashanka Mogaliraju,  for 'First Correct Comment', Mânïshå Mùlchåndânï,  for 'Best Comment' and Sai Ram for the 'Popular Comment'. The 'lucky liker' is Maheshwari Natarajan. 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-26 04:03:05


© meritcampus 2019

All Rights Reserved.

Open In App