0% found this document useful (0 votes)
27 views5 pages

One-Dimensional Array Declaration in C

Arrays allow storing multiple values of the same type under a single name. They have a fixed size and contain elements that are accessed via indexes. Arrays can be one, two, or multi-dimensional. Elements are added to arrays using indexes and the array size must be specified when the array is created using the new operator. The length property returns the size of the first dimension of a multi-dimensional array while the length() method returns the number of characters in a String.

Uploaded by

ameet
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views5 pages

One-Dimensional Array Declaration in C

Arrays allow storing multiple values of the same type under a single name. They have a fixed size and contain elements that are accessed via indexes. Arrays can be one, two, or multi-dimensional. Elements are added to arrays using indexes and the array size must be specified when the array is created using the new operator. The length property returns the size of the first dimension of a multi-dimensional array while the length() method returns the number of characters in a String.

Uploaded by

ameet
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Array

 Arrays are continuous memory locations having fixed size.


 Where we require storing multiple data elements under single name, there we can use
arrays.
 Arrays are homogenous in nature. It means and integer array can hold only integer
values likewise a String array will hold only String values.
 We can create array of byte, short, int, long, double, float, char, String and Object.
 Arrays cannot grow at runtime. They are fixed in size. This is the limitation of the array.
 We can create arrays of multiple dimensions.
 We can access array elements by means of index.

Array Declaration:

1. One Dimensional Array:


 One-dimensional arrays can hold values up to one dimension only.
 General form of One-Dimensional array is:
<data-type> <var-name>[ ];
 Example: int a[ ]; //This line only declares a as one-dimensional array, but it is not yet
created in ,memory.
 Size is not declared at the time of declaration.
Valid declarations are:
o int[] a;
o int []a;
o int a[];
2. Two-Dimensional Array:
 General form of two-dimensional array is:
<data-type> <var-name>[ ][ ];
 Example: int a[ ][ ];
 Valid declarations are: 0 1 2 3
o int[][] a; a
o int [][]a;
o int a[][];
o int []a[];
o int[] []a;
o int[] a[]
o int a[][]
3. Three-Dimensional array:
 General form of 3D array is:
<data-type> <var-name>[ ][ ][ ];
 Valid declarations are:
o int[][][] a;
o int a[][][];
o int [][][]a;
o int[][] []a;
o int[] [][]a;
o int[] []a[];
o int[] a[][];
o int[][] a[];
o int []a[][];
o int [][]a[];

Array Creation:
 In java, arrays are treated as object. Hence we can create array using ‘new’ operator.
 At the time of creation of array, we have to specify it’s size, else we will get compile time
error.
 E.g int[] a=new int[4]
int[] a=new int[] //this line will give compile time error
 It is legal to have size ‘0’ in java for array.
E.g int[] a=new int[0] //This is legal
 We can specify –ve size of array as well, but it will throw Runtime Exception
‘NegativeArraySizeException’.
 To specify array size, allowed data types are: byte, short, int and char. No other data
types are allowed. If we use other data types, it will throw compile time error.
 E.g. byte b=5;
int[] a= new int[b];
1. Creation of 2-Dimensional Array:
 In java, multi-dimensional arrays are not implemented as matrix; rather they are
implemented as tree structure.
 We usually call multi-dimensional arrays as ‘Array of arrays’
 Main advantage of this approach is memory optimization.
0 1 2
a Dim-1

Dim-2

 Ex. int[][] a=new int[3]


a[0]=new int[2]
a[1]=new int[2]
a[2]=new int[3]
 While creating a multi-dimensional array we have to specify size to consecutive
dimensions.
 Ex. int [][]a=new int[4][3] //Allowed
Int [][]=new int[4][] //Allowed
int [][]a=new int[][4] //Not allowed, because 1st dimension
doesn’t have size.

Adding Elements to Array


 To add elements to array we can follow the below given procedure.
1. Create Array
2. Initialize size
3. Add elements to array at separate indexes.
4. Ex. int a[]=new int[4];
a[0]=11;
a[1]=12
a[2]=13
a[3]=14

 Above method is tedious as it requires more lines of codes to add elements to array.
 A short cut to above method is:
int a[]={11,12,13,14};
 Above line will automatically create an array ‘a’ with size 4. It will contain 4 elements
mentioned in curly braces.
 Same short cut we can use for multi-dimensional arrays as well.
int a[][]={{1,2},{11,12,13},{56}}
 We can also add elements to an array by using Java loops. Below is the program to insert
elements to an array and read inserted elements iteratively.
public class ArrayDemo {
public static void main(String[] args) {
int[] a=new int[4];
Scanner sc=new Scanner([Link]);
for (int i = 0; i < [Link]; i++) {
[Link]("Enter a number:>> ");
a[i]=[Link]();
}

for (int i = 0; i < [Link]; i++) {


[Link](a[i]);
} } }

length() vs length:
1. length:
 It is a final variable applicable only for arrays only.
 It gives size of array.
 Ex. int a[]=new int[5];
[Link]([Link]); // This will print 5
2. length():
 length() is the final method applicable only for String objects.
 It returns number of characters in a String.
 Its return type is int.
 Ex. String s=”Testing Shastra”;
[Link]([Link]()); //This will print 15.
Please note: number of characters in above string are 14, still it prints 15 because it considers a
space as character.
 In multi-dimensional arrays, length will return size of first dimension only.
 Ex. int a[][]=new int[7][8]
[Link]([Link]) //This will print 7.
[Link](a[0].length) //This will print 8
Quiz

1. Which of the following is a valid declaration of array?


a. int[] a,b;
b. int[] a[],b;
c. int[] []a,b;
d. int[] []a,[]b;
2. Which of the following are invalid declarations of array? You can select multiple.
a. int[] a=new int[];
b. int []a=new int[3];
c. int a[3]=new int[];
d. int[] a=new int[-4]
e. int[] a=new int[5.0]
3. Which of the following declarations are valid?
a. int[] a=new int[];
b. int[][] a=new int[4][3];
c. int a[][]=new int[4][];
d. int a[][][]=new int[3][][4];
4. Which of the following is invalid?
a. int a[]=new int[5];
S.o.p([Link]());
b. int a[]=new int[5];
S.o.p([Link]);
c. String s=”Testing Shastra”;
S.o.p([Link]);
d. String s=”Testing Shastra”;
S.o.p([Link]());

Common questions

Powered by AI

Arrays are chosen for storing data in programming primarily because they offer a way to store multiple data elements under a single name. They are homogenous, meaning they can hold only one data type, like integers or strings. Additionally, arrays are stored in continuous memory locations, which helps in accessing elements efficiently using indices. However, they have some limitations, such as fixed size and inability to grow dynamically at runtime .

The 'length' variable is specific to arrays in Java and is used to get the size of the array. It is a final variable. For example, if an array is defined as int[] a = new int[5]; then a.length will return 5. On the other hand, 'length()' is a final method used with String objects to return the number of characters in a String. For example, if String s = "Testing Shastra";, then s.length() will return 15 because it counts spaces as characters .

A 'NegativeArraySizeException' occurs in Java when an attempt is made to create an array with a negative size. Array size must be non-negative because it represents the number of elements the array can hold, and specifying a negative size is invalid. For example, an expression like int[] a = new int[-4]; would trigger this exception at runtime .

In Java, when declaring multi-dimensional arrays, the size of the first dimension must be specified because memory allocation starts at the first dimension. If the size is unspecified for this dimension, the compiler does not know how much memory to allocate for the subsequent dimensions. Hence, declarations like int[][] a = new int[][4]; are not allowed, while specifying the first dimension as int[][] a = new int[4][]; is valid .

Multi-dimensional arrays optimize memory usage because they are implemented as 'arrays of arrays' rather than as traditional matrices. This approach allows memory to be allocated only for the necessary dimensions and sub-arrays, which can reduce waste. For example, sub-arrays can be of varying sizes, such as declaring int[][] a = new int[3][]; followed by different sub-array sizes a[0]=new int[2]; a[1]=new int[2]; a[2]=new int[3];. This results in memory being allocated only where it is needed rather than for an entire block .

Loops can be used to assign values to an array by iterating through each index and assigning a value from an external source, such as user input. For example, in Java, using a Scanner to read integers and assign them to an array could look like: int[] a = new int[4]; for (int i = 0; i < a.length; i++) { a[i] = scanner.nextInt(); }. The advantage of this method is that it allows for dynamic and flexible assignment of values, which can be useful when the values are not known at compile time or need to be input by the user .

In Java, one-dimensional arrays are created using a single pair of brackets and hold elements in a single line, e.g., int[] a = new int[4];. Each element is accessed by a single index. Two-dimensional arrays, however, are created using two pairs of brackets and are conceptually treated as an array of arrays. Syntax for creating a two-dimensional array is like int[][] a = new int[4][3];, where the first dimension denotes the number of rows and the second dimension denotes the number of columns. Key differences include the need to specify sizes for both dimensions in two-dimensional arrays and the nested nature of their access using two indices .

An array's length can be effectively utilized by using it as the limiting condition in loops when accessing array elements. For example, iterating through an array with for (int i = 0; i < a.length; i++) { } ensures that the accessing index 'i' remains within the bounds of the array. This practice helps prevent 'ArrayIndexOutOfBoundsException', which occurs when an attempt is made to access an index outside the array's size. Additionally, using array length for such conditions ensures flexibility, as changes in array size do not necessitate changes in the code .

Initializing arrays using the shortcut method, like int a[] = {11,12,13,14};, offers the advantage of brevity and clarity since it creates and initializes the array in one line without explicitly specifying its size. However, this method is less flexible because the size and type of elements are fixed at compile-time. It is mostly suited for small arrays where the values are known beforehand. This method cannot be used if the array needs to be initialized with dynamic data or if further processing is required before array declaration .

Declaring an array with a size specified by an improper data type will result in a compile-time error. In Java, only byte, short, int, and char types are allowed to specify the size of arrays. Using any other data type, such as float or double, will cause a compile-time error because the array's size needs to be an integral value. For example, declaring an array as int[] a = new int[5.0]; will result in a compile-time error because 5.0 is a double, not an int, which is required for array size .

You might also like