LabManual_Comp-213_Programming-2
LabManual_Comp-213_Programming-2
Methods – Week 1
Objectives:
To define and call void methods with formal parameters and with actual
parameters (i.e., arguments).
To define and call methods with a return value.
Examples:
Example01. Write Java program to define and call void myMethod() function.
myMethod() function prints a message “I just got executed!”:
Output:
I just got called and executed!
Example03. Write Java program to define and call myMethod(int firstNumber, int
secondNumber) function with a return value, where myMethod(int firstNumber,
int secondNumber) function returns the sum of firstNumber and secondNumber
parameters:
Output :
10
Exercises:
Write a class that contains the following two methods:
public static double footToMeter(double foot) /** Convert from feet to meters
*/
public static double meterToFoot(double meter) /** Convert from meters to feet */
Where the formula for the conversion is 1 meter = 0.305 * foot, and 1 foot = 3.279 * meter.
Consider the following values feets (1.0, 2.0, 3.0) and meters (20.0, 21.0, 22.0):
n++;
int x = 1;
increment(x);
Output:
return num1;
else
return num2;
else
return num2;
}
Output:
is 9.45
Example03. Write Java program to create method name swap(int firstnumber , int
secondnumber) to exchange the value of two variable.
int num1 = 1;
int num2 = 2;
System.out.println("Before invoking the swap method, num1 is " + num1 + " and num2 is "
+ num2);
swap(num1, num2);
System.out.println("After invoking the swap method, num1 is " + num1 + " and num2 is " +
num2);
// Swap n1 with n2
n1 = n2;
n2 = temp;
Objectives:
To determine the scope of variables.
To solve mathematical problems by using the methods in the Math class
Examples:
Example 01. Write Java program with the same method twice where it takes a single argument.
The program prints the value of x squared to the screen:
a. What is the difference between x and y variables in terms of scope ?
System.out.println(y*y);
return;
double x = 5.0;
printSquare(3.0);
printSquare(x);
Output :
9.0
25.0
Example02. Write Java program to call suitable functions from the Math class solve the
following mathematical questions:
Round a floating-point value up of 7.343 to the nearest integer value.
Find the value of 2 raised to the power of 8.
Find the logarithm of 1.
°
Find the cosine value of 45 in radians.
import java.lang.Math;
Output:
Logarithm of 1 is 0.0
OUTPUT:-
Cylinder 1 Area: 490.08
Cylinder 2 Area: 106.81
Cylinder 3 Area: 104.04
Lab 4
Week 4
Objectives:
To implement recursive methods.
Example 1. Write a Java program to calculate factorial of a given number using recursion.
{ class Factorial
{
public static void main(String[] args) public static int fact(int num)
{
{ if (num == 0)
return 1;
int num = 5; else
return num * fact(num-1);
long factorial = multiplyNumbers(num); }
public static void main(String[] args)
System.out.println("Factorial of " + num + " = " + factorial); {
int fact_num = fact(4);
} System.out.println(fact_num);
}
public static long multiplyNumbers(int num) }
if (num >= 1)
else
return 1;
return num;
Example 3. Write a Java program to generate fibonacci Series using recursion 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
{ class Fibonacci
{
public static long fib(long n) public static int fib(int n)
{
if (n <= 1)
{ return n;
return fib(n-1) + fib(n-2);
if ((n == 0) || (n == 1)) }
{ OUTPUT : 8
}
Lab 5
Single-dimensional Arrays –Week 5
Objectives:
To create single-dimensional arrays and access array elements using indexes.
To initialize an array using an array initializer.
To program common array operations (displaying arrays, summing all elements)
To invoke methods with array arguments and return values.
Example 01. Write Java program to create two 1-dimensional arrays, myFirstArray and
mySecondArray, with the following specifications:
Declare myFirstArray variable with int type.
Initialize mySecondArray variable with double type and size of 5 using Array Initializer.
Assign five elements of double type with 5.6, 4.5, 3.3, 13.2, and 4.0 values, and
assigns its reference to mySecondArray.
Add 20 on the first index of mySecondArray.
Print the first index, middle index, and the last index of mySecondArray.
int[] myFirstArray;
mySecondArray[0] = 5.6;
mySecondArray[1] = 4.5;
mySecondArray[2] = 3.3;
mySecondArray[3] = 13.2;
mySecondArray[4] = 4.0;
Output:
Example 02. Set up a string array to hold the following names: Ali, Ahmed, and Khalid. Write a
//WAP IN JAVA TO ENTER THE DATA IN STRING ARRAY
program to print them. BY USER USING Scanner library//
import java.util.Scanner;
import java.util.Scanner; public class StringArrayExample {
public static void main(String[] args)
{
public class Exercise { Scanner scanner = new Scanner(System.in); // Prompt
user for the size of the array//
public static void main(String[] args) { System.out.print("Enter the number of strings: ");
int size = scanner.nextInt();
String[] Array = {"Ali", "Mohammed", scanner.nextLine(); // Consume the newline character///
"Khalid"}; for (int i = 0; i < Array.length; String[] strings = new String[size]; // Create the string
array//
i++) { // Input strings from the user//
for (int i = 0; i < size; i++)
String element = Array[i]; {
System.out.print("Enter string " + (i + 1) + ": ");
System.out.println(element); strings[i] = scanner.nextLine();
}
}
// Display the strings//
System.out.println("\nYou entered the following
} strings:");
for (String str : strings)
} {
System.out.println(str);
}
scanner.close(); // Close the scanner//
}
}
Example 03..Write a Java program to calculate the average value of array elements.
import java.util.Scanner;
int[] numbers = new int[] {20, 30, 25, 35, 16, 60, 100};
int sum = 0;
}
Lab 6
Single-dimensional Arrays –Week 6
Example 01. Write a Java program to swap number by passing a array to method.
swap(a[0], a[1]);
swapFirstTwoInArray(a);
n2 = temp;
array[0] = array[1];
array[1] = temp;
Output:
array is {1, 2}
array is {1, 2}
array is {1, 2}
array is {2, 1}
Example 02. Write a program to find a element from a list of elements(Linear Search).
Step 3: If key element is found, return the index position of the array element.
if (key == list[i])
return i;
return -1;
System.out.println(linearSearch(list, 2));
Output:
3
Exercise01. Write a Java program to create a method that finds the smallest element in an array
of double values using the following header:
Exercise02. Write a program that reads ten integers and displays them in the reverse of the order
in which they were read.
Lab 7th Week
Q1) Write a Java program that will read n integers from the user and store them in an array
called arr. Then do the following:
1. Print all the elements of arr in the order they were entered.
if (arr[i] % 2 == 0)
else
Sample Run:
double total = 0;
total += myList[i];
Output :
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Q.3) Write a program to find the a) Smallest element in the array b) Largest element in the array
c) Second largest element in the array.
import java.util.Scanner;
int n;
n=in.nextInt();
arr[i]=in.nextInt();
for(int j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1]){
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
Exercise 01: Write a Java Program to print odd and even elements in an array.
Lab 8 & Lab 9
Objectives:
To declare two-dimensional arrays, and access array elements in a two- dimensional array using
row and column indexes.
To program common operations for two-dimensional arrays (displaying arrays, summing all
elements).
Example01. Write a Java program to create two multi-dimensional arrays, myFirstMatrix, and
mySecondMatrix with the following specifications:
Initialize myFirstMatrix variable with int type and size of 5x5 or 5-by-5 (i.e., five rows, five
columns).
Print the value of first index, and the value of last index of myFirstMatrix.
Initialize mySecondMatrix variable with double type and size of 4-by-3 (i.e., four rows, 3
columns) using Array Initializer.
Assign the following elements of double type with (1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 9.0),
(10.0, 11.0, 12.0), and assigns its reference to mySecondMatrix.
Print the value of first index, and the value of last index of mySecondMatrix.
double[][] mySecondMatrix = {{1.0, 2.0, 3.0}, {4, 5, 6},{7.0, 8, 9.0}, {10, 11.0, 12}};
}
}
Output:
Example02. Write a Java program to create a two-dimensional array, myThirdMatrix, with the following
specifications:
Allow the user to input values using for loop. Use length() function to get the array length.
import java.util.Scanner;
myThirdMatrix[row][column] = input.nextInt();
System.out.println();
Output:
2468
1357
Example 03. Write a program to input Two dimensional array and compute the sum of all elements of
the array.
import java.util.Scanner;
// Create a Scanner
System.out.println("Enter " + m.length + " rows and “ + m*0+.length + " columns: ");
m[i][j] = input.nextInt();
return m;
int total = 0;
total += m[row][column];
return total;
}
}
1234
4567
8 9 10 11
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}}
int a[][]={{1,2,3},{4,5,6},{7,8,9}};
int b[][]={{1,1,1},{1,1,1},{1,1,1}};
for(int i = 0;i<3;i++){
for(int j = 0;j<3;j++){
c[i][j] = a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
System.out.println();
Output:
234
567
8 9 10
Lab 10
Objec&ve
1. **File Class** - Represents a file or directory path in the file system.
2. **FileReader and FileWriter**- Used for reading from and wri?ng to text
files.
3. **BufferedReader and BufferedWriter**- Provide buffering for reading and
wri?ng, improving performance.
import java.io.File;
OUTPUT:
File does exist.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOExcep?on;
Output:
File does exit.
Else.
java.io.FileNotFoundExcep&on: example.txt (No such file or directory)
at java.base/java.io.FileInputStream.open0(Na&ve Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
=== Code Execu+on Successful ===
Example 3: Wri&ng to a File using FileWriter and BufferedWriter java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOExcep?on;
Output:
Hello World
Welcome to file handling in Java
Else.
java.io.FileNotFoundExcep&on: example.txt (Permission denied)
at java.base/java.io.FileOutputStream.open0(Na&ve Method)
at java.base/java.io.FileOutputStream.open(FileOutputStream.java:298)
=== Code Execu+on Successful ===
Lab 11
Objec&ve
1. *PrintWriter**
- Provides convenient methods to write forma7ed text to files.
2. **FileInputStream and FileOutputStream**
- Used for reading and wriDng binary files.
3. **SerializaDon**
- ConverDng an object into a byte stream for saving to a file.
4. **NIO (New Input/Output)**
- Introduces classes like `Path`, `Files` for advanced file operaDons.
import java.io.FileNotFoundExcepDon;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOExcepDon;
Output:
File does exit.
Else.
java.io.FileNotFoundExcep&on: data.bin (Permission denied)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:126)
at BinaryFileExample.main(BinaryFileExample.java:13)
java.io.FileNotFoundExcep&on: data.bin (No such file or directory
=== Code Execu+on Successful ===