Java Program to Generate 30 Terms of Fibonacci number in an Array

Java Program to Generate 30 Terms of Fibonacci number in an Array

In the previous article, we have seen Java Program to Check if Array is Empty

In this article we are going to see how to generate 30 terms of Fibonacci number in an Array using Java programming language.

Java Program to Generate 30 Terms of Fibonacci number in 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 generate 30 terms of Fibonacci number in an Array.

Method-1: Java Program to Generate 30 Terms of Fibonacci number in an Array By Using Iterative Method

Approach:

  1. Initialize the array of size 30.
  2. Initialize first two value to 1.
  3. Loop through the array.
  4. Assign the next value to the sum of the previous two values.
  5. Print the array.

Program:

public class Main
{
    public static void main(String[] args) 
    {
        // initialize array of size 30
        long[] fibonacci = new long[30];
        // initialize first two values  to 1
        fibonacci[0] = 1;
        fibonacci[1] = 1;
        // loop through the array
        for (int i = 2; i < fibonacci.length; i++) 
        {
            // assign the next value to the sum of the previous two values
            fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
        }
        System.out.print("The fibonacci Series = ");
        for(long i: fibonacci) 
        {
            System.out.print(i + " ");
        }

    }

}
Output:

The fibonacci Series = 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040

Method-2: Java Program to Generate 30 Terms of Fibonacci number in an Array By Using Recursive method

Approach:

  1. Initialize the array of size 30.
  2. Initialize first two values to 1.
  3. Run a for loop from i= 2->29.
  4. Call the generate30Fibonacci() user defined method for each value of i and update that value at the ith index of the array.

Program:

public class Main 
{
    public static void main(String[] args) 
    {
        int[] fibonacci = new int[30];
        fibonacci[0] = 0;
        fibonacci[1] = 1;
        for (int i = 2; i < fibonacci.length; i++) 
        {
            fibonacci[i] = generate30FibonacciNumbers(i);
        }
        System.out.println("The fibonacci series = ");
        for (int i : fibonacci) {
            System.out.print(i + " ");
        }
    }

    static int generate30FibonacciNumbers(int n) 
    {
        if (n <= 1)
            return n;
        return generate30FibonacciNumbers(n - 1) + generate30FibonacciNumbers(n - 2);
    }

}
Output:

The fibonacci series = 
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229

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 Divide an Arrays in Two Arrays

Java Program to Divide an Arrays in Two Arrays

In the previous article, we have seen Java Program to Copy an Array in Reverse

In this article we are going to see how we can divide an array into two subarrays in JAVA.

Java Program to Divide an Arrays in Two Arrays

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 divide an array into two subarrays.

Method-1: Java Program to Divide an Arrays in Two Arrays by Find Mid Index and By Copying Elements Individually

Approach:

  • Create an array.
  • Display the array to the user.
  • Find the mid index of the array
  • Create two subarrays. In the first sub array set size to mid, and for the second subtract the size of the first sub array from the size of the main array.
  • Use a for loop to copy elements into the subarrays.
  • Print both the sub arrays.

Program:

import java.util.Arrays;
import java.util.Collections;
public class Main
{
    public static void main(String args[])
    {
        //Original array
        int arr[] = {12, 22, 34, 22, 54};
        // Printing the array
        System.out.println("The array elements are : "+Arrays.toString(arr));
        int len = arr.length;
        // Creating the subarrays
        int subArr1[] = new int[(len+1)/2];
        int subArr2[] = new int[len-subArr1.length];

        // Copying elements to sub arrays individually
        for (int i = 0; i < len; i++)
        {
            if (i < subArr1.length) {
                subArr1[i] = arr[i];
            }
            else {
                subArr2[i - subArr1.length] = arr[i];
            }
        }
        // Printing the sub arrays
        System.out.println("The sub array 1 elements are : "+Arrays.toString(subArr1));
        System.out.println("The sub array 2 elements are : "+Arrays.toString(subArr2));
    }
}
Output:

