PDF05

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

BLDEA's

V P Dr. P. G. Halakatti College of Engineering and


Technology, Vijayapur
Approved by AICTE New Delhi, Recognized by Govt. of Karnataka and Affiliated to VTU Belagavi

LABORATORY MANUAL

COURSE: DATA STRUCTURES LABORATORY

COURSE CODE: BCSL305

SEMESTER: III

DEPARTMENT OF CSE (Artificial Intelligence and Machine Learning)


LAB MANUAL OBJECT ORIENTED PROGRAMMING WITH JAVA

1. Course Details
Year / Semester 2nd Academic Year 2022-23
Course Title PHP Programming Course Code BAI358D
Course Type CIE Marks 50
(Theory/Practical Practical SEE Marks 50
/Integrated ) Total Marks 100
Teaching Hours/Week
0:0:2:0 Duration of SEE 02
(L:T:P:S)
Lab Manual Authors Sign - Date

Checked By Sign - Date

2. Institute Mission:
 To Enrich Students with the essence of science and engineering knowledge, Professional ethics
and social values.
 To instill creativity and Research Temperament to Reach the Greater Heights of Professional
Success.

3. Institute Vision: To Emerge as a Widely Acknowledged Centre in Technical Education and


Research to Cater the need of Society with a Futuristic outlook.

4. Program Objectives: The educational objectives of the Mechanical Engineering Program are to
prepare our graduates to:
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.

PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural science, and engineering sciences.

PO3: Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate consideration
for the public health and safety, cultural, societal and environmental considerations.

PO4: Conduct investigations of complex problems: Use of research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.

PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice

Department of Electrical and Electronics Engineering. 1


BLDEA’s V P Dr PGHCET, Vijayapur
LAB MANUAL OBJECT ORIENTED PROGRAMMING WITH
PO7: Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of and need for
sustainable development.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9: Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams and in multidisciplinary settings.

PO10: Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations and to give and receive
clear instructions.

PO11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader
in a team, to manage projects and in multidisciplinary environments.

PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

5. Course Objectives
This laboratory course enables students to get practical experience in design, develop, implement,
analyze and evaluation/testing of
● To introduce the PHP syntax, elements, and control structures
● To make use of PHP Functions and File handling
● To illustrate the concept of PHP arrays and OOPs

6. Course Outcomes
At the end of the course, the student will be able to:

CO1 Apply basic concepts of PHP to develop web program


CO2 Develop programs in PHP involving control structures.
CO3 Develop programs to handle structured data (object) and data items (array)
CO4 Develop programs to access and manipulate contents of files

CO5 Use super-global arrays and regular expressions to solve real world problems.

Dep of CSE(Artificial intelligence & machine 5


learning).BLDEA’s V P Dr PGHCET, Vijayapur
LAB MANUAL OBJECT ORIENTED PROGRAMMING WITH

7. Assessment Detail

The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE)
is 50%. The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and
for the SEE minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A student shall be
deemed to have satisfied the academic requirements and earned the credits allotted to each subject/ course
if the student secures a minimum of 40% (40 marks out of 100) in the sum total of the CIE (Continuous
Internal Evaluation) and SEE (Semester End Examination) taken together

Continuous Internal Evaluation (CIE): CIE marks for the practical course are 50 Marks. The split-up of CIE
marks for record/ journal and test are in the ratio 60:40.

● Each experiment is to be evaluated for conduction with an observation sheet and record write-up. Rubrics
for the evaluation of the journal/write-up for hardware/software experiments are designed by the faculty
who is handling the laboratory session and are made known to students at the beginning of the practical
session.

● Record should contain all the specified experiments in the syllabus and each experiment write-up will be
evaluated for 10 marks.

● Total marks scored by the students are scaled down to 30 marks (60% of maximum marks).

● Weightage to be given for neatness and submission of record/write-up on time.

● Department shall conduct a test of 100 marks after the completion of all the experiments listed in the
syllabus.

● In a test, test write-up, conduction of experiment, acceptable result, and procedural knowledge will carry
a weightage of 60% and the rest 40% for viva-voce.

● The suitable rubrics can be designed to evaluate each student’s performance and learning ability.

● The marks scored shall be scaled down to 20 marks (40% of the maximum marks).

The Sum of scaled-down marks scored in the report write-up/journal and marks of a test is the total CIE
marks scored by the student.

