Java Program to Separate 0s on Left Side and 1s on Right Side of an Array of 0s and 1s in Random Order

Java Program to Separate 0s on Left Side and 1s on Right Side of an Array of 0s and 1s in Random Order

In the previous article, we have seen Java Program to Arrange the Elements of a Given Array of Integers Where All Negative Integers Appear Before All the Positive Integers

In this article we are going to see how to separate 0s on Left Side and 1s on Right Side of an Array of 0s and 1s in random order using Java programming language..

Java Program to Separate 0s on Left Side and 1s on Right Side of an Array of 0s and 1s in Random Order

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to separate 0s on Left Side and 1s on Right Side of an Array of 0s and 1s in random order.

Method-1: Java Program to Separate 0s on Left Side and 1s on Right Side of an Array of 0s and 1s in Random Order By Static Initialization of Array Elements

Approach:

  • Declare and initialize an array.
  • Initialize two pointers, i = 0, j = arr.length – 1.
  • While i <= j, if the element at i is equal to 0, increment i.
  • If the element at j is equal to 1, decrement j.
  • Now at index i, there is 1 and at index j, there is 0, so swap these two.

Program:

public class Main
{
    public static void main(String[] args) 
    {
        int[] nums = { 0, 1, 0, 0, 1, 1, 0, 0, 1 };
        System.out.print("Original array: ");
        
        for (int i : nums)
        {
            System.out.print(i + " ");
        }
        
        modifyMethod(nums);
        System.out.print("\nModified array: ");
        for (int i : nums) {
            System.out.print(i + " ");
        }

    }

    static void modifyMethod(int[] nums) {
        int i = 0;
        int j = nums.length - 1;
        while (i <= j) {
            // if the element at i is negative, increment i
            if (nums[i] == 0 )
                i++;
            // if the element at j is positive, increment j
            if (nums[j] == 1)
                j--;
            // swap the elements
            if (i <= j) {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }
    }
}

Output:

Original array: 0 1 0 0 1 1 0 0 1 
Modified array: 0 0 0 0 0 1 1 1 1

Method-2: Java Program to Separate 0s on Left Side and 1s on Right Side of an Array of 0s and 1s in Random Order By Dynamic Initialization of Array Elements

Approach:

  • Ask use length of the array.
  • Initialize the array with given size.
  • Ask the user for array elements.
  • Initialize two pointers, i = 0, j = arr.length – 1.
  • While i <= j, if the element at i is equal to 0, increment i.
  • If the element at j is equal to 1, decrement j.
  • Now at index i, there is 1 and at index j, there is 0, so swap these two.

Program:

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        // asking user to enter the number of elements
        System.out.println("Enter number of elements in the array: ");
        int n = sc.nextInt();
        // initializing the array
        int[] nums = new int[n];
        // asking user to enter the elements
        System.out.println("Enter elements of the array: ");
        for (int i = 0; i < n; i++) 
        {
            nums[i] = sc.nextInt();
        }

        System.out.print("Original array: ");
        for (int i : nums) 
        {
            System.out.print(i + " ");
        }
        
        //calling modifyMethod() method
        modifyMethod(nums);
        System.out.print("\nModified array: ");
        for (int i : nums) 
        {
            System.out.print(i + " ");
        }

    }

    static void modifyMethod(int[] nums) 
    {
        int i = 0;
        int j = nums.length - 1;
        while (i <= j) {
            // if the element at i is negative, increment i
            if (nums[i] == 0 )
                i++;
            // if the element at j is positive, increment j
            if (nums[j] == 1)
                j--;
            // swap the elements
            if (i <= j) {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }
    }
}

Output:

Enter number of elements in the array: 
5
Enter elements of the array: 
1 0 1 0 1 1
Original array: 1 0 1 0 1 
Modified array: 0 0 1 1 1

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

Related Java Programs:

Java Program to Check Pointer Prime Number

Java Program to Check Pointer Prime Number

In the previous article, we have seen Java Program to Check Insolite Number

In this article we are going to see  how we can write a program to find out whether the number is pointer prime or not.

Java Program to Check Pointer Prime Number

The number which is a prime number, and the next prime number can be find out by adding the product of the digit to its number is called pointer prime.

Let’s see different ways to check pointer prime number.

Method-1: Java Program to Check Pointer Prime Number

Approach :

  • Initialize an integer variable and declare the value to it .
  • Check the number is prime or not.
  • If the number is prime, then find out the product of the digit and add to itself and check whether the result is next prime to it or not .
  • If number is not prime the return false .

