Java program for interview

For example the given array is {2,3,4,5}, we have to get the output as multiple of 3 * 4 * 5 = 60, in next line we have to get the multiple of 2 * 4 * 5 = 40, in next line we have to get the multiple of 2 * 3 * 5 = 30 and in next line we have to get the multiple of 2 * 3 * 4 = 24

Input: {2,3,4,5}
Output:
60
40
30
24

The source code is written below:

Program:

Method-1:

public class Main
{
public static void main(String[] args) {
int a[ ] = {1,2,3,4};
int n = a.length;
int b[ ] = new int[n];
for(int i = 0; i < a.length; i++)
b[i] = 1;
for(int i = 0; i < a.length; i++)
{
    for(int j = 0;j < a.length; j++)
    {
        if(i != j)
        b[i] *= a[j];
        
    }
}
for(int i = 0; i < a.length; i++)
System.out.println(b[i]);
}
}

Output:

24
12
8
6

Program:

Method-2:

public class Main
{
public static void main(String[] args) {
int a[ ] = {1,2,3,4};
int n = a.length;
int b[ ] = new int[n];
for(int i = 0; i < a.length; i++)
b[i] = 1;
for(int i = 0; i < a.length; i++)
{
    for(int j = 0; j < a.length; j++)
    {
        if(i != j)
        b[i] *= a[j];
        
    }
}
for(int i = 0; i < a.length; i++)
System.out.println(b[i]);
}

}


Output:

24
12
8
6

No comments:

Post a Comment