Arrays - Part 1
Arrays - Part 1
PART - 1
2
MANAGING VARIABLES
MANAGING VARIABLES
TO HANDLE SUCH
SITUATIONS ALL
PROGRAMMING
LANGUAGES PROVIDE A
DATA STRUCTURE CALLED
ARRAY.
6
WHAT IS AN
ARRAY ?
UTILITY OF AN ARRAY
Primitive:
byte, short, int, long, float, double, char, boolean
DATA TYPE OF
AN ARRAY
Reference:
Objects (user –
defined)
10
TYPES OF ARRAY
Data type:
of each element Identifier:
in an array Array name
Separator:
Separator: statement
specifies name terminator
preceding it is
an array.
Data type:
of each element Identifier:
in an array Array name
Separator:
Separator: statement
specifies name terminator
preceding it is
an array.
If an array is declared as
int[] arr, j, k This means that arr, j & k are arrays of int
type.
0
Length of an array is given by arr.length
0
- this will give 8 for the given example.
0
length is a final variable associated with arrays.
0
arr[7]
“
17
READING VALUES {
INTO AN ARRAY System.out.println(“Enter a value”);
x[i] = scr.nextInt();
}
For every iteration, a value will be read into the
array.
When i = 0, value will be read into x[0]
When i = 1, value will be read into x[1]
When i = 2, value will be read into x[2]
When i = 3, value will be read into x[3]
When i = 4, last value will be read into x[4]
(assuming that values are stored in the array) 20
DISPLAYING {
VALUES OF AN
ARRAY System.out.println(“value of x[”+(i+1)+“]:
”+x[i]);
}
For every iteration, an array value is displayed.
When i = 0, 1st value will be displayed ie. x[0]
When i = 1, 2nd value will be displayed ie. x[1]
When i = 2, 3rd value will be displayed ie. x[2]
When i = 3, 4th value will be displayed ie. x[3]
When i = 4, last value will be displayed ie. x[4]
21
1. Write a program to create an array arr. Accept 10 int values into the array, display
the double of each element that is accepted.
2. Write a program to create an array x and accept 5 double values into the array.
Find the cube of each value and store it into another array y. Display both the
arrays.
3. Write a program to accept 5 values into an array arr1 and 5 values into another
array arr2. Find the sum of the corresponding values of both the arrays and store
the sum into an another array sum.
4. Write a program to accept 10 int values into an array. Copy the value of arr[0] into
arr[1], arr[1] into arr[2] and so on. The value of arr[9] should be copied to arr[0].
Display the initial and the final array.
5. Write a program to initialize a String array with 10 names. Reverse each element
and store it into another array. Display both the arrays.
6. Write a program to accept 20 int values into an array arr1. Copy only the even
numbers from the arr1 to another array arr2. Display both the arrays.
23
Thanks
!