Program :

import java.util.*;
public class Main
{
       // Driver Code
        public static void main(String[] args)
        {
                // Given Number num
                int num = 1123;
                // Function Call
                if (isPointerPrime(num))
                        System.out.print("Entered number "+num+" is Pointer Prime");
                else
                        System.out.print("Entered number "+num+" is not Pointer Prime");
        } 
            
    // Function that returns true if a is prime else returns false
    static boolean isPrime(int num)
    {
            // Corner cases
            if (num <= 1)
                return false;
            if (num <= 3)
                 return true;
            // This is checked so that we can skip middle five numbers in below loop
            if (num % 2 == 0 || num % 3 == 0)
                 return false;
            for (int x = 5; x * x <= num; x = x + 6)
                    if (num % x == 0 || num % (x + 2) == 0)
                return false;
            return true;
    }
        
    // Function to find the product of digits of num number N
    static int digprod(int num)
    {
        int prod = 1;
        while (num != 0)
            {
                prod = prod * (num % 10);
                num = num / 10;
            }
        return prod;
    }
    
    // Function to return the next prime 
    static int nxtprm(int num)
        {
 
            // Base case
            if (num <= 1)
                return 2;
 
            int prime = num;
                boolean found = false;
            // Loop continuously until isPrime returns true for a number greater than n
            while (!found)
                {
                    prime++;
                    if (isPrime(prime))
                    found = true;
                }
             return prime;
        }
        
        // Function to check Pointer-Prime numbers
        static boolean isPointerPrime(int num)
            {
                if (isPrime(num) && (num + digprod(num) == nxtprm(num)))
                        return true;
                else
                    return false;
            }
}
Output:

Entered number 1123 is Pointer Prime

Method-2: Java Program to Check Pointer Prime Number

Approach :

  • Initialize a integer variable and take the value for it as user input.
  • Check the number is prime or not
  • If the number is prime then find out the product of the digit and add to itself and check whether the result is next prime to it or not .
  • If number is not prime the return false .

Program :

import java.util.*;

public class Main
{
    
    // Driver Code
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        // entering the number  through user input 
        System.out.print("Enter a number  : ");
        int num= s.nextInt();
        // Function Call
        if (isPointerPrime(num))
            System.out.print("Entered number "+num+" is Pointer Prime");
         else
            System.out.print("Entered number "+num+" is not Pointer Prime");
    } 
   
    // Function that returns true if a is prime else returns false
    static boolean isPrime(int num)
    {
            // Corner cases
            if (num <= 1)
                return false;
            if (num <= 3)
                 return true;
            // This is checked so that we can skip middle five numbers in below loop
            if (num % 2 == 0 || num % 3 == 0)
                 return false;
            for (int x = 5; x * x <= num; x = x + 6)
                    if (num % x == 0 || num % (x + 2) == 0)
                return false;
            return true;
    }
    
    // Function to find the product of digits of num number N
   static int digprod(int num)
    {
        int prod = 1;
        while (num != 0)
            {
                prod = prod * (num % 10);
                num = num / 10;
            }
        return prod;
    }
    
    // Function to return the next prime 
    static int nxtprm(int num)
        {
 
            // Base case
            if (num <= 1)
                return 2;
 
            int prime = num;
                boolean found = false;
            // Loop continuously until isPrime returns true for a number greater than n
            while (!found)
                {
                    prime++;
                    if (isPrime(prime))
                    found = true;
                }
             return prime;
        }
        
        // Function to check Pointer-Prime numbers
        static boolean isPointerPrime(int num)
            {
                if (isPrime(num) && (num + digprod(num) == nxtprm(num)))
                        return true;
                else
                    return false;
            }
}

Output:

Enter a number : 23
Entered number 23 is Pointer Prime

Access the Simple Java program for Interview examples with output from our page and impress your interviewer panel with your coding skills.

Related Java Programs:

Java Program to Check Canada Numbers

Java Program to Check Canada Numbers

In the previous article, we have seen Java Program to Check Pointer Prime Number

In this article we are going to see how we can write a program to find out whether the number is Canada number or not.

Java Program to Check Canada Numbers

The number whose sum of square of digit is equal to the sum if of non- trivial factor of that number  is called Canada number.

Let’s see different ways to check whether the number is Canada number or not.

Method-1: Java Program to Check Canada Numbers By Using Static Value

