How to Print Arrays in Java | Java Program to Accept and Print Array Elements

In this article we are going to learn how to accept and print array elements in Java. 

How to print arrays in java: 

To print array elements we first need to accept it from user. In this post we will learn how to accept array elements from user dynamically and print it on the output screen. Simple java program to insert elements in array. 


How to print arrays in java


We can print array elements using any type of loop like :

  • for loop (we can also use for-each loop)
  • while loop
  • do-while loop


  Step by Step logic of the Given Program :


We can take array input from user using the method of the Scanner class. 

1. Accept array elements from user one by one using simple for loop:

for(int i=0;i<5;i++) {
	a[i]=sc.nextInt();		
}
2. Print Elements using for loop in this program i used Enhanced for loop to print array elements:
for(int e:a) {	
	System.out.print(e+" ");
}

but, you can also use simple for loop to print array elements like:

for(int i=0;i<5;i++) {
	System.out.print(a[i]+" ");
}


  Simple Array Program to Accept and Print Array Elements:


import java.util.Scanner;

public class SimpleArrayExample {

	public static void main(String[] args) {
		//Declaration and instantiation
		int  a[] = new int[5];
		Scanner sc = new Scanner(System.in);
		//Accepting elements using simple for loop
		System.out.println("ENTER THE ELEMENTS: ");
		for(int i=0;i<5;i++) {
			a[i]=sc.nextInt();		
		}
		System.out.println("ELEMENTS IN ARRAY ARE: ");
		//printing elements using Enhanced for loop(for-each loop)
		for(int e:a) {
			System.out.print(e+" ");
		}
	}		
}



  Same above Program using a while loop:

In the above program, we have used for loop to store and print array elements. So, In this program, we will use a while loop to store and print array elements.


import java.util.Scanner;

public class SimpleArrayExample {

	public static void main(String[] args) {
		//Declaration and instantiation
		int  a[] = new int[5];
		Scanner sc = new Scanner(System.in);
		//Accepting elements using while loop
		System.out.println("ENTER THE ELEMENTS: ");
		int i=0;
		while(i<5) {
			a[i]=sc.nextInt();
			i++;
		}
		System.out.println("ELEMENTS IN ARRAY ARE: ");
		//printing elements using while loop
		int j=0;
		while(j<5) {
			System.out.print(a[j]+" ");
			j++;
		}
	}		
}


  

 
 Output of the above program is :

ENTER THE ELEMENTS:
3
8
2
1
ELEMENTS IN ARRAY ARE: 
5 3 8 2 1



Learn more basic concepts of arrays in C array tutorial...

No comments:

Post a Comment

If you have any doubts, please discuss here...👇