The array elements are : [12, 22, 34, 22, 54]
The sub array 1 elements are : [12, 22, 34]
The sub array 2 elements are : [22, 54]

Method-2: Java Program to Divide an Arrays in Two Arrays by Find Mid Index and By Using System.arraycopy() Method

Approach:

  • Create an array.
  • Display the array to the user.
  • Find the mid index of the array
  • Create two subarrays. In the first sub array set size to mid, and for the second subtract the size of the first sub array from the size of the main array.
  • Use System.arraycopy to copy the elements.
  • Print both the sub arrays.

Program:

import java.util.*;
public class Main
{
    public static void main(String args[])
    {
        //Original array
        int arr[] = {12, 22, 34, 22, 54};
        // Printing the array
        System.out.println("The array elements are : "+Arrays.toString(arr));
        int len = arr.length;
        // Creating the subarrays
        int subArr1[] = new int[(len+1)/2];
        int subArr2[] = new int[len-subArr1.length];

        // Copying elements to sub arrays
        System.arraycopy(arr, 0, subArr1, 0, subArr1.length);
        System.arraycopy(arr, subArr1.length, subArr2, 0, subArr2.length);
        // Printing the sub arrays
        System.out.println("The sub array 1 elements are : "+Arrays.toString(subArr1));
        System.out.println("The sub array 2 elements are : "+Arrays.toString(subArr2));
    }
}

Output:

The array elements are : [12, 22, 34, 22, 54]
The sub array 1 elements are : [12, 22, 34]
The sub array 2 elements are : [22, 54]

Method-3: Java Program to Divide an Arrays in Two Arrays by Find Mid Index and By Uing copyOfRange() Method

Approach:

  • Create an array.
  • Display the array to the user.
  • Find the mid index of the array
  • Create two subarrays. In the first sub array set size to mid, and for the second subtract the size of the first sub array from the size of the main array.
  • Use Arrays.copyOfRange() to copy the elements.
  • Print both the sub arrays.

Program:

import java.util.*;
public class Main
{
    public static void main(String args[])
    {
        //Original array
        int arr[] = {12, 22, 34, 22, 54};
        // Printing the array
        System.out.println("The array elements are : "+Arrays.toString(arr));
        int len = arr.length;
        // Creating the subarrays and copying elements
        int subArr1[] = Arrays.copyOfRange(arr,0,(len+1)/2);
        int subArr2[] = Arrays.copyOfRange(arr,(len+1)/2,len);

        // Printing the sub arrays
        System.out.println("The sub array 1 elements are : "+Arrays.toString(subArr1));
        System.out.println("The sub array 2 elements are : "+Arrays.toString(subArr2));
    }
}

Output:

The array elements are : [12, 22, 34, 22, 54]
The sub array 1 elements are : [12, 22, 34]
The sub array 2 elements are : [22, 54]

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Related Java Programs:

Java Program to Copy an Array in Reverse

Java Program to Copy an Array in Reverse

In the previous article, we have seen Java Program to Copy an Array to Another Array

In this article we are going to see how we can copy an array in reverse.

Java Program to Copy an Array in Reverse

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 copy an array in reverse.

Method-1: Java Program to Copy an Array in Reverse By Static Initialization of Array Elements

Approach:

  • Create and initialize an array.
  • Display the array to the user.
  • Copy each element from the last location to the first location and store it in our copied array.
  • Display the copied array.

Program:

import java.util.Arrays;
import java.util.Collections;
public class Main
{
    public static void main(String args[])
    {
        //Original array
        int arr[] = {12, 22, 34, 22, 54};
        int copyarr[] = new int[arr.length];
        // Printing the array
        System.out.println("The array elements are : "+Arrays.toString(arr));
        // Copying each element from the array
        for(int i = 0;i<arr.length;i++)
            copyarr[i] = arr[arr.length-i-1];
        System.out.println("The copied array elements are : "+Arrays.toString(copyarr));
    }
}