Approach :

  • Declare a number.
  • Calculate its sum of the square of the digits.
  • Calculate its sum of non trivial factors.
  • Check if both are same or not. If same print number as Canada number else not Canada number .

Program :

import java.util.*;

public class Main
{
    
        // Driver Code
        public static void main (String[] args)
                {
                    // Given Number
                    int num = 8549;
                    // Function Call
                    if (isCanada(num))
                        System.out.println("Number is Canada Number");
                    else
                        System.out.println("Number is not Canada Number");
                }
                
        // Function to return sum  of squares of digits of a number
        static int gets(int num)
            {
                int s = 0;
                while (num != 0)
                    {
                        int r = num % 10;
                        s  = s  + r * r;
                        num = num / 10;
                    }
                return s ;
            }
            
        // Function to calculate sum of  all trivial divisors of given  number
        static int divs(int numm)
            {
                // Final result of sum  of trivial divisors
                int res = 0;
                 // Find all divisors which  divides 'numm'
                for (int x = 1; x <= Math.sqrt(numm); x++)
                        {
                            // if 'x' is divisor of 'numm'
                            if (numm % x == 0)
                                {
                                    // if both divisors are same then add  it only once else add both
                                    if (x == (numm / x))
                                        res += x;
                                    else
                                        res += (x + numm / x);
                                }
                        }
                    return (res  - 1 - numm);
            }
            
        // Function to check if N is a Canada number
        static boolean isCanada(int num)
                {
                    return divs(num) == gets(num);
                }
                
}

Output:

Number is Canada Number

Method-2: Java Program to Check Canada Numbers By User Input Value

Approach :

  • Take input of a number.
  • Calculate its sum of the square of the digits.
  • Calculate its sum of non trivial factors.
  • Check if both are same or not. If same print number as Canada number else not Canada number .

Program :

import java.util.*;
public class Main
    {
        // Driver Code
        public static void main (String[] args)
                {
                    Scanner s = new Scanner(System.in);
                // entering the number  through user input 
                System.out.print("Enter a number  : ");
                int num= s.nextInt();
                    // Function Call
                    if (isCanada(num))
                        System.out.println("Number is Canada Number");
                    else
                        System.out.println("Number is not Canada Number");
                }
                
        // Function to return sum  of squares of digits of a number
        static int gets(int num)
            {
                int s = 0;
                while (num != 0)
                    {
                        int r = num % 10;
                        s  = s  + r * r;
                        num = num / 10;
                    }
                return s ;
            }
        // Function to calculate sum of  all trivial divisors of given  number
        static int divs(int numm)
            {
                // Final result of sum  of trivial divisors
                int res = 0;
                 // Find all divisors which  divides 'numm'
                for (int x = 1; x <= Math.sqrt(numm); x++)
                        {
                            // if 'x' is divisor of 'numm'
                            if (numm % x == 0)
                                {
                                    // if both divisors are same then add  it only once else add both
                                    if (x == (numm / x))
                                        res += x;
                                    else
                                        res += (x + numm / x);
                                }
                        }
                    return (res  - 1 - numm);
            }
        // Function to check if N is a Canada number
        static boolean isCanada(int num)
                {
                    return divs(num) == gets(num);
                
                }
    }
Output:

Enter a number : 16999
Number is Canada Number

Provided list of Simple Java Programs is specially designed for freshers and beginners to get familiarize with the concepts of Java programming language and become pro in coding.

Related Java Programs:

Java Program to Separate all Even Numbers First and Then Odd Numbers

Java Program to Separate all Even Numbers First and Then Odd Numbers

In the previous article, we have seen Java Program to Separate 0s on Left Side and 1s on Right Side of an Array of 0s and 1s in Random Order

In this article we are going to see how to separate all even numbers first and then odd numbers using Java programming language.

Java Program to Separate all Even Numbers First and Then Odd Numbers

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to separate all even numbers first and then odd numbers.

Method-1: Java Program to Separate all Even Numbers First and Then Odd Numbers By Static Initialization of Array Elements

Approach:

  • Initialize two pointers, i = 0, j = arr.length – 1.
  • While i <= j, if the element at i is even, increment i.
  • If the element at j is odd, decrement j.
  • Now at index i, there is an even element and at index j, there is an odd element, so swap these two.

Program:

public class Main 
{
    public static void main(String[] args) 
    {
        // initialize the array
        int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        // print the array
        System.out.print("Original array: ");
        for (int i : nums)
        {
            System.out.print(i+ " ");
        }
        // call the method
        placeNumber(nums);
        // print the array
        System.out.print("\nModified array: ");
        for (int i : nums) 
        {
            System.out.print(i + " ");
        }
    }

    //placeNumber() method to keep all even numbers first 
    //then all negative number in array
    static void placeNumber(int[] nums) 
    {
        int i = 0;
        int j = nums.length - 1;
        while (i <= j) 
        {
            // if the element at i is negative, increment i
            if (nums[i] % 2 == 0 )
                i++;
            // if the element at j is positive, increment j
            if (nums[j] % 2== 1)
                j--;
            // swap the elements
            if (i <= j) 
            {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }
    }
}
Output:

Original array: 1 2 3 4 5 6 7 8 9 10 
Modified array: 10 2 8 4 6 5 7 3 9 1

Method-2: Java Program to Separate all Even Numbers First and Then Odd Numbers By Dynamic Initialization of Array Elements

Approach:

  • Ask use length of the array.
  • Initialize the array with given size.
  • Ask the user for array elements.
  • Initialize two pointers, i = 0, j = arr.length – 1.
  • While i <= j, if the element at i is even, increment i.
  • If the element at j is odd, decrement j.
  • Now at index i, there is an even element and at index j, there is an odd element, so swap these two.

Program:

import java.util.*;

public class Main 
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        // asking user to enter the number of elements
        System.out.println("Enter number of elements in the array: ");
        int n = sc.nextInt();
        // initializing the array
        int[] nums = new int[n];
        // asking user to enter the elements
        System.out.println("Enter elements of the array: ");
        for (int i = 0; i < n; i++) {
            nums[i] = sc.nextInt();
        }

        // print the array
        System.out.println("Original array: ");
        for (int i : nums)
        {
            System.out.print(i+ " ");
        }
        // call the method
        placeNumber(nums);
        // print the array
        System.out.println("\nModified array: ");
        for (int i : nums) 
        {
            System.out.print(i + " ");
        }
    }

    //placeNumber() method to keep all even numbers first 
    //then all negative number in array
    static void placeNumber(int[] nums) 
    {
        int i = 0;
        int j = nums.length - 1;
        while (i <= j) 
        {
            // if the element at i is negative, increment i
            if (nums[i] % 2 == 0 )
                i++;
            // if the element at j is positive, increment j
            if (nums[j] % 2== 1)
                j--;
            // swap the elements
            if (i <= j) 
            {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }
    }
}
Output:

Enter number of elements in the array: 
5
Enter elements of the array:
2 3 1 5 6 
Original array: 
2 3 1 5 6 
Modified array: 
2 6 5 1 3

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

Related Java Programs:

Java Program to Find all the Triplets Where Sum of All the Three Elements are Equal to a Specified Number

Java Program to Find all the Triplets Where Sum of All the Three Elements are Equal to a Specified Number

In the previous article, we have seen Java Program to Check if an Array of Integers without 0 and 1

In this article we will see find all the Triplets Where Sum of All the Three Elements are Equal to a Specified Number.

Java Program to Find all the Triplets Where Sum of All the Three Elements are Equal to a Specified Number

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find all the Triplets Where Sum of All the Three Elements are Equal to a Specified Number

Method-1: Java Program to Find all the Triplets Where Sum of All the Three Elements are Equal to a Specified Number By Static Initialization of Array Elements

Approach:

  • Declare and initialize an array.
  • Create three nested for loops.
  • First loop runs from start to end (counter i), second loop runs from i+1 to end (counter j) and third loop runs from j+1 to end (loop counter k)
  • Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.
  • If there is no triplet, then print that no triplet exists.

Program:

public class Main 
{
    public static void main(String[] args) 
    {
        int[] arr = { 2, 5, 7, 9, 3, -2, 1 };
        int sum = 14;
        System.out.println("Finding triplets whose sum are equal to : "+sum);
        System.out.println("The triplets are : ");
        findTriplet(arr, sum);
}
    
public static void findTriplet(int[] arr, int sum) 
{
   int count = 1;
        for (int i = 0; i < arr.length; i++) 
        {
            for (int j = i + 1; j < arr.length; j++) 
            {
                for (int k = j + 1; k < arr.length; k++) 
                {
                    if (arr[i] + arr[j] + arr[k] == sum) 
                    {
                        System.out.println("Triplet " + count + ": " + arr[i] + " " + arr[j] + " " + arr[k]);
                        count++;
                        break;
                    }
                }
            }
        }
    }
}
Output:

Finding triplets whose sum are equal to : 14
The triplets are : 
Triplet 1: 2 5 7
Triplet 2: 2 9 3
Triplet 3: 7 9 -2

Method-2: Java Program to Find all the Triplets Where Sum of All the Three Elements are Equal to a Specified Number By Dynamic Initialization of Array Elements

Approach:

  • Ask use length of the array.
  • Initialize the array with given size.
  • Ask the user for array elements.
  • Create three nested for loops.
  • First loop runs from start to end (counter i), second loop runs from i+1 to end (counter j) and third loop runs from j+1 to end (loop counter k)
  • Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.
  • If there is no triplet, then print that no triplet exists.

Program:

import java.util.*;

public class Main 
{
    public static void main(String[] args) 
    {
         Scanner sc = new Scanner(System.in);
        // asking user to enter the number of elements
        System.out.println("Enter number of elements in the array: ");
        int n = sc.nextInt();
        // initializing the array
        int[] arr = new int[n];
        // asking user to enter the elements
        System.out.println("Enter elements of the array: ");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        // asking user to enter the sum
        System.out.println("Enter sum: ");
        int sum = sc.nextInt();

        System.out.println("Finding triplets whose sum are equal to : "+sum);
        System.out.println("The triplets are : ");
        findTriplet(arr, sum);
}
    
public static void findTriplet(int[] arr, int sum) 
{
   int count = 1;
        for (int i = 0; i < arr.length; i++) 
        {
            for (int j = i + 1; j < arr.length; j++) 
            {
                for (int k = j + 1; k < arr.length; k++) 
                {
                    if (arr[i] + arr[j] + arr[k] == sum) 
                    {
                        System.out.println("Triplet " + count + ": " + arr[i] + " " + arr[j] + " " + arr[k]);
                        count++;
                        break;
                    }
                }
            }
        }
    }
}
Output:

Enter number of elements in the array: 5
Enter elements of the array: 2 2 1 4 5
Enter sum: 5
Finding triplets whose sum are equal to : 5
The triplets are : 
Triplet 1: 2 2 1

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs:

Java Program to Find all the Combination of Four Elements Where Sum of All the Four Elements are Equal to a Specified Number

Java Program to Find all the Combination of Four Elements Where Sum of All the Four Elements are Equal to a Specified Number

In the previous article, we have seen Java Program to Find all the Triplets Where Sum of All the Three Elements are Equal to a Specified Number

In this article we are going to see how to find all the Combination of Four Elements Where Sum of All the Three Elements are Equal to a Specified Number.

Java Program to Find all the Combination of Four Elements Where Sum of All the Four Elements are Equal to a Specified Number

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find all the Triplets Where Sum of All the Three Elements are Equal to a Specified Number

Method-1: Java Program to Find all the Combination of Four Elements Where Sum of All the Four Elements are Equal to a Specified Number By Static Initialization of Array Elements

Approach:

  1. Create four nested for loops and compare each quadruple with the required sum.
  2. If it’s equal, print the quadruple.

Program:

public class Main
{
    public static void main(String[] args) 
    {
        int[] arr = { 2, 3, 6, 7, 4, 1, 5, 0 };
        int sum = 14;
        System.out.println("Finding quadruple whose sum are equal to : "+sum); 
        System.out.println("The quadruple are : ");
        findQuadruples(arr, sum);
    }

    static void findQuadruples(int[] arr, int sum) 
    {
    int count = 1;
        int n = arr.length;
        for (int i = 0; i < n - 3; i++) 
        {
            for (int j = i + 1; j < n - 2; j++) 
            {
                for (int k = j + 1; k < n - 1; k++) 
                {
                    for (int l = k + 1; l < n; l++) 
                    {
                        if (arr[i] + arr[j] + arr[k] + arr[l] == sum)
                        {
                            System.out.print("Quadruple " + count + ": " + arr[i] + " " + arr[j] + " " + arr[k] + " " + arr[l] + "\n");
                            count++; 
                            break;
                        }
                    }
                }
            }
        }
    }
}

Output:

Finding quadruple whose sum are equal to : 14
The quadruple are : 
Quadruple 1: 2 3 4 5
Quadruple 2: 2 6 1 5
Quadruple 3: 2 7 4 1
Quadruple 4: 2 7 5 0
Quadruple 5: 3 6 4 1
Quadruple 6: 3 6 5 0
Quadruple 7: 3 7 4 0
Quadruple 8: 6 7 1 0

