[go: up one dir, main page]

0% found this document useful (0 votes)
24 views10 pages

Exp 2

مثال

Uploaded by

nazmrwy0
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)
24 views10 pages

Exp 2

مثال

Uploaded by

nazmrwy0
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/ 10

Experiment 2

Java Basics (2)


Objective
This experiment explores the following topics:
 Manipulation of data arrays and array lists.
 Constructing programs through the use of functions.
----------------------------------------------------------------------------------------

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:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}

Example 3:

public class ArrayExample {


public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10};
for (int n: numbers) {
System.out.println(n); }
}
}

Example 4: Write a java program to compute the summation of array elements and find the maximum element
in the array.

public class TestArray


{
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");

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]);
}}}}

Example 6: Write a Java program to remove a specific element from an array.

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:

ArrayList<String> cars = new ArrayList<String>();


cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for (int i = 0; i < cars.size(); i++) {
System.out.println(cars.get(i));
}

Example 10:

import java.util.ArrayList;
import java.util.Collections; // Import the Collections class

public class Main {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Collections.sort(cars); // Sort cars
for (String i : cars) {
System.out.println(i); } }}
5
Example 11:
import java.util.*;

// 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");

// Printing all elements of ArrayList


System.out.println("Initial ArrayList " + al);

// Removing element from above ArrayList


al.remove(1);

// Printing the updated Arraylist elements


System.out.println("After the Index Removal " + al);

// Removing this word element in ArrayList


al.remove("Geeks");

// Now printing updated ArrayList


System.out.println("After the Object Removal " + al);
}
}

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.

To implement a function (static method):


• Create a name.
• Declare type and name of argument(s).
• Specify type for return value.
• Implement body of method.
• Finish with return statement.

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));
}}

Example13: Fibonacci Sequence Using Recursion

public class Main {

// Method to calculate the nth Fibonacci number


public static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
8
return fibonacci(n - 1) + fibonacci(n - 2);
} }

public static void main(String[] args) {


int n = 10;
System.out.println("Fibonacci of " + n + ": " + fibonacci(n)); // Output: Fibonacci of 10: 55
}}

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

Enter the number of students: 7


Enter the grade for student 1: 90
Enter the grade for student 2: 100
Enter the grade for student 3: 89
Enter the grade for student 4: 86
Enter the grade for student 5: 0
Enter the grade for student 6: 5
Enter the grade for student 7: 50
0- 9: 2
10- 19: 0
20- 29: 0
30- 39: 0
40- 49: 0
50- 59: 1
60- 69: 0
70- 79: 0
80- 89: 2
90-100: 2

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

Enter the number of items: 5


Enter the value of all items (separated by spaces): 6 1 8 2 4
Enter the search key: 8
8 is found with index 2

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

Enter the number of items: 5


Enter the value of all items (separated by space): 1 2 3 4 5
The original array is: [1, 2, 3, 4, 5]
The reverse is: [5, 4, 3, 2, 1

10

You might also like