Exp 2
Exp 2
1- Arrays
A computer's memory is also an indexed sequence of memory locations.
• Each primitive type value occupies a fixed number of locations.
• Array values are stored in contiguous locations.
1
Example 1:
public class PQarray1
{
public static void main(String[] args)
{
int[] a = new int[6];
int[] b = new int[a.length];
b = a;
for (int i = 1; i < b.length; i++)
b[i] = i;
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
for (int i = 0; i < b.length; i++)
System.out.print(b[i] + " ");
System.out.println();
}
}
Example 2: Complete then run the following code excerpt:
Example 3:
Example 4: Write a java program to compute the summation of array elements and find the maximum element
in the array.
2
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}}
Example 5: Write a Java program to find duplicate values in an array of integer values.
public static void main(String[] args)
{
int[] my_array = {1, 2, 5, 5, 6, 6, 7, 2};
for (int i = 0; i < my_array.length-1; i++) {
for (int j = i+1; j < my_array.length; j++) {
if (my_array[i] == my_array[j]) {
System.out.println("Duplicate Element : " + my_array[j]);
}}}}
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
int removeIndex = -1;
Scanner in = new Scanner(System.in);
System.out.println("Enter the value to be removed: ");
int RM = in.nextInt();
for(int i = 0; i < my_array.length; i++)
if(my_array[i] == RM)
removeIndex = i;
if(removeIndex == -1)
System.out.println("the element is not found");
else {
for (int i = removeIndex; i < my_array.length - 1; i++) {
my_array[i] = my_array[i + 1];}
System.out.println("array elements after removal are: ");
for (int i = 0; i < my_array.length-1; i++) {
System.out.println(my_array[i]);}
}
3
Example 7: Write a Java program to sort the array elements in ascending order.
class GFG {
// Main driver method
public static void main(String[] args)
{
// Custom input array
int[] arr = { 4, 3, 2, 1 };
int temp = 0;
// Outer loop
for (int i = 0; i < arr.length-1; i++) {
// Inner nested loop pointing 1 index ahead
for (int j = i + 1; j < arr.length; j++) {
// Checking elements
if (arr[j] < arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}}
// Printing sorted array elements
System.out.print(arr[i] + " ");
}}}
Example 8: Write a Java program that read array elements of two dimensions from keyboard.
import java.util.Scanner;
public class ArrayInputExample2
{
public static void main(String args[])
{
int m, n, i, j;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of rows: ");
//taking row as input
m = sc.nextInt();
System.out.print("Enter the number of columns: ");
//taking column as input
n = sc.nextInt();
// Declaring the two-dimensional matrix
int array[][] = new int[m][n];
// Read the matrix values
System.out.println("Enter the elements of the array: ");
//loop for row
for (i = 0; i < m; i++)
//inner for loop for column
for (j = 0; j < n; j++)
array[i][j] = sc.nextInt();
//accessing array elements
System.out.println("Elements of the array are: ");
4
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
//prints the array elements
System.out.print(array[i][j] + " ");
//throws the cursor to the next line
System.out.println();
}}}
2- ArrayList
In Java, we use the ArrayList class to implement the functionality of resizable-arrays. It implements
the List interface of the collections framework.
Unlike arrays, ArrayLists can automatically adjust their capacity when we add or remove elements from
them. Hence, ArrayLists are also known as dynamic arrays.
Before using ArrayList, we need to import the java.util.ArrayList package first. Here is how we can create
ArrayLists in Java:
ArrayList<Type> name = new ArrayList<Type>();
Example 9:
Example 10:
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an object of ArrayList class
ArrayList<String> al = new ArrayList<String >();
// Adding elements to ArrayList
// Custom addition
al.add("Geeks");
al.add("Geeks");
// Adding element at specific index
al.add(1, "For");
6
We have to use Integer instead of int because we cannot use primitive types while creating an ArrayList.
Instead, we have to use the corresponding wrapper classes.
The wrapper classes in Java are used to convert primitive types (int, char, float, etc) into the
corresponding objects.
7
3- Functions
Applications:
• Scientists use mathematical functions to calculate formulas.
• Programmers use functions to build modular programs.
Example 12:
public class PQfunctions1a {
public static int cube(int i)
{
int j = i * i * i;
return j;
}
public static void main(String[] args)
{
int N = 10;
for (int i = 1; i <= N; i++)
System.out.println(i + "^3 = " + cube(i));
}}
Assignments
Q1\ Write a program that prompts the user for the number of students in a class (a non-negative integer), reads
it, and saves it in an integer variable called numStudents. It then prompts the user for the grade of each of the
students (an integer between 0 and 100) and saves them in an integer array called grades. Assume that the
grades are between 0 and 100. The program shall then create 10 histogram bins to contain the counts of grades
between 0-9, 10-19, ..., and 90-100, respectively, in an integer array called bins. Finally, print the contents of
the bins as shown in the sample output below. No input validation is needed.
Sample Output:
Sample Output Sample
Input
9
Q2\ Write a function called search(), which takes an array of integers and another integer value; and returns
the array index if the array contains the latter integer value; or -1, otherwise. The function's prototype is as
follows:
public static int search(int[] array, int key)
Also write the main() section that prompts the user for the size of an integer array, followed by its values and
a search key; and calls the search function as shown in the sample output below.
Sample Output:
Sample Output Sample Input
Q3\ write a function called reverse(int[] array) to reverse the contents of the argument array; and a function
called print(int[] array) to print the array. The prototypes are:
public static void reverse(int[] array) // Reverse the contents of the given int array, in place
public static void print(int[] array) // Print [x1, x2, ..., xN]
Also write the main() section that prompts the user for the size of an integer array, then for its values, and
calls these functions as shown in the sample output below.
Sample Output:
Sample Output Sample Input
10