Semester End Evaluation (SEE):

● SEE marks for the practical course are 50 Marks.

● SEE shall be conducted jointly by the two examiners of the same institute, examiners are appointed by
the Head of the Institute.

● The examination schedule and names of examiners are informed to the university before the conduction
of the examination. These practical examinations are to be conducted between the schedule mentioned in
Dep of CSE(Artificial intelligence & machine 5
learning).BLDEA’s V P Dr PGHCET, Vijayapur
LAB MANUAL OBJECT ORIENTED PROGRAMMING WITH
the academic calendar of the University.

● All laboratory experiments are to be included for practical examination.

● (Rubrics) Breakup of marks and the instructions printed on the cover page of the answer script to be
strictly adhered to by the examiners. OR based on the course requirement evaluation rubrics shall be
decided jointly by examiners.

● Students can pick one question (experiment) from the questions lot prepared by the examiners jointly.

● Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly by
examiners.

● General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure and result in
-60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for 100 marks and scored
marks shall be scaled down to 50 marks (however, based on course type, rubrics shall be decided by the
examiners)

● Change of experiment is allowed only once and 15% of Marks allotted to the procedure part are to be
made zero.

The minimum duration of SEE is 02 hours

Suggested Learning Resources:

● BOOK: Programming in HTML and PHP (Coding for Scientists and Engineers, BY DEVID R
BROOKS, Springer International Publishing AG 2017

● PHP TUTORIALS: [https://www.w3schools.com/php/}

● PHP TUTORIALS: [ https://www.tutorialspoint.com/php/index.htm]

● HTML TUTORIALS: [https://www.w3schools.com/html/]

Title of the Program


Sl No.

1 a. Develop a PHP program to calculate areas of Triangle and Rectangle.


b. Develop a PHP program to calculate Compound Interest.

2 Demonstrating the various forms to concatenate multiple strings Develop program(s) to


demonstrate concatenation of strings:
(i) Strings represented with literals (single quote or double quote)
(ii) Strings as variables
(iii) Multiple strings represented with literals (single quote or double quote) and
variables
(iv) Strings and string variables containing single quotes as part string contents
Dep of CSE(Artificial intelligence & machine 5
learning).BLDEA’s V P Dr PGHCET, Vijayapur
LAB MANUAL OBJECT ORIENTED PROGRAMMING WITH
(v) Strings containing HTML segments having elements with attributes
a. Develop a PHP Program(s) to check given number is: (i) Odd or even (ii) Divisible by
a given number (N) (iii) Square of a another number b. Develop a PHP Program to
3
compute the roots of a quadratic equation by accepting the coefficients. Print the
appropriate messages.

a. Develop a PHP program to find the square root of a number by using the newton’s
4
algorithm. b. Develop a PHP program to generate Floyd’s triangle.

a. Develop a PHP application that reads a list of numbers and calculates mean and standard
deviation. b. Develop a PHP application that reads scores between 0 and 100 (possibly
5 including both 0 and 100) and creates a histogram array whose elements contain the
number of scores between 0 and 9, 10 and 19, etc. The last “box” in the histogram should
include scores between 90 and 100. Use a function to generate the histogram.

a. Develop PHP program to demonstrate the date() with different parameter options. b.
6
Develop a PHP program to generate the Fibonacci series using a recursive function.

Develop a PHP program to accept the file and perform the following (i) Print the first N
7
lines of a file (ii) Update/Add the content of a file

Develop a PHP program to read the content of the file and print the frequency of
8
occurrence of the word accepted by the user in the file

Develop a PHP program to filter the elements of an array with key names. Sample Input
Data: 1st array: ('c1' => 'Red', 'c2' => 'Green', 'c3' => 'White', c4 => 'Black') 2nd array:
9
('c2', 'c4')
Output: Array ( [c1] => Red [c3] => White )

Develop a PHP program that illustrates the concept of classes and objects by reading and
10 printing employee data, including Emp_Name, Emp_ID, Emp_Dept, Emp_Salary, and
Emp_DOJ.

a. Develop a PHP program to count the occurrences of Aadhaar numbers present in a text.
11 b. Develop a PHP program to find the occurrences of a given pattern and replace them
with a text.

Develop a PHP program to read the contents of a HTML form and display the contents on
12
browser.

Dep of CSE(Artificial intelligence & machine 5


learning).BLDEA’s V P Dr PGHCET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA

EXPERIMENT: 1

1. a. Develop a PHP program to calculate areas of Triangle and Rectangle. b. Develop a PHP program to
calculate Compound Interest.
#DEMO(TRIANGLE)
<?php
$base = 10;
$height = 15;
echo "area with base $base and height $height= " . ($base * $height) / 2;
?>
#DEMO(RECTANGLE)
<?php
$length = 14;
$width = 12;
echo "area of rectangle is $length * $width= " . ($length * $width) . "<br />";
?>
#1 Develop a PHP program to calculate Compound Interest.
<?php
$p = readline("Enter the Principal amount: ");
$R = readline("Enter the Annual nominal interest rate as a percent: ");
$t = readline("Enter the time in decimal years: ");
$n = readline("Enter the number of times the interest is compounded: ");
$r = $R / 100;
$ci = $p * pow((1 + ($r / $n)), $n * $t);
echo "Compound Interest = $ci";
?>
Output:
area with base 10 and height 15= 75
Enter the Principal amount: 100
Enter the Annual nominal interest rate as a percent: 10
Enter the time in decimal years: 1
Enter the number of times the interest is compounded: 2
Compound Interest = 110.25

2. Demonstrating the various forms to concatenate multiple strings Develop program(s) to demonstrate
concatenation of strings: (i) Strings represented with literals (single quote or double quote) (ii) Strings
as variables (iii) Multiple strings represented with literals (single quote or double quote) and variables
(iv) Strings and string variables containing single quotes as part string contents (v) Strings containing
HTML segments having elements with attributes
<?php
// (i) Strings represented with literals (single quote or double quote)
$string_literal_concatenation = 'Hello, ' . "world!";
// (ii) Strings as variables
$string_variable1 = "Hello, ";
$string_variable2 = "world!";
$variable_concatenation = $string_variable1 . $string_variable2;
// (iii) Multiple strings represented with literals and variables
$string_literal_variable_concatenation = "Concatenating " . $string_variable1 . "multiple " . "strings.";
// (iv) Strings and string variables containing single quotes as part of string contents
$string_with_single_quotes = "I'm using single quotes inside this string.";
$variable_with_single_quotes = 'This variable contains a single quote: ' . $string_variable1;
// (v) Strings containing HTML segments having elements with attributes
$html_string = '<div class="container">' . '<p id="paragraph">This is an HTML string.</p>' . '</div>';
Department of CSE( artificial intelligence & machine learning) 21
.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA
// Printing the results
echo "(i) Strings represented with literals:\n";
echo $string_literal_concatenation . "\n\n";
echo "(ii) Strings as variables:\n";
echo $variable_concatenation . "\n\n";
echo "(iii) Multiple strings represented with literals and variables:\n";
echo $string_literal_variable_concatenation . "\n\n";
echo "(iv) Strings and string variables containing single quotes:\n";
echo $string_with_single_quotes . "\n";
echo $variable_with_single_quotes . "\n\n";
echo "(v) Strings containing HTML segments:\n";
echo $html_string . "\n";
?>
Output:
(i) Strings represented with literals:
Hello, world!

(ii) Strings as variables:


Hello, world!

(iii) Multiple strings represented with literals and variables:


Concatenating Hello, multiple strings.

(iv) Strings and string variables containing single quotes:


I'm using single quotes inside this string.
This variable contains a single quote: Hello,

(v) Strings containing HTML segments:


<div class="container"><p id="paragraph">This is an HTML string.</p></div>

3. A) Develop a PHP Program(s) to check given number is: (i) Odd or even (ii) Divisible by a given
number (N) (iii) Square of another number
B) Develop a PHP Program to compute the roots of a quadratic equation by accepting the coefficients.
Print the appropriate messages.

<?php

// Function to check if a number is odd or even


function checkOddEven($number) {
if ($number % 2 == 0) {
echo "$number is even.\n";
} else {
echo "$number is odd.\n";
}
}

// Function to check if a number is divisible by N


function checkDivisibility($number, $divisor) {
if ($number % $divisor == 0) {
Department of CSE( artificial intelligence & machine learning) 21
.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA
echo "$number is divisible by $divisor.\n";
} else {
echo "$number is not divisible by $divisor.\n";
}
}

// Function to check if a number is the square of another number


function checkSquare($number, $base) {
$square = $base * $base;
if ($number == $square) {
echo "$number is the square of $base.\n";
} else {
echo "$number is not the square of $base.\n";
}
}

// Example usage
$givenNumber = readline("Enter the number:");
$divisor = readline("Enter the divisor:");
$baseNumber = readline("Enter the basenumber:");

// Check if the number is odd or even


checkOddEven($givenNumber);

// Check if the number is divisible by N


checkDivisibility($givenNumber, $divisor);

// Check if the number is the square of another number


checkSquare($givenNumber, $baseNumber);
?>
Output:
Enter the number:16
Enter the divisor:4
Enter the basenumber:4
16 is even.
16 is divisible by 4.
16 is the square of 4.

<?php

// Function to calculate the roots of a quadratic equation


function calculateRoots($a, $b, $c) {
Department of CSE( artificial intelligence & machine learning) 21
.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA
// Calculate the discriminant
$discriminant = $b * $b - 4 * $a * $c;

// Check if the discriminant is non-negative


if ($discriminant >= 0) {
// Calculate the roots
$root1 = (-$b + sqrt($discriminant)) / (2 * $a);
$root2 = (-$b - sqrt($discriminant)) / (2 * $a);

// Print the roots


echo "Root 1: $root1\n";
echo "Root 2: $root2\n";
} else {
// If the discriminant is negative, roots are imaginary
$realPart = -$b / (2 * $a);
$imaginaryPart = sqrt(abs($discriminant)) / (2 * $a);

// Print the roots as complex numbers


echo "Root 1: $realPart + $imaginaryPart i\n";
echo "Root 2: $realPart - $imaginaryPart i\n";
}
}

// Accept coefficients from the user


echo "Enter coefficient a: ";
$a = floatval(readline());

echo "Enter coefficient b: ";


$b = floatval(readline());

echo "Enter coefficient c: ";


$c = floatval(readline());

// Call the function to calculate and print the roots


calculateRoots($a, $b, $c);
?>
Output:
Enter coefficient a: 1
Enter coefficient b: -3
Enter coefficient c: 2
Root 1: 2
Root 2: 1
Department of CSE( artificial intelligence & machine learning) 21
.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA

4 a. Develop a PHP program to find the square root of a number by using the newton’s algorithm. b.
Develop a PHP program to generate Floyd’s triangle.
<?php
function newtonSquareRoot($number, $guess = null, $epsilon = 1e-10) {
// Check if the initial guess is provided
if ($guess === null) {
$guess = $number / 2; // A common initial guess is half of the number
}
// Iterate until the difference between consecutive guesses is less than epsilon
while (abs($guess * $guess - $number) > $epsilon) {
// Update the guess using Newton's method
$guess = 0.5 * ($guess + $number / $guess);
}
return $guess;
}
// Example usage:
$number = 25; // Change this to the number for which you want to find the square root
$result = newtonSquareRoot($number);
echo "The square root of $number is approximately: $result\n";
?>

Output
The square root of 25 is approximately: 5

<?php
function generateFloydsTriangle($rows) {
$number = 1;

for ($i = 1; $i <= $rows; $i++) {


for ($j = 1; $j <= $i; $j++) {
echo $number . " ";
$number++;
}
echo "\n";
}
}
// Example usage:
$rows = 5; // Change this to the number of rows you want in the triangle
generateFloydsTriangle($rows);
?>
Output
1
23
456
7 8 9 10
11 12 13 14 15

Department of CSE( artificial intelligence & machine learning) 21


.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA

5 a. Develop a PHP application that reads a list of numbers and calculates mean and standard deviation.
b. Develop a PHP application that reads scores between 0 and 100 (possibly including both 0 and 100) and creates a
histogram array whose elements contain the number of scores between 0 and 9, 10 and 19, etc. The last “box” in the
histogram should include scores between 90 and 100. Use a function to generate the histogram.

<?php
// Function to calculate mean
function calculateMean($numbers) {
$sum = array_sum($numbers);
$count = count($numbers);
return $sum / $count;
}

// Function to calculate standard deviation


function calculateStandardDeviation($numbers) {
$mean = calculateMean($numbers);
$sumSquaredDiff = 0;

foreach ($numbers as $number) {


$sumSquaredDiff += pow($number - $mean, 2);
}

$variance = $sumSquaredDiff / count($numbers);


return sqrt($variance);
}

// Input list of numbers


$numbers = [5, 8, 12, 15, 20];

// Calculate mean and standard deviation


$mean = calculateMean($numbers);
$stdDeviation = calculateStandardDeviation($numbers);

// Display results
echo "Numbers: " . implode(', ', $numbers) . "\n";
echo "Mean: $mean\n";
echo "Standard Deviation: $stdDeviation\n";
?>
OUTPUT
Numbers: 5, 8, 12, 15, 20
Mean: 12
Standard Deviation: 5.2535702146255

Department of CSE( artificial intelligence & machine learning) 21


.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA

<?php
// Function to generate histogram
function generateHistogram($scores) {
$histogram = array_fill(0, 11, 0); // Initialize histogram array with 11 "boxes" (0-9, 10-19, ..., 90-100)

foreach ($scores as $score) {


$index = floor($score / 10); // Determine the index for the histogram array
$histogram[$index]++;
}

return $histogram;
}

// Sample scores (replace with your own scores)


$scores = [85, 92, 45, 60, 78, 15, 99, 30, 55, 88, 100];

// Generate histogram
$histogram = generateHistogram($scores);

// Display results
echo "Scores: " . implode(', ', $scores) . "\n";

echo "Histogram:\n";
for ($i = 0; $i < count($histogram); $i++) {
$rangeStart = $i * 10;
$rangeEnd = ($i * 10) + 9;

if ($i == 10) {
$rangeEnd = 100;
}

echo "[$rangeStart-$rangeEnd]: {$histogram[$i]}\n";


}
?>
OUTPUT
Scores: 85, 92, 45, 60, 78, 15, 99, 30, 55, 88, 100
Histogram:
[0-9]: 0
[10-19]: 1
[20-29]: 0
[30-39]: 1
[40-49]: 1
[50-59]: 1
[60-69]: 1
[70-79]: 1
[80-89]: 2
[90-99]: 2
[100-100]: 1

Department of CSE( artificial intelligence & machine learning) 21


.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA

6 a. Develop PHP program to demonstrate the date() with different parameter options.
b. Develop a PHP program to generate the Fibonacci series using a recursive function.

<?php
// Current date and time
echo "Current Date and Time: " . date("Y-m-d H:i:s") . "\n";

// Date with a custom format


echo "Formatted Date: " . date("l, F j, Y") . "\n";

// Displaying the day of the week


echo "Day of the Week: " . date("l") . "\n";

// Displaying the month


echo "Month: " . date("F") . "\n";

// Displaying the year


echo "Year: " . date("Y") . "\n";

// Displaying the time in 12-hour format with AM/PM


echo "Time (12-hour format): " . date("h:i:s A") . "\n";

// Displaying the time in 24-hour format


echo "Time (24-hour format): " . date("H:i:s") . "\n";

// Displaying the day of the year


echo "Day of the Year: " . date("z") . "\n";

// Displaying the week number of the year


echo "Week Number: " . date("W") . "\n";

// Displaying the current time zone


echo "Time Zone: " . date_default_timezone_get() . "\n";

// Displaying the Unix timestamp


echo "Unix Timestamp: " . time() . "\n";
?>
OUTPUT
Current Date and Time: 2023-12-20 05:43:59
Formatted Date: Wednesday, December 20, 2023
Day of the Week: Wednesday
Month: December
Year: 2023
Time (12-hour format): 05:43:59 AM
Time (24-hour format): 05:43:59
Day of the Year: 353
Week Number: 51
Time Zone: UTC
Unix Timestamp: 1703051039

Department of CSE( artificial intelligence & machine learning) 21


.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA
<?php
// Function to generate Fibonacci series recursively
function fibonacci($n) {
if ($n <= 1) {
return $n;
} else {
return (fibonacci($n - 1) + fibonacci($n - 2));
}
}

// Number of terms in the Fibonacci series


$terms = 10;

// Display the Fibonacci series


echo "Fibonacci Series (first $terms terms): ";
for ($i = 0; $i < $terms; $i++) {
echo fibonacci($i) . " ";
}
?>

OUTPUT
Fibonacci Series (first 10 terms): 0 1 1 2 3 5 8 13 21 34

Department of CSE( artificial intelligence & machine learning) 21


.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA
7. Develop a PHP program to accept the file and perform the following (i) Print the first N lines of a file (ii)
Update/Add the content of a file
<?php

// Function to print the first N lines of a file


function printFirstNLines($filename, $n) {
$file = fopen($filename, "r");

if ($file) {
$lineNumber = 0;

while (($line = fgets($file)) !== false && $lineNumber < $n) {


echo $line;
$lineNumber++;
}

fclose($file);
} else {
echo "Error opening file: $filename";
}
}

// Function to update/add content to a file


function updateFileContent($filename, $content) {
$file = fopen($filename, "a"); // Open the file in append mode

if ($file) {
fwrite($file, $content);
fclose($file);
echo "Content updated/added successfully!";
} else {
echo "Error opening file: $filename";
}
}

// Example usage:
$filename = "example.txt"; // Replace with your file name
$N = 5; // Replace with the desired number of lines to print

echo "Printing the first $N lines of the file:\n";


printFirstNLines($filename, $N);

$newContent = "\nNew content to be added to the file.";


echo "\n\nUpdating/add content to the file:\n";
updateFileContent($filename, $newContent);

Output:
Hi
Hello
Good morning
Welcome to PHP Programming
Do well

Updating/add content to the file


Content updated/added successfully!

Department of CSE( artificial intelligence & machine learning) 21


.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA

8.Develop a PHP program to read the content of the file and print the frequency of occurrence of the word accepted
by the user in the file
<?php

// Function to calculate the frequency of a word in a file


function calculateWordFrequency($filename, $searchWord) {
$fileContent = file_get_contents($filename);

if ($fileContent !== false) {


$wordCount = substr_count($fileContent, $searchWord);
return $wordCount;
} else {
return -1; // Indicates an error in reading the file
}
}

// Example usage:
$filename = "example.txt"; // Replace with your file name

// Accept the word from the user


$searchWord = readline("Enter the word to find its frequency in the file: ");

// Calculate and print the frequency


$wordFrequency = calculateWordFrequency($filename, $searchWord);

if ($wordFrequency !== -1) {


echo "The word '$searchWord' occurs $wordFrequency times in the file.\n";
} else {
echo "Error reading the file: $filename\n";
}
?>

Output:
Enter the word to find its frequency in the file: hello
The word 'hello' occurs 3 times in the file.

Department of CSE( artificial intelligence & machine learning) 21


.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA
9.Develop a PHP program to filter the elements of an array with key names. Sample Input Data: 1st array: ('c1' =>
'Red', 'c2' => 'Green', 'c3' => 'White', c4 => 'Black') 2nd array: ('c2', 'c4')
Output: Array ( [c1] => Red [c3] => White )

<?php

// Function to filter array elements based on key names


function filterArrayByKeys($inputArray, $keysToKeep) {
// Use array_diff_key to filter elements by keys
$filteredArray = array_diff_key($inputArray, array_flip($keysToKeep));

return $filteredArray;
}

// Sample input data


$array1 = array('c1' => 'Red', 'c2' => 'Green', 'c3' => 'White', 'c4' => 'Black');
$array2 = array('c2', 'c4');

// Filter the elements of $array1 based on keys in $array2


$outputArray = filterArrayByKeys($array1, $array2);

// Print the output


print_r($outputArray);

?>

Output:
Array
(
[c1] => Red
[c3] => White
)

Department of CSE( artificial intelligence & machine learning) 21


.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA
10. Develop a PHP program that illustrates the concept of classes and objects by reading and printing employee data,
including Emp_Name, Emp_ID, Emp_Dept, Emp_Salary, and Emp_DOJ.

<?php

class Employee {
// Properties
public $Emp_Name;
public $Emp_ID;
public $Emp_Dept;
public $Emp_Salary;
public $Emp_DOJ;

// Constructor
public function __construct($name, $id, $dept, $salary, $doj) {
$this->Emp_Name = $name;
$this->Emp_ID = $id;
$this->Emp_Dept = $dept;
$this->Emp_Salary = $salary;
$this->Emp_DOJ = $doj;
}

// Method to display employee details


public function displayEmployeeDetails() {
echo "Employee Name: " . $this->Emp_Name . "\n";
echo "Employee ID: " . $this->Emp_ID ."\n";
echo "Employee Department: " . $this->Emp_Dept . "\n";
echo "Employee Salary: " . $this->Emp_Salary . "\n";
echo "Employee Date of Joining: " . $this->Emp_DOJ . "\n";
}
}

// Creating objects
$employee1 = new Employee("John Doe", "E001", "IT", 50000, "2022-01-01");
$employee2 = new Employee("Jane Smith", "E002", "HR", 45000, "2022-02-15");

// Displaying employee details


echo "Employee 1 Details:\n";
$employee1->displayEmployeeDetails();

echo "\t";

echo "Employee 2 Details:\n";


$employee2->displayEmployeeDetails();

?>

Output
Employee 1 Details:
Employee Name: John Doe
Employee ID: E001
Employee Department: IT
Employee Salary: 50000
Employee Date of Joining: 2022-01-01
Employee 2 Details:
Employee Name: Jane Smith
Employee ID: E002
Department of CSE( artificial intelligence & machine learning) 21
.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA
Employee Department: HR
Employee Salary: 45000
Employee Date of Joining: 2022-02-15

11 a. Develop a PHP program to count the occurrences of Aadhaar numbers present in a text. b. Develop a PHP
program to find the occurrences of a given pattern and replace them with a text.

<?php

function countAadhaarOccurrences($text) {
// Regular expression pattern for Aadhaar numbers
$pattern = '/\b\d{4}\s?\d{4}\s?\d{4}\b/';

// Use preg_match_all to find all occurrences of Aadhaar numbers


preg_match_all($pattern, $text, $matches);

// Count the number of occurrences


$count = count($matches[0]);

return $count;
}

// Example usage:
$text = "The Aadhaar numbers are 1234 5678 9012 and 9876 5432 1098.";
$result = countAadhaarOccurrences($text);

echo "Number of Aadhaar occurrences: " . $result;

?>

Output:
Number of Aadhaar occurrences: 2

<?php

function replacePattern($text, $pattern, $replacement) {


// Use preg_replace to find and replace the specified pattern
$result = preg_replace($pattern, $replacement, $text);

return $result;
}

// Example usage:
$text = "The quick brown fox jumps over the lazy dog.";
$pattern = '/quick brown/';
$replacement = 'swift black';

$result = replacePattern($text, $pattern, $replacement);

echo "Original text: " . $text . "<br>";


echo "Modified text: " . $result;

?>
Output:
Original text: The quick brown fox jumps over the lazy dog.<br>Modified text: The swift black fox jumps over the
lazy dog.
Department of CSE( artificial intelligence & machine learning) 21
.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA

12. Develop a PHP program to read the contents of a HTML form and display the contents on browser.

Steps to Run PHP Program on Ubuntu Localhost

Let’s see the tutorial to run PHP programs on ubuntu localhost.

Step 1: First, We need to install PHP Package in ubuntu using Sudo apt-get install
sudo apt-get install php
Step 2: Make sure the PHP package is installed successfully using the below command.
php –version
Step 3: Now, we can execute the PHP program on ubuntu, We need to replace the default apache page with
our PHP page. To do that run the below command.
sudo mv /var/www/html/index.html /var/www/html/index.back
Step 4: Now write your PHP Script to execute using the below command.
sudo gedit /var/www/html/index.php
Step 5: Save the file using ctrl+s.

Step 6: Now you can run the PHP script by opening any browser and typing ‘http://localhost’
Or You can Enter the below command to open.

xdg-open http://localhost

Program

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<!-- HTML form with POST method -->
<form method='POST'>
<h2>Please input your name:</h2>
<!-- Text input field for the name -->
<input type="text" name="name">
<!-- Submit button to submit the form -->
<input type="submit" value="Submit Name">
</form>
<?php
// Check if the form is submitted and 'name' is set in $_POST
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['name'])) {
// Retrieve name from the form and store it in a local variable
$name = $_POST['name'];
// Display a greeting message with the entered name
echo "<h3> Hello $name </h3>";
}
?>
</body>
</html>

output:
Department of CSE( artificial intelligence & machine learning) 21
.BLDEA’s V P Dr P G H CET, Vijayapur
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING WITH JAVA

Please input your name:


Hello Poornima

Department of CSE( artificial intelligence & machine learning) 21


.BLDEA’s V P Dr P G H CET, Vijayapur

You might also like