Method-2: Java Program to Find all the Combination of Four Elements Where Sum of All the Four Elements are Equal to a Specified Number By Dynamic Initialization of Array Elements

Approach:

  • Create scanner class object.
  • Ask use length of the array.
  • Initialize the array with given size.
  • Ask the user for array elements.
  • Create four nested for loops and compare each quadruple with the required sum.
  • If it’s equal, print the quadruple.

Program:

import java.util.*;

public class Main
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        // asking user to enter the number of elements
        System.out.println("Enter number of elements in the array: ");
        int n = sc.nextInt();
        // initializing the array
        int[] arr = new int[n];
        // asking user to enter the elements
        System.out.println("Enter elements of the array: ");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        // asking user to enter the required sum
        System.out.println("Enter the required sum: ");
        int sum = sc.nextInt();

        System.out.println("Finding quadruple whose sum are equal to : "+sum); 
        System.out.println("The quadruple are : ");
        findQuadruples(arr, sum);
    }

    static void findQuadruples(int[] arr, int sum) 
    {
    int count = 1;
        int n = arr.length;
        for (int i = 0; i < n - 3; i++) 
        {
            for (int j = i + 1; j < n - 2; j++) 
            {
                for (int k = j + 1; k < n - 1; k++) 
                {
                    for (int l = k + 1; l < n; l++) 
                    {
                        if (arr[i] + arr[j] + arr[k] + arr[l] == sum)
                        {
                            System.out.print("Quadruple " + count + ": " + arr[i] + " " + arr[j] + " " + arr[k] + " " + arr[l] + "\n");
                            count++; 
                            break;
                        }
                    }
                }
            }
        }
    }
}

Output:
Enter number of elements in the array: 
8
Enter elements of the array: 
6 3 1 2 4 7 5 4
Enter the required sum: 
12
Finding quadruple whose sum are equal to : 12
The quadruple are : 
Quadruple 1: 6 3 1 2
Quadruple 2: 3 1 4 4
Quadruple 3: 1 2 4 5
Quadruple 4: 1 2 5 4

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Related Java Programs:

Java Program to Find the Sum of All the Elements of an Array

Java Program to Find the Sum of All the Elements of an Array

In the previous article, we have seen Java Program to Replace Each Element of the Array with Sum of All Other Elements of the Array

In this article we are going to see how we can find the sum of elements of the array.

Java Program to Find the Sum of All the Elements of an Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find the sum of elements of the array.

Method-1: Java Program to Find the Sum of All the Elements of an Array By Static Initialization of Array Elements

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Find the sum of all elements by iterating using a for loop.
  • Print the sum.

Program:

import java.util.Arrays;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12,2,34,20,54,6};

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        // Adds the sum of all elements
        int sum = 0;        
        for(int i:arr)
        {
            sum+=i;
        }
        // Prints the sum
        System.out.println("The sum of all the array elements is: "+sum);
    }
}

Output:

The array elements are[12, 2, 34, 20, 54, 6]
The sum of all the array elements is: 128

Method-2: Java Program to Find the Sum of All the Elements of an Array By Dynamic Initialization of Array Elements

Approach:

  • Ask the user to enter the array size and store it.
  • Create an empty array of the specified size.
  • Ask the user to enter the elements.
  • Use a for loop to store the elements. Find the sum of all elements by iterating using a for loop.
  • Print the array elements.
  • Print the sum.

Program:

import java.util.Arrays;
import java.util.Scanner;
public class Main
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        // Taking size as input from the user
        System.out.println("Enter the array size : ");
        int size = scan.nextInt();

        // Creating the array
        int arr[] = new int[size];

        // Entering the array elements
        System.out.println("Enter array elements : ");
        int sum = 0;        
        for(int i=0;i<size;i++)
        {
            arr[i] = scan.nextInt();
            // Adds the sum of all elements
            sum+=arr[i];
        }

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        
        // Prints the sum
        System.out.println("The sum of all the array elements is: "+sum);
    }
}

Output:

Enter the array size 5
Enter array elements 1 2 3 4 5
The array elements are[1, 2, 3, 4, 5]
The sum of all the array elements is: 15

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs:

Java Program to Find the Product of All the Elements of an Array

Java Program to Find the Product of All the Elements of an Array

In the previous article, we have seen Java Program to Find the Sum of All the Elements of an Array

In this article we are going to see how we can find the product of elements of the array.

Java Program to Find the Product of All the Elements of an Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find the product of elements of the array.

Method-1: Java Program to Find the Product of All the Elements of an Array By Static Initialization of Array Elements

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Find the product of all elements by iterating using a for loop.
  • Print the sum.

Program:

import java.util.Arrays;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12,2,34,20,54,6};

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        // Multiplies the product of all elements
        int pro = 1;        
        for(int i:arr)
        {
            pro*=i;
        }
        // Prints the product
        System.out.println("The product of all the array elements is: "+pro);
    }
}

Output:

The array elements are[12, 2, 34, 20, 54, 6]
The sum of all the array elements is: 128

Method-2: Java Program to Find the Product of All the Elements of an Array By Dynamic Initialization of Array Elements

Approach:

  • Ask the user to enter the array size and store it.
  • Create an empty array of the specified size.
  • Ask the user to enter the elements.
  • Use a for loop to store the elements.
  • Find the product of all elements by iterating using a for loop.
  • Print the array elements.
  • Print the sum.

Program:

import java.util.Arrays;
import java.util.Scanner;
public class Main
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        // Taking size as input from the user
        System.out.println("Enter the array size : ");
        int size = scan.nextInt();

        // Creating the array
        int arr[] = new int[size];

        // Entering the array elements
        System.out.println("Enter array elements : ");
        int pro = 1;        
        for(int i=0;i<size;i++)
        {
            arr[i] = scan.nextInt();
            // Adds the sum of all elements
            pro*=arr[i];
        }

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        
        // Prints the product
        System.out.println("The product of all the array elements is: "+pro);
    }
}

Output:

Enter the array size 5
Enter array elements 1 2 3 4 5
The array elements are[1, 2, 3, 4, 5]
The sum of all the array elements is: 15

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs:

Java Program to Find the Largest Number in an Array

Java Program to Find the Largest Number in an Array

In the previous article, we have seen Java Program to Find the Average of an Array

In this article we are going to see how we can find the largest element in an array.

Java Program to Find the Largest Number in an Array

Prerequisite: 

See below articles to know more about Array, array declaration, array instantiation and array initialization.

Let’s see different ways to find largest element in the array.

Method-1: Java Program to Find the Largest Number in an Array By Comparing Array Elements

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Create a variable and store the first element of the array in it.
  • Compare the variable with the whole array to find and store the largest element.
  • Print the largest element.

Program:

import java.util.Arrays;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 2, 34, 20, 54, 6};

        // Initializing the first element of the array to large
        int large=arr[0];        
        
        // Compares all the element to find out the largest one
        for(int i:arr)
        {
            if(large<i)
                large=i;
        }

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        
        // Prints the largest element
        System.out.println("The largest element of the array is: "+large);
    }
}


Output:

The array elements are[12, 2, 34, 20, 54, 6]
The largest element of the array is: 54

Method-2: Java Program to Find the Largest Number in an Array By Using Arrays.sort Method

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Use Arrays.sort function to sort the array in ascending order.
  • Print the last element.

Program:

 import java.util.Arrays;
import java.util.Scanner;
public class array{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 2, 34, 20, 54, 6};
        
        // Sorts the array in ascending order
        Arrays.sort(arr);

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        
        // Prints the largest element
        System.out.println("The largest element of the array is: "+arr[arr.length-1]);
    }
}

Output:

The array elements are[2, 6, 12, 20, 34, 54]
The largest element of the array is: 54

Method-3: Java Program to Find the Largest Number in an Array By Using array list and collections

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Convert the array elements into a list.
  • Use the Collection.sort function to sort the list in ascending order.
  •  Print the last element.

Program:

import java.util.*;
import java.util.Scanner;
public class array{
    public static void main(String args[])
    {
        // Creating the array
        Integer arr[] = {12, 2, 34, 20, 54, 6};
        
        // Converts the array into a list
        List<Integer> list=Arrays.asList(arr);
        // Sorts the array in ascending order  
        Collections.sort(list);  

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        
        // Prints the largest element
        System.out.println("The largest element of the array is: "+list.get(arr.length-1));
    }
}

Output:

The array elements are[2, 6, 12, 20, 34, 54]
The largest element of the array is: 54

Method-4: Java Program to Find the Largest Number in an Array By Using Stream API

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Pass the array into the stream function max( ) to find out the largest element.
  •  Print the element.

Program:

import java.util.*;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 2, 34, 20, 54, 6};
        
        // Using the stream API
        int large = Arrays.stream(arr).max().getAsInt();  

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        
        // Prints the largest element
        System.out.println("The largest element of the array is: "+ large);
    }
}

Output:

The array elements are[12, 2, 34, 20, 54, 6]
The largest element of the array is: 54

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Related Java Programs:

Java Program to Separate Even and Odd Integers in an Array of Integers

Java Program to Separate Odd and Even Integers in Separate Arrays

In the previous article, we have seen Java Program to Separate Odd and Even Integers in Separate Arrays

In this article we are going to see how to separate odd and even integers in separate arrays in Java.

Java Program to Separate Even and Odd Integers in an Array of Integers

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to separate odd and even integers in separate arrays.

Method-1: Java Program to Separate Even and Odd Integers in an Array of Integers By Static Initialization of Array Elements

Approach:

  • Create an array with elements, and two blank arrays of same size.
  • Display the array elements to the user.
  • Pass both the arrays into an user function segregate() that segregates the elements by traversing through the array and storing odd and even elements at their respective arrays.
  • Print both odd and even arrays.

Program:

import java.util.*;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 22, 34, 22, 54, 6, 52, 8, 9, 34, 54, 68,10,20,30};
        int odd[] = new int[arr.length], even[] = new int[arr.length];
        // Prints the array elements
        System.out.println("The array elements are "+ Arrays.toString(arr));
        
        segregate(arr,odd,even);

    }
    
    // Function that segregates the array into two arrays
    static void segregate(int arr[], int odd[], int even[])
    {
        int oddCounter = 0, evenCounter = 0;
        // Segregating the array into two smaall arrays odd and even
        for(int i:arr)
        {
            if(i%2==0)
                odd[oddCounter++]=i;
            else
                even[evenCounter++]=i;
        }

        System.out.print("\nThe odd array elements are : ");
        // Prints odd element array
        for(int i=0;i<oddCounter;i++)
            System.out.print(odd[i]+" ");
        
        System.out.print("\nThe even array elements are : ");
        // Prints even element array
        for(int i=0;i<evenCounter;i++)
            System.out.print(even[i]+" ");
    }
}

Output:

The array elements are [12, 22, 34, 22, 54, 6, 52, 8, 9, 34, 54, 68, 10, 20, 30]

The odd array elements are : 12 22 34 22 54 6 52 8 34 54 68 10 20 30 
The even array elements are : 9

Method-2: Java Program Separate the Number of Even and Odd Integers in an Array of Integers By Dynamic Initialization of Array Elements

Approach:

  • Create an array by taking array elements as input, and two blank arrays of same size.
  • Display the array elements to the user.
  • Pass both the arrays into an user function segregate() that segregates the elements by traversing through the array and storing odd and even elements at their respective arrays.
  • Print both odd and even arrays.

Program:

import java.util.*;

public class Main
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        
        // Taking size as input from the user
        System.out.println("Enter the array size :");
        int size = scan.nextInt();
        
        // Creating the array
        int arr[] = new int[size];
        
        // Entering the array elements
        System.out.println("Enter array elements : ");
        for(int i=0;i<size;i++)
        {
            arr[i] = scan.nextInt();
        }
        
        int odd[] = new int[arr.length], even[] = new int[arr.length];
        // Prints the array elements
        System.out.println("The array elements are "+ Arrays.toString(arr));
        
        segregate(arr,odd,even);

    }
    
    // Function that segregates the array into two arrays
    static void segregate(int arr[], int odd[], int even[])
    {
        int oddCounter = 0, evenCounter = 0;
        // Segregating the array into two smaall arrays odd and even
        for(int i:arr)
        {
            if(i%2==0)
                even[evenCounter++]=i;
            else
                odd[oddCounter++]=i;
        }

        System.out.print("\nThe odd array elements are : ");
        // Prints odd element array
        for(int i=0;i<oddCounter;i++)
            System.out.print(odd[i]+" ");
        
        System.out.print("\nThe even array elements are : ");
        // Prints even element array
        for(int i=0;i<evenCounter;i++)
            System.out.print(even[i]+" ");
    }
}

Outpu:

Enter the array size : 8
Enter array elements : 1 2 3 4 5 6 7 8
The array elements are [1, 2, 3, 4, 5, 6, 7, 8]

The odd array elements are : 2 4 6 8 
The even array elements are : 1 3 5 7

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Related Java Programs: