Arrays_part1
Arrays_part1
Part 1
COMP102 Prog. Fundamentals I:
Arrays / Slide 2
1. Array creation
2. Performing different functions on Arrays
3. Searching 1D arrays
4. Sorting 1D arrays
5. 2D arrays(Basic operations)
COMP102 Prog. Fundamentals I:
Arrays / Slide 3
Arrays
Base type
Index
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- -- -- -- -- -- -- --
Ar
4
COMP102 Prog. Fundamentals I:
Arrays / Slide 7
Initial value
Array Declaration
● Syntax:
<type> <arrayName>=new <type> [<array_size>]
Ex. int Ar[]=new int[10];(or)
int []Ar=new int[10];
● The array elements are all values of the type <type>.
● The size of the array is indicated by <array_size>, the
number of elements in the array.
● <array_size> must be an int constant or a constant
expression. Note that an array can have multiple
dimensions.
COMP102 Prog. Fundamentals I:
Arrays / Slide 12
Subscripting
● Declare an array of 10 integers:
int Ar[10]; // array of 10 ints
● To access an individual element we must apply a subscript to array
named Ar.
● A subscript is a bracketed expression.
– The expression in the brackets is known as the index.
● First element of array has index 0.Ar[0]
● Second element of array has index 1, and so on.
Ar[1], Ar[2], Ar[3],…
● Last element has an index one less than the size of the array.
Ar[9]
● Incorrect indexing is a common error.
COMP102 Prog. Fundamentals I:
Arrays / Slide 13
Subscripting
// array of 10 uninitialized ints
int Ar[10];
--
Ar[3] = 1;
int x = Ar[3]; 1 --
-- -- --
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- 1 -- -- -- -- -- --
Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8] Ar[9]
COMP102 Prog. Fundamentals I:
Arrays / Slide 14
import java.util.*;
class arr1
{
void main()
{ int i;
int m[]={1,2,3,4,5};
for(i=0;i<5;i++)
{
System.out.println(m[i]);
}
}
}
COMP102 Prog. Fundamentals I:
Arrays / Slide 16
Java program
. To declare a array of char data type
. Print its elements using for loop
. Print the length of array
COMP102 Prog. Fundamentals I:
Arrays / Slide 17
import java.util.*;
class arr2
{ void main()
{ int i,len;
char m[]={'c','o','m','p','u','t','e','r'};
for(i=0;i<8;i++)
{
System.out.println(m[i]);
//to print all elements in an array using for loop
}
len=m.length; //print length of array
System.out.println("Length of the array is"+len);
}
}
COMP102 Prog. Fundamentals I:
Arrays / Slide 18
Java program
. To declare a array of String data type
. Print its elements using for loop and length
function
COMP102 Prog. Fundamentals I:
Arrays / Slide 19
import java.util.*;
class strarr
{
void arr()
{ int i,len;
String m[]={"student1","student2","student3"};
len=m.length;
System.out.println("Length of the array is"+len);
System.out.println("list of students are:");
for(i=0;i<len;i++)
{
System.out.println(m[i]); //To print all elements in an array using for loop
} //end of for
} // end of arr
} //end of arr