Output:

The array elements are : [12, 22, 34, 22, 54]
The copied array elements are : [54, 22, 34, 22, 12]

Method-2: Java Program to Copy an Array in Reverse By Dynamic Initialization of Array Elements

Approach:

  • Create and initialize an array.
  • Display the array to the user.
  • Copy each element from the last location to the first location and store it in our copied array.
  • Display the copied array.

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 copyarr[] = new int[arr.length];
        // Printing the array
        System.out.println("The array elements are : "+Arrays.toString(arr));
        // Copying each element from the array
        for(int i = 0;i<arr.length;i++)
            copyarr[i] = arr[arr.length-i-1];
        System.out.println("The copied array elements are : "+Arrays.toString(copyarr));
    }
}

Output:

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

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Related Java Programs:

Java Program to Find Line Passing Through 2 Points

Java Program to Find Line Passing Through 2 Points

In the previous article, we have seen Java Program to Check if Three Points are Collinear

In this article we will discuss about how to find line passing through 2 points  using Java programming language.

Java Program to Find Line Passing Through 2 Points

Before jumping into the program directly, let’s first know how we can find line passing through 2 points.

Explanation:

Lets assume we have two point (x1,y1) and (x2,y2) .now we can find equation of the line by

x1x + y1y = c1

x2x + y2y = c2

Let’s see different ways to find line passing through 2 points.

Method-1: Java Program to Find Line Passing Through 2 Points By Using Static Value

Approach :

  • Initialize and declare the point x1,x2.
  • Find out the equation of the line
  • Print it .

Program :

class Main
{
   
     // Driver method
    public static void main(String args[])
    {
        IntsPoint x1 = new IntsPoint(3, 2);
        IntsPoint x2 = new IntsPoint(2, 6);
        lines_pts(x1,x2);
    }
    
     static class IntsPoint
    {
        int a,b;
        public IntsPoint(int a, int b) 
            {
                this.a = a;
                this.b = b;
            }
    }
    //find the line passing through 2 points by using equation
   static void lines_pts(IntsPoint x1, IntsPoint x2)
    {
        int x = x2.b - x1.b;
        int y = x1.a - x2.a;
        int z = x * (x1.a) + y * (x1.b);
        if (y < 0)
            System.out.println("The line passing through points x1 and x2 is: " + x + "x - " + y + "y = " + z);
        else 
            System.out.println("The line passing through points x1 and x2 is: " + x + "x + " + y + "y = " + z);
    }
}
Output:

The line passing through points x1 and x2 is: 4x + 1y = 14

Method-2: Java Program to Find Line Passing Through 2 Points By Using Dynamic Value

Approach :

  • Take input of point x1,x2.
  • Find out the equation of the line
  • Print it .

Program :

import java.util.*;
class Main
{
     // Driver method
    public static void main(String args[])
    {
        Scanner s = new Scanner(System.in);
        int l ,m ;
        //taking input of point values
        System.out.println("Enter values of point 1: ");
        l=s.nextInt();
        m=s.nextInt();
        IntsPoint x1 = new IntsPoint(l, m);
        System.out.println("Enter values of point 2: ");
        l=s.nextInt();
        m=s.nextInt();
        IntsPoint x2 = new IntsPoint(l, m);
        lines_pts(x1,x2);
    }
    static class IntsPoint
    {
        int a,b;
        public IntsPoint(int a, int b) 
            {
                this.a = a;
                this.b = b;
            }
    }
    
   //find the line passing through 2 points by using equation
   static void lines_pts(IntsPoint x1, IntsPoint x2)
    {
        int x = x2.b - x1.b;
        int y = x1.a - x2.a;
        int z = x * (x1.a) + y * (x1.b);
        if (y < 0)
            System.out.println("The line passing through points x1 and x2 is: " + x + "x - " + y + "y = " + z);
        else 
            System.out.println("The line passing through points x1 and x2 is: " + x + "x + " + y + "y = " + z);
    }
}
Output:

Enter values of point 1: 
3
2
Enter values of point 2: 
2
4
The line passing through points x1 and x2 is: 2x + 1y = 8

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Related Java Programs:

Java Program to Increment Each Element of Array by 1 and Print the Incremented Array

Java Program to Increment Each Element of Array by 1 and Print the Incremented Array

In the previous article, we have seen Java Program to Sort String Elements in an Alphabetical Order

In this article we are going to see how increment array element by one using Java programming language.

Java Program to Increment Each Element of Array by 1 and Print the Incremented 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 increment each element of array by 1 and print the incremented array.

Method-1: Java Program to Increment Each Element of Array by 1 and Print the Incremented Array By Static Initialization of Array Elements

Approach:

  • Declare and initialize an array.
  • Iterate over the array.
  • Increment each element by one.
  • Print the array.

Program:

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

public class Main
{
    public static void main(String[] args) 
    {
        int arr[]={10,20,30,40,50};
        System.out.println("Original array: " + Arrays.toString(arr));
        IncrementByOne(arr);
    }

    private static void IncrementByOne(int[] arr) 
    {
        for (int i = 0; i < arr.length; i++) 
        {
            arr[i]++;
        }
        System.out.println("Incremented array: " + Arrays.toString(arr));
    }

}
Output:

Original array: [10, 20, 30, 40, 50]
Incremented array: [11, 21, 31, 41, 51]

Method-2: Java Program to Increment Each Element of Array by 1 and Print the Incremented Array By Dynamic Initialization of Array Elements

Approach:

  • Take the array size from user.
  • Take input of array elements as user input.
  • Iterate over the array.
  • Increment each element by one.
  • Print the array.

Program:

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

public class Main
{
    public static void main(String[] args) 
    {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of array: ");
        int n = sc.nextInt();
        // initialize array with size n
        int[] arr = new int[n];
        // take input from user for array elements
        System.out.print("Enter array elements: ");
        for (int i = 0; i < n; i++) 
        {
            arr[i] = sc.nextInt();
        }
        System.out.println("Original array: " + Arrays.toString(arr));
        IncrementByOne(arr);
    }

    private static void IncrementByOne(int[] arr) 
    {
        for (int i = 0; i < arr.length; i++) 
        {
            arr[i]++;
        }
        System.out.println("Incremented array: " + Arrays.toString(arr));
    }

}
Output:

Enter the size of array: 5
Enter array elements: 10 20 30 40 50
Original array: [10, 20, 30, 40, 50]
Incremented array: [11, 21, 31, 41, 51]

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Related Java Programs:

Java Program to Decrement Each Element of Array by a Specified Number

Java Program to Decrement Each Element of Array by a Specified Number

In the previous article, we have seen Java Program to Decrement Each Element of Array by 1 and Print the Decremented Array

In this article we are going to see how decrement array element by a specified number using Java programming language.

Java Program to Decrement Each Element of Array by a Specified Number and Print the Decremented 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 decrement each element of array by a specified number and print the incremented array.

Method-1: Java Program to Decrement Each Element of Array by 1 and Print the Decremented Array By Static Initialization of Array Elements

Approach:

  • Declare and initialize an array.
  • Iterate over the array.
  • Decrement each element by a specified number.
  • Print the array.

Program:

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

public class Main
{
    public static void main(String[] args) 
    {
        int arr[]={10,20,30,40,50};
        int n=5;
        System.out.println("Original array: " + Arrays.toString(arr));
        Decrement(arr,n);
    }

    private static void Decrement(int[] arr, int n) 
    {
        for (int i=0; i<arr.length; i++) 
        {
            arr[i]=arr[i]-n;
        }
        System.out.println("Decremented array: " + Arrays.toString(arr));
    }

}
Output:

Original array: [10, 20, 30, 40, 50]
Decremented array: [5, 15, 25, 35, 45]

Method-2: Java Program to Decrement Each Element of Array by a Specified Number and Print the Decremented Array By Dynamic Initialization of Array Elements

Approach:

  • Take the array size from user.
  • Take input of array elements as user input.
  • Iterate over the array.
  • Decrement each element by a specified number.
  • Print the array.

Program:

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

public class Main
{
    public static void main(String[] args) 
    {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of array: ");
        int n = sc.nextInt();
        // initialize array with size n
        int[] arr = new int[n];
        // take input from user for array elements
        System.out.print("Enter array elements: ");
        for (int i = 0; i < n; i++) 
        {
            arr[i] = sc.nextInt();
        }
        // take input from user for array size 
        System.out.print("Enter the specified number : "); 
        int num = sc.nextInt();
        System.out.println("Original array: " + Arrays.toString(arr));
        Decrement(arr,num);
    }

    private static void Decrement(int[] arr,int num) 
    {
        for (int i = 0; i < arr.length; i++) 
        {
            arr[i]=arr[i]-num;
        }
        System.out.println("Decremented array: " + Arrays.toString(arr));
    }

}
Output:

Enter the size of array: 5
Enter array elements: 10 20 30 40 50
Enter the specified number : 5
Original array: [10, 20, 30, 40, 50]
Decremented array: [5, 15, 25, 35, 45]

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Related Java Programs:

Java Program to Increment Each Element of Array by a Specified Number

Java Program to Increment Each Element of Array by a Specified Number

In the previous article, we have seen Java Program to Decrement Each Element of Array by a Specified Number

In this article we are going to see how increment array element by a specified number using Java programming language.

Java Program to Increment Each Element of Array by 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 increment each element of array by a  specified number and print the incremented array.

Method-1: Java Program to Increment Each Element of Array by a Specified Number and Print the Incremented Array By Static Initialization of Array Elements

Approach:

  • Declare and initialize an array.
  • Iterate over the array.
  • Increment each element by a specified number.
  • Print the array.

Program:

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

public class Main
{
    public static void main(String[] args) 
    {
        int arr[]={10,20,30,40,50};
        int n=5;
        System.out.println("Original array: " + Arrays.toString(arr));
        Increment(arr,n);
    }

    private static void Increment(int[] arr, int n) 
    {
        for (int i = 0; i < arr.length; i++) 
        {
            arr[i]=arr[i]+n;
        }
        System.out.println("Incremented array: " + Arrays.toString(arr));
    }

}
Output:

Original array: [10, 20, 30, 40, 50]
Incremented array: [15, 25, 35, 45, 55]

Method-2: Java Program to Increment Each Element of Array by a Specified Number and Print the Incremented Array By Dynamic Initialization of Array Elements

Approach:

  • Take the array size from user.
  • Take input of array elements as user input.
  • Iterate over the array.
  • Increment each element by a specified number.
  • Print the array.

Program:

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

public class Main
{
    public static void main(String[] args) 
    {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of array: ");
        int n = sc.nextInt();
        // initialize array with size n
        int[] arr = new int[n];
        // take input from user for array elements
        System.out.print("Enter array elements: ");
        for (int i = 0; i < n; i++) 
        {
            arr[i] = sc.nextInt();
        }
        System.out.print("Enter the specified number: ");
        int num=sc.nextInt();
        System.out.println("Original array: " + Arrays.toString(arr));
        Increment(arr,num);
    }

    private static void Increment(int[] arr,int num) 
    {
        for (int i = 0; i < arr.length; i++) 
        {
            arr[i]=arr[i]+num;
        }
        System.out.println("Incremented array: " + Arrays.toString(arr));
    }

}
Output:

Enter the size of array: 5
Enter array elements: 10 20 30 40 50
Original array: [10, 20, 30, 40, 50]
Incremented array: [15, 25, 35, 45, 55]

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Related Java Programs:

Java Program to Multiply an Element to Every Element of the Array

Java Program to Multiply an Element to Every Other Elements of the Array

In the previous article, we have seen Java Program to Print nth Element of the Array

In this article we are going to see how we can multiply an element to every other elements of the array except itself by using Java Language.

Java Program to Multiply an Element to Every Element of the 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 multiply an element to every other elements of the array except itself.

Method-1: Java Program to Multiply an Element to Every Element of the Array By Static Initialization of Array Elements

Approach:

  • Declare and initialize an array.
  • Enter the index of array element to find that specific element.
  • This array element  will be multiplied with other array elements.
  •  Iterate each element of the array and multiply that specific array element with others elements except self.

Program:

public class Main
{

    public static void main(String[] args) 
    {
        //array initialized
        int arr[] = {10,20,30,40,50,60};
        // creating new array with size of actual array 
        int result[]= new int[arr.length];
        
        System.out.println("Array length is : "+arr.length);
        
        //declaring array index of the specified number 
        //which will be multiplied withother array elelments
        int num  = 2;
        
        //if the entered index(means specified number) exists in the array 
        //then only the specified array element can be multiplied with other array elements 
        if(num<arr.length)
        {
            //iterating the array
           for(int i=0;i<arr.length;i++)
           {
               // checking condition 
               // if array element is not the specified number 
               // then it will enter into the if block 
               // and the number will be multiplied with other elements except itself 
               if(arr[i]!=arr[num])
               {
                    // multiplying the specified array element with other array elements
                    result[i] = arr[i]*arr[num];
               }
           }
        }
        
        //assigning the specified number to the same index of result array
        //as the specified number will be same 
        result[num]=arr[num];
        
        //printing the result array after multiplication
        System.out.println("New array after multiplication of array with a specific array element : ");
        for(int i=0;i<result.length;i++)
        {
            System.out.print(result[i]+" ");
        }    
   }
}
Output:

Array length is : 6
New array after multiplication of array with a specific array element : 
300 600 30 1200 1500 1800

Method-2: Java Program to Multiply an Element to Every Element of the Array By Dynamic Initialization of Array Elements

Approach:

  • Take the array size as user input.
  • Then take array elements as user input.
  • Enter the index of array element to find that specific element.
  • This array element  will be multiplied with other array elements.
  • Iterate each element of the array and multiply that specific array element with others elements except self.

Program:

import java.util.Scanner;

public class Main
{

    public static void main(String[] args) 
    {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of array: ");
        int n = sc.nextInt();
        
        // initialize array with size n
        int arr[] = new int[n];
        // creating new array with size of actual array 
        int result[]= new int[arr.length];
        
        // take input from user for array elements
        System.out.print("Enter array elements: ");
        for (int i = 0; i < n; i++) 
        {
            arr[i] = sc.nextInt();
        }
        
        System.out.println("Array length is : "+arr.length);
        
        //talking input of array index
        System.out.print("Enter index of the element to be multiplied : ");
        int num  = sc.nextInt();
        
        //if the entered index(means specified number) exists in the array 
        //then only the specified array element can be multiplied with other array elements 
        if(num<arr.length)
        {
            //iterating the array
           for(int i=0;i<arr.length;i++)
           {
               // checking condition 
               // if array element is not the specified number 
               // then it will enter into the if block 
               // and the number will be multiplied with other elements except itself 
               if(arr[i]!=arr[num])
               {
                    // multiplying the speciifed array element with other array elements
                    result[i] = arr[i]*arr[num];
               }
           }
        }
        
        //assigning the specified number to the same index of result array
        //as the specified number will be same 
        result[num]=arr[num];
        
        //printing the result array after multiplication
        System.out.println("New array after multiplication of array with a specific array element : ");
        for(int i=0;i<result.length;i++)
        {
            System.out.print(result[i]+" ");
        }    
   }
}
Output:

'Enter the size of array: 5
Enter array elements: 1 2 3 4 5
Array length is : 5
Enter index of the element to be multiplied : 2 
New array after multiplication of array with a specific array element : 
3 6 3 12 15

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language.

Related Java Programs:

Java Program for Basic Input and Output

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

Java program to take input from user using scanner class: In this Java program, we will learn about taking an integer, character, float and string input from user using Scanner class and then printing integer, character, float and string on screen using System.out.format method.

Java Program for Basic Input and Output

To perform any input operation using Scanner in a java program, we have to first import Scanner class as :

import java.util.Scanner;
Scanner class in part of java.util package, which is s widely used for taking the input of basic data types like char, int, double etc from user. It breaks the keyboard input into tokens using a specified delimiter or using whitespace as default delimiter. It provide various method to parse basic data types from input.

While creating an object of Scanner class, we initialize it with predefined standard input stream System.in as

Scanner scanner = new Scanner(System.in);

Reading Integer using Scanner

To read integers, we use nextInt() method, which parses the next input token as an integer value and return it.

For Example,

int v_int;
v_int = scanner.nextInt();

Reading Character using Scanner

To read a character, we use next() method followed by charAt(0). next method returns the next input token as string as the charAt(0) returns the first character of token.

For Example,

char c;
c = scanner.next().charAt(0);

Reading String using Scanner

For reading a string, we use nextLine() method which returns a string till end of the line(newline character).

For Example,

String str;
str = scanner.nextLine();

Reading Float using Scanner

To read integers, we use nextFloat() method, which parses the next input token as an float value and return it.

For Example,

float v_float;
v_float = scanner.nextFloat();

Java Program for Taking input from user using Scanner

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to take input from user.
 */
public class TakingInput {
    public static void main(String[] args) {
        char c;
        int v_int;
        ;
        float v_float;
        String str;
 
        Scanner scanner;
        scanner = new Scanner(System.in);
        // Taking input from user
        System.out.println("Enter a String");
        str = scanner.nextLine();
 
        System.out.println("Enter a Character");
        c = scanner.next().charAt(0);
 
        System.out.println("Enter an Integer");
        v_int = scanner.nextInt();
 
        System.out.println("Enter a Float");
        v_float = scanner.nextFloat();
 
        // Printing data entered by user
        System.out.println("You Entered Following Data:");
        System.out.format("Char : %c\n", c);
        System.out.format("Integer : %d\n", v_int);
        System.out.format("Float : %f\n", v_float);
        System.out.format("String : %s", str);
    }
}

Output

Enter a Character
A
Enter an Integer
123
Enter a Float
1234.6
You Entered Following Data:
Char : A
Integer : 123
Float : 1234.599976
String : BTechGeeks

Java Program to Print Hello World

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Java Program to Print Hello World

In this java program, we have to print “Hello World” string on screen. Printing “Hello World” program is one of the simplest programs of Java programming languages. It become the traditional first program that many people write while learning a new programming language. It helps in understanding basic syntax of Java programming language and Java program structure to new programmers.

Java Program to print Hello World string on screen

In this java program, we are printing “Hello World” string using println method (System.out.println()). println method is used to print a line on screen.

package com.tcc.java.programs;
 
/**
 * Java Program to Print Hello World on Screen
 */
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Output:

Hello World

Java Program to print Hello World string 10 times using for loop

In this java program, we will print “Hello World” string 10 times using a for loop. For loop will iterate 10 times and in every iteration it prints “Hello World” string once in a separate line using System.out.println method.

package com.tcc.java.programs;
 
/**
 * Java Program to Print "Hello World" 10 times using for loop
 */
public class HelloWorldLoop {
    public static void main(String[] args) {
        int i;
        for (i = 0; i < 10; i++) {
            System.out.println("Hello World");
        }
    }
}

Output

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World