elements – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sat, 26 Sep 2020 16:26:40 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg elements – Programmerbay https://programmerbay.com 32 32 Java Program to Print Elements of an Array https://programmerbay.com/java-program-to-initialize-and-print-the-elements-in-an-array/ https://programmerbay.com/java-program-to-initialize-and-print-the-elements-in-an-array/#respond Fri, 11 Jan 2019 09:51:32 +0000 https://www.programmerbay.com/?p=2336 In Java, an array is an object that is capable of storing a fixed number of elements having similar types. It uses an index in order to directly access a particular item.

There are various ways to print an array :

  1. Simply, iterating through a loop
  2.  Using Arrays class method
  3. Using advance for loop

The program initializes and prints all the elements of an array.

Print elements of an array using Loop

Program:

import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner ed=new Scanner(System.in);
int[] a=new int[5];
int i;
System.out.println("Please Enter An Array");
for(i=0;i<5;i++)
{
a[i]=ed.nextInt();
}
System.out.println("Entered Array:-");
for(i=0;i<5;i++)
{
System.out.println(a[i]);
}
} 
}

 

Output:

array initialize

Print elements of an array using Advance For loop

Program: 

import java.util.Scanner;

public class ArrayPrint {
    public static void main(String[] args) {
        Scanner ed = new Scanner(System.in);
        int[] arr = new int[5];
        int i;
        System.out.println("Please Enter An Array");
        for (i = 0; i < 5; i++) {
            arr[i] = ed.nextInt();
        }
        System.out.println("Entered Array:-");
      for(int item : arr){
          System.out.println(item);
      }
    }
}

Output: 

Please Enter An Array
32
54
32
5
67
Entered Array:-
32
54
32
5
67

Print elements of an array Using Arrays.toString()

Program:

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

public class ArrayPrint {
    public static void main(String[] args) {
        Scanner ed = new Scanner(System.in);
        int[] arr = new int[5];
        int i;
        System.out.println("Please Enter An Array");
        for (i = 0; i < 5; i++) {
            arr[i] = ed.nextInt();
        }
        System.out.println("Entered Array:-");
        System.out.println(Arrays.toString(arr));
    }
}

Output:

Please Enter An Array
45
76
43
2
45
Entered Array:-
[45, 76, 43, 2, 45]

]]>
https://programmerbay.com/java-program-to-initialize-and-print-the-elements-in-an-array/feed/ 0