Professional Documents
Culture Documents
An array of 10 elements.
roll[10] ELEMENT
NAME
1 Roll[0]
2 Roll[1]
3 Roll[2]
4 Roll[3]
5 Roll[4]
6 Roll[5]
Roll[6] SUBSCRIPT/IND
7
EX
8 Roll[7]
9 Roll[8]
10 Roll[9]
}
}
Using an array initialiser
}
Using Method Argument in BLUEJ
Using scanner class
Out of bound indices
1.Single dimensional array or 1-D array.:- When the elements of an array are
specified using single index (one column and multiple rows)
In a single dimensional array , the elements are stored in contiguous memory
locations in order of their index.
2.Multidimensional array :- Multiple rows and columns
1 [0][0] 2 [0][1] 3 [0][2]
4 [1][0] 5 [1][1] 6 [1][2]
Position of elements
1 2 3 4 5
99 25 45 52 60
0 1 1 3 4
list[0] list[1] list[2] list[3] list[4]
Subscript / index
Output:-
The element
found in (3+1)
4th location
import java.io.*;
import java.util.Scanner;
public class linear
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int searchno;
int found=0;
int list[]={99,25,45,52,60};//creating and initializing array with value
System.out.println("Enter the no to be search:");
searchno=sc.nextInt();
int len1=list.length;
for(int i=0;i<len1;i++) // searching start from ist location till end or till search no found
{
if(list[i]==searchno) // searching
{
found=i;
break;
}
}
if(found !=0) // checking
{
System.out.println(" The element found in :"+(found+1)+ "location");
}
else
{
System.out.println(" The element not found ");
}
}// main end
}// class end
INPUT :- Enter the no to be search:52
0 1 2 3 4 5 6 7
65 47 70 9 37 72 45 17
Unsorted array with indices
1.Ist the element in 0 and 1 index position are compared. There positions are
swapped if the element at 0th index is greater than the element at the ist index.
Since 65> 47 a swap occurs.
1 2 3 4 5 6 7
0
65 47 70 9 37 72 45 17
2.Now , the elements at the ist and 2nd index are compared. Since 65 < 70
no swap occurs.
0 1 2 3 4 5 6 7
47 65 70 9 37 72 45 17
3.he elements at the 2nd and 3rd index are compared . Since 70>9 , a swap occurs
. SWAP
0 1 2 3 4 5 6 7
47 65 70 9 37 72 45 17
4. The elements at the 3rd and the 4th index are compared.
0 2 3 4 5 6 7
47 65 9 70 37 72 45 17
70>37, yes so swap occurs
5. The elements at the 4th and the 5th index are compared. Since
70<72 no swap occurs
0 1 2 3 4 5 6 7
47 65 9 37 70 72 45 17
6.The elements at the 5th and the 6th index are compared .
Since 72>45 , a swap occurs
0 1 2 3 4 5 6 7
47 65 9 37 70 72 45 17
7. The elements at the 6th and 7th index are compared. Since 72> 17 , a swap occurs
0 1 2 3 4 5 6 7
47 65 9 37 70 45 72 17
8. This results in a list with the highest element in the last position
0 1 2 3 4 5 6 7
47 65 9 37 70 45 17 72