Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views39 pages

Java Arrays for Beginners

Chapter 7 covers Java arrays, including one-dimensional and two-dimensional arrays, their declaration, initialization, and common operations such as finding the length, sum, and maximum element. It provides examples of array manipulation and introduces parallel arrays. The chapter also includes code snippets demonstrating how to read from user input and process arrays.

Uploaded by

co9m365
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)
7 views39 pages

Java Arrays for Beginners

Chapter 7 covers Java arrays, including one-dimensional and two-dimensional arrays, their declaration, initialization, and common operations such as finding the length, sum, and maximum element. It provides examples of array manipulation and introduces parallel arrays. The chapter also includes code snippets demonstrating how to read from user input and process arrays.

Uploaded by

co9m365
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
You are on page 1/ 39

Chapter 7

Java Arrays

1
What is the output
public class Main
{
public static void main(String[] args)
{
int a= 1;
int b= 2;
int c= 3;
int d= 4;
int e= 5;
int f= 6;
System.out.println(f);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
System.out.println(a);
}
} 2
Java Arrays
Normally, an array is a collection of similar type of elements, all elements
have same name, but each element has different index.

3
Java Arrays
◼ A one-dimensional array stores a
list of elements one
dimensional

4
Java Arrays
To declare an Array
<type> [ ] array_name; or <type> array_name [ ];
− int myList [ ];
− int [ ] myList;

−Both syntaxes are equivalent

Define an array as follows:

int mylist [ ] = new int [10];


Or int x=10;
int mylist [ ] = new int [x];

5
Java Arrays
Define the following arrays
Name Type Size
ID int 3 int ID [ ] = new int [3];
name String 5 String name [ ] = new String [5];
gpa double 7 double gpa [ ] = new double[7];
abc char 15 char abc [ ] = new char [15];

6
Java Arrays
To declare one dimensional array and assign
values to it in the same statement:
− int mylist [ ] = {4,2,3,1,6,5};
The size of the array is the number of elements in the array.
How many elements are there in mylist array ? 6
What are the elements of the array?
mylist[0]
mylist[1]
mylist[2] 3
mylist[3]
mylist[4]
mylist[5] 7
Examples
How to Find Array Length in Java
To find the length of any array you can use
arrayname.length
public class Main
{
Output
public static void main(String[] args)
{ 6
int mylist [] = {5,2,6,4,1,3};
int i=mylist.length;
System.out.println(i);
}}

9
Array example in Java
Write a java program to find the sum of all elements
in the array
int mylist [] = {5,2,6,4,9,15,1,13}
public class Main
{
public static void main(String[] args)
{
int mylist [] = {5,2,6,4,9,15,1,13};
int sum = 0;
for(int i = 0; i<mylist.length ; i++)
sum = sum + mylist[i];
System.out.println(“Sum = " + sum);
}}
10
Array example in Java
Write a java program to find the max element of
this array
int mylist [] = {5,2,6,4,9,15,1,13}
public class Main
{
public static void main(String[] args)
{
int mylist [] = {5,2,6,4,9,15,1,13};
int max = mylist[0];
int n = mylist.length;
for(int i = 0; i<n ; i++)
if(mylist[i]>max) max = mylist[i];
System.out.println("Max = " +max); }}
11
Parallel Arrays
Parallel Array: multiple arrays of the same size such that
i-th element of each array is related to all i-th elements in
the other arrays.

Example

12
Java Arrays

Enter number of new inventories: 4


Enter 4 inventory details (name,units,price):
Desk 3 125.5
Table 2 75.5
Chair 6 39.55
Fridge 2 236.4
Total cost for all inventories = BD 1237.6
Name New Units Unit Price Cost
Desk 3 125.5 376.5
Table 2 75.5 151.8
Chair 6 39.55 237.299999999
Fridge 2 236.4 472.8 13
import java.util.Scanner;
public class Inventory {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int Inventoryno;
System.out.print("Enter number of new inventories: ");
Inventoryno = kb.nextInt();
String name [ ]=new String[Inventoryno];
int unit [ ] = new int[Inventoryno];
double price [ ] = new double[Inventoryno];
double totalAll=0, cost;
System.out.println("Enter "+Inventoryno+ " inventory details (name,units,price):");
for(int i=0; i<Inventoryno; ++i)
{
name[i]=kb.next();
unit[i]=kb.nextInt();
price[i]=kb.nextDouble();
totalAll+=unit[i]*price[i];
}
System.out.println("Total cost for all inventories = BD "+totalAll);
System.out.println("Name\tNew Units\tUnit Price\tCost");
for(int i=0; i<numInventory; ++i)
System.out.println(name[i]+"\t\t"+unit[i]+"\t\t"+price[i]+"\t\t"+(unit[i]*price[i]);
}} 14
Java Arrays
What is the output of the following code

Output
int[] arr = {5,2,0,9,10};
for(int i=0;i<2;++i) a. 109052
arr[i]=arr[arr.length-i-1]; b. 1090510
c. 1090910
for(int i=4;i>=0;--i)
d. 52025
System.out.print(arr[i]);

15
Java Arrays
What is the output of the following code

Output
int[] x={5,3,1,7,9};
for(int i=x.length-1;i>0;i-=2) 7 3
{ 5 1 9
System.out.print(x[i]+" "); 9 1
} 9 1 5

16
Java Arrays
What is the output of the following code

int[] arr = {10, 14, 18, 5, -15, 15, 13};


System.out.println(arr[arr[4] + arr[2]]);

Output

3
13
5
18

17
Java Arrays
What is the output of the following code

int[] a = { 11, 9, 15, 12, 1, 3, 15, 1, 4, 8 };


for (int i = 0; i < a.length; i++)
{
if (a[i] > 2) continue;
System.out.print(a[i] + 1);
}
Output
1
22
0
119
18
SAMPLE INPUT/OUTPUT
Enter the number of packages: 5
Enter package code and number of bookings:
UK01 6
UK02 10
TUR1 100
TUR2 150
FRA1 30
Total bookings: 296
Code Booking# %of total Popularity
UK01 6 2.027027027027827 Less Popular
UK82 10 3.3783783783783785 Less Popular
TUR1 100 33.78378378378378 Highly Popular
TUR2 150 58.67567567567568 Highly Popular
19
FRA1 38 18.135135135135135 Moderately Popular
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int numPackages;
System.out.print("Enter the number of packages: ");
numPackages = kb.nextInt();
String[] packageCodes = new String[numPackages];
int[] bookings = new int[numPackages];
double percentage;
String popularity;
int totalBookings = 0;
System.out.println("Enter package code & number of bookings: ");
for(int i=0; i<numPackages ; i++)
{ packageCodes[i] = kb.next();
bookings[i] = kb.nextInt();
totalBookings += bookings[i]; }
System.out.println("\nTotal bookings: " + totalBookings);
System.out.println("\nCode\tBooking#\t% of total\tPopularity");
for (int i = 0; i < numPackages; i++)
{
percentage = (bookings[i] / (double) totalBookings) * 100;
if (percentage < 5)
popularity = "Less Popular";
else if (percentage < 20)
popularity = "Moderately Popular";
else
popularity = "Highly Popular";
System.out.println(packageCodes[i]+"\t"+ bookings[i]+"\t"+ percentage +"\t"+ popularity); }
}} 20
Arrays in Java

◼ A two-dimensional array can be


thought of as a table of
elements, with rows and columns

21
Java Arrays
Declaring an Array Variable
<type> [ ] [ ] variable_name;
− int myList [ ] [ ];
− int [ ] [ ] myList;
⚫ Both syntaxes are equivalent
⚫ No memory allocation at this point

Declaring and defining in the same statement:


<type> arraye_name[ ]=new <type>[rows][column];
int mylist [ ] [ ] = new int [10] [5];
Or int x=10;
int y=5;
int mylist [ ][ ] = new int [x] [y];

22
Java two-dimension Arrays
Declaring defining and assign values in the same statement:
− int mylist [ ] [ ] = {{1,2,3,4,5} , { 6, 7,8,9,10}};

0 1 2 3 4
0
1

public class Main {


public static void main(String[] args)
{
int mylist [ ] [ ] = {{1,2,3,4,5} , {6,7,8,9,10}};
for (int i=0; i<2 ; i++)
{
for (int j=0; j< 5 ;j++ )
System.out.print(mylist [i][j] +" ");
System.out.print( "\n");
}
}
} 23
How to Find Array Length in Java

To find the length of two-dimensional array you can use


arrayname.length to get the number of rows
arrayname[0].length to get the number of columns

public class Main {


public static void main(String[] args) {
Output
int mylist [] []={{1,2,3,4,5} , { 6, 7,8,9,10}};
2
int r=mylist.length;
5
int c=mylist[0].length;
System.out.println(r);
System.out.println(c);
}}
24
Java two-dimension Arrays
What is the output of the following code

char[][] LTR={ {'A','B’}, {'C','D’}, {'E','F'}};


System.out.println("x="+LTR[1][0]+LTR[2][1]);

Output

a. X=BD

b. X=CF

c. X=AD

d. Error 25
Java two-dimension Arrays
What is the output of the following code

String[][] str= { {"ABCD","XYAS"}, {"BMNIC","CARS"}};

System.out.println(str[1][0].substring(1,3));

Output

MN

MNK

YA

YAS 26
A

int A[ ][ ] = {{3, 4, 2, 1, 6, 5}, 342165


{2, 1, 7, 4, 5, 3}, 217453
{5, 7, 5, 3, 1, 2}, 575312
{4, 2, 3, 6, 4, 7}, 423647
{6, 3, 4, 5, 2, 1}, 634521
{1, 5, 2, 6, 1, 4}}; 152614
27
Java two-dimension Arrays

Define a two-dimension Array named A


of 6 rows and 6 columns of type integer.

int A [ ] [ ] = new int [6] [6] ;

28
Java two-dimension Arrays
Read the data from the keyboard into
the array A.

for (int r=0 ; r<A.length ; r++)


for (int c=0 ; c<A.length ; c++)
A[r][c]= kb.nextInt();

29
Java two-dimension Arrays
Print array A.

for (int r=0 ; r<A.length ; r++)


{
for (int c = 0; c < A.length; c++)
System.out.print(A[r][c] + " ");
System.out.print("\n");
}

30
Java two-dimension Arrays
Find and print the sum of all elements
in array A.

int sum =0;


for (int r=0 ; r<A.length ; r++)
for (int c = 0; c < A.length; c++)
sum = sum + A[r][c];
System.out.print("Sum = " + sum);

31
Java two-dimension Arrays
Find and print the sum of all elements
on the main diagonal in array A.

sum =0;
for (int r=0 ; r<A.length ; r++)
for (int c = 0; c < A.length; c++)
if (r==c) sum = sum + A[r][c];
System.out.println("Sum of the main diagonal = " + sum);

32
Java two-dimension Arrays
Find and print the sum of all elements on
the main second diagonal in array A.
sum =0;
for (int r=0 ; r<A.length ; r++)
for (int c = 0; c < A.length; c++)
if (r+c==5) sum = sum + A[r][c];
System.out.println("Sum of the main second diagonal = " + sum);

33
Java two-dimension Arrays
Find and print the sum of all elements
above the main diagonal in array A.

sum =0;
for (int r=0 ; r<A.length ; r++)
for (int c = 0; c < A.length; c++)
if (r<c) sum = sum + A[r][c];
System.out.println("Sum above main = " + sum);

34
Java two-dimension Arrays
Find and print the sum of all elements
below the main diagonal in array A.

sum =0;
for (int r=0 ; r<A.length ; r++)
for (int c = 0; c < A.length; c++)
if (r>c) sum = sum + A[r][c];
System.out.println("Sum below main = " + sum);

35
Java two-dimension Arrays
Find and print the sum of each row in
array A.

int sumr[ ] ={0,0,0,0,0,0};


for (int r=0 ; r<A.length ; r++)
for (int c = 0; c < A.length; c++)
sumr[r] = sumr[r] + A[r][c];
for( int i =0 ; i<=A.length ; i++)
System.out.println("Sum of row " + i + " " + sumr[i]);
36
Java two-dimension Arrays
Find and print the sum of each column
in array A.

int sumc[ ] ={0,0,0,0,0,0};


for (int c=0 ; c<A.length ; c++)
for (int r = 0; r < A.length; r++)
sumc[c] = sumc[c] + A[r][c];
for( int i =0 ; i<=A.length ; i++)
System.out.println("Sum of column " + i + " " + sumc[i]);
37
Java two-dimension Arrays
Find and print the maximum element
an array A.
int max = 0;
for (int r=0 ; r<A.length ; r++)
for (int c = 0; c < A.length; c++)
if(A[r][c] > max) max = A[r][c];

System.out.println("Max = " + max );


38
Java two-dimension Arrays
Find and print the maximum of each
row in array A.
for (int r=0 ; r<A.length ; r++)
{
int max = 0;
for (int c = 0; c < A.length; c++)
if (A[r][c] > max) max = A[r][c];
System.out.println("Max of row " + r + " " + max);
} 39

You might also like