Java Program to get and print the array elements

Get array size n and n elements of array, then print the elements.

Sample Input 1:

5 5 7 9 3 1

Sample Output 1:

5 7 9 3 1

Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

public class Hello { public static void main(String args[]) { //Write your code here } }

Program or Solution

				
			
					
import java.util.*;
class Array
{
  public static void main(String args[])
  {
     int size,i;
     Scanner sc=new Scanner(System.in);
     System.out.println("Enter Size Of Array:");
     size=sc.nextInt();
     int a[]=new int[size];
     System.out.println("Enter The Array Elements:\n");
     for(i=0;i<size;i++)
        {
            a[i]=sc.nextInt();
	}
     System.out.println("The Array Elements are:");
     for(i=0;i<size;i++)
	{

	   System.out.print(" "+a[i]);

	}
	


  }
}
			
				
			

Program Explanation

Array is a Collection of data with same type.

1. Get the size of the Array

2. Create a array with the given size (Array has 0 to size-1 index to access every location)









        0                         1                        2                         3                .................             size-2                  size-1


for(i=0;i<size;i++)


Here i starts at 0, incremented by 1 at every iteration and finally iteration stops when i is equal to size.

Therefore,

In First iteration i is 0, so a[i] is a[0]

In second iteration i is 1, so a[i] is a[1]

....

In last iteration i is size-1, so a[i] is a[size-1]


the input statement nextInt() reads input and stores in array location consecutively. like a[0], a[1], a[2].....


The second For Loop

Writes the values of array consecutively to  the console using println().




Comments