Lesson Plan - Arrays 2 PDF
Lesson Plan - Arrays 2 PDF
Arrays - 2
Pre-Requisites
Basics of arrays and methods
Code:
import java.io.*;
import java.util.*;
int n=sc.nextInt();
arr[i] = sc.nextInt();
System.out.println(arr[i]);
int a[] = { 1, 4, 7, 9 };
int n = a.length;
b = a;
b[0] = 5;
Output:
Original array
5 4 7 9
Referenced Array
5 4 7 9
Note: Changes in the referenced array will be reflected in the original array as well because both are referring
to the same location.
Code:
int a[] = { 1, 4, 7, 9 };
int n = a.length;
b[0] = 5;
Original array
1 4 7 9
Cloned Array
5 4 7 9
Note: When we make a copy of an entire array without referencing it, it forms a deep copy of that array. In case
of a cloned array, the changes will not be reflected in the original array as we have created a deep copy of the
original array.
Syntax:
Code:
import java.io.*;
import java.util.*;
int a[] = { 1, 4, 7, 9 };
int n = a.length;
b[0] = 5;
Output:
Original array
1 4 7 9
Copied Array
5479
Input a[] = {1 , 4, 7 , 9 , 1}
x = 1
Output 4
import java.io.*;
import java.util.*;
int x) {
if(a[i] == x)
index = i;
return index;
System.out.println(lastOccurance(a,1));
Explanation: Traverse through the whole array and compare the current element with the target element ‘x’
and if it matches then it will be our last seen index.
Input a[] = {1 , 4, 7 , 9 , 1}
x = 1
Output 2
Code:
import java.util.*;
int count = 0;
if(a[i] == x)
count++;
return count;
System.out.println(countOfElements(a,1));
Explanation: Check if the element is equal to the element x and increment the count variable and in the end
return it.
Input a[] = {1 , 4, 7 , 9 , 1}
x = 1
Output 3
Code :
import java.io.*;
import java.util.*;
int count = 0;
if(a[i] > x)
count++;
return count;
System.out.println(countOfElements(a,1));
Explanation: Traverse the array and check if the element is greater than x and increment the count variable, in
the end simply return it.
Input a[] = {1 , 2, 3 , 4 , 5}
Output True
Code :
import java.io.*;
import java.util.*;
ans = false;
return ans;
System.out.println(check(a));
That is all for this class ! See you in the next one !