Java Programming | Introduction to arrays

Introduction

This is a tutorial for using arrays in java. The program is given below that takes numbers from user and save the numbers in arrays and prints them. The program is extendable. Go enjoy the program. Lets begin…….

What are arrays?

A array is collection of variables of same type i.e int,char,float (whatever is your requirement). The array is declared by :- <data type> <name>[] = new <name>[<number of arrays>]; i.e  int a[] = new a[10];

The advantage of array is that it helps the program. The programmer does not have to think of new names of variables every time and remember those names for further programming

Program for using arrays in java.

//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class Array {
	//void main
		public static void main (String[] args)
		{
			//declare int
			int i,a[] = new int[10];

			//Declare input as scanner
			Scanner input = new Scanner(System.in);

			//Take input for arrays
			for(i=0;i<5;i++)
			{
			 System.out.println("Enter Number :");
			 a[i] = input.nextInt();
			}

			System.out.println("Numbers in Arrays :-");
			//print the arrays
			for(i=0;i<5;i++)
			System.out.println(a[i]);
		}
}

Output

Enter Number :
1
Enter Number :
2
Enter Number :
3
Enter Number :
4
Enter Number :
5
Numbers in Arrays :-
1
2
3
4
5

How does it work

  1. You enter the number.
  2. The number is saved in respective array.
  3. The numbers are printed.

Extending it

The program can be extended by using char in place of int. This is basics of java programming and can be used in any program where big number of data is to be stored.

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Declare input as Scanner.
  5. Add a for loop
  6. Add system.out.println() function with the message to enter number.
  7. Take the inputs and save it in variables.
  8. Add one more loop.
  9. Add system.out.println() function to print number from array.

At the end.

You learnt creating the Java program for Introduction to arrays. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s