Chapter 7 - 1D Arrays
Chapter 7 - 1D Arrays
Arrays
Challenge problem
Write a program that read
marks for 5 test , calculate
average and then count
how may test above
average
Arrays
• An array is a collection of a fixed number of
elements (or “components”), all the same
data type.
• For example, an array might contain:
• Five elements, each of which is an int.
• One hundred elements, each of which is a
double.
• Seven thousand elements, each of which is a
char.
Array Dimension
Every array has a dimension.
• one-dimensional array
0 1 2 3 4
test
• two-dimensional array
0 1 2 3 4
0
test 1
2
Array declarations:
More accurate
0 1 2 3 4
test
How to declare One Dimension Array
datatype [ ] array_name; OR datatype array_name [ ];
Examples:
int test[]= new int [5];
double myArray1[]= new double [100];
char myArray2[];
myArray2 = new char [7000];
int list[ ] = new int [10];
Array Initialization During Declaration
• You can initialize an array when you declare it by listing values between curly braces.
– If no array size is given inside the square brackets, the array’s size is equal to the number of
initial values in the braces.
• Example:
0 1 2 3
sales 12.25 32.50 16.90 45.68
Array Initialization or inputting values from the user
Let consider
int list[] =new int [4];
0 1 2 3
list=20 Error
System.out.print(list) Error
You should loop (For is most used )
Write a program that do
the following:
• Declare an array to store 10 integers.
• Ask the user to enter 10 integers and
store them inside array .
• Ask the user to enter an integer x.
• Count how many x repeated in the
array.
Write a program that do
the following:
• Declare an array to store temperature
of a week.
• Ask the user to enter 7 temperature
of the week and store them inside
array .
• Calculate the average temperature
for a week
• Count how days are above average
Write a program that do
the following:
• Declare an array to store temperature
of a week.
• Ask the user to enter 7 temperature
of the week and store them inside
array .
• Calculate the average temperature
for a week
• Count how days are above average
Arrays as Parameters to Functions
Example name 0 1 2
ALI NOORA MARIAM
height 0 1 2
169 158 201
weight 0 1 2
65.5 67.1 91.3