What is an array? - ICSE Java Expert

Breaking

ICSE Java Expert

Learn Java for school

Unordered List

WELCOME

Tuesday, August 07, 2018

What is an array?


An array is a collection of elements of same data type. Array is required when we have to store a large amount of data of same type.

If we want to store age of a single student then we will use an integer variable as follows:
int age;
age=22;
System.out.println("Your age is "+age);

But what if you want to store age of 100 students. You would not like to create 100 integer variables because creating 100 variables and remembering their names while manipulating them will be a tedious job. So in order to overcome this situation Array was introduced in programming.

Syntax:
datatype name[] = new datatype[size];

Example: 
Declare an integer array named as age that can store 100 values.
int age[] = new int[100];

Question:
Write a Java program to input age of 100 students and display them.

Answer:
import java.util.*;
class test
{
 public static void main()
 {
    Scanner sc=new Scanner(System.in);
    int ar[]=new int[100];
    int sum=0;
    System.out.println("Enter elements of the array: ");
    for(int i=0;i<ar.length;i++)
    {
        ar[i]=sc.nextInt();
        sum=sum+ar[i];
    }
    System.out.println("The sum of all 100 elements of the array : "+sum);
 }
}

No comments:

Post a Comment