0% found this document useful (0 votes)
8 views30 pages

List of Programming Experiments

The document contains a list of 11 experiments related to programming languages and concepts. The experiments include designing a lexical analyzer using flex/lex, studying how a virtual machine works, implementing 2D and 3D arrays in memory, creating a web page in PHP, and using concepts like pointers, exception handling, parameter passing, and inheritance in various languages. For each experiment, a brief overview is provided of the goal and approach. The algorithms, sample code, inputs, and outputs are listed for select experiments to demonstrate how to complete the tasks.

Uploaded by

Rocky Samuel
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)
8 views30 pages

List of Programming Experiments

The document contains a list of 11 experiments related to programming languages and concepts. The experiments include designing a lexical analyzer using flex/lex, studying how a virtual machine works, implementing 2D and 3D arrays in memory, creating a web page in PHP, and using concepts like pointers, exception handling, parameter passing, and inheritance in various languages. For each experiment, a brief overview is provided of the goal and approach. The algorithms, sample code, inputs, and outputs are listed for select experiments to demonstrate how to complete the tasks.

Uploaded by

Rocky Samuel
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

List of Experiments

S. No. Experiment Date Sign.

1 Design of Lexical Analyzer using lex/flex.

2 Case study of working of virtual machine.

3 Memory Implementation of 2D and 3D array.

4 Design a web page in PHP.

5 Implementation of pointers in C++.

6 Write a program in Java to implement exception handling.

Write a program in C++ to implement different parameter passing


7
methods.

Write a program in Java to implement concurrent execution of a job


8
using threads.

9 Implement different types of functions used in Prolog.

10 Implement Inheritance, Encapsulation and Polymorphism in C#.

11 Write a program to find factorial of a number in LISP.


Experiment-01
AIM: Design of lexical Analyzer using lex/flex.
ABOUT THE EXPERIMENT: Flex/Lex is a compiler construction tool that can be used to design a
compiler. In this experiment flex is used to create a sample lexical analyser for c programming language,
it can recognize the valid symbols in c programming language including valid programming constructs.
Lexical analyser reads the characters from source code and converts it into tokens.

ALGORITHM:
Step1: Start.
Step2: Define a function to check the token as a keyword (The number of keywords in C language are
32).
Step3: Define the arithmetic operators in an Array.
Step 4: Open the Source Code in a file in read mode.
Step 5: If file is empty, Exit from Program otherwise goto next step.
Step 6: Fetch each character from file and Check it as keyword, operator, number or identifier, till null
character.
Step 7: Close open file.
Step 8: Stop.

Software Used:Turbo C / Turbo C++

PROGRAM CODE:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>

int isKeyword (char buffer []) {


char keywords [32][10] = {"auto","break","case","char","const","continue","default",
"do","double","else","enum","extern","float","for","goto",
"if","int","long","register","return","short","signed",
"sizeof","static","struct","switch","typedef","union",
"unsigned","void","volatile","while"};
int i, flag = 0;

for (i = 0; i < 32; ++i) {


if(strcmp(keywords[i], buffer) == 0) {
flag = 1;
break;
}
}
return flag;
}

int main () {
char ch, buffer [15], operators [] = "+-*/%=";
FILE *fp;
int i, j=0;

fp = fopen("program.c","r");

if (fp == NULL) {
printf ("error while opening the file\n");
exit (0);
}

while ((ch = fgetc(fp))! = EOF) {


for (i = 0; i < 6; ++i) {
if (ch == operators[i])
printf ("%c is operator\n", ch);
}

if(isalnum(ch)) {
buffer[j++] = ch;
}
else if ((ch == ' ' || ch == '\n') && (j! = 0)) {
buffer[j] = '\0';
j = 0;

if(isKeyword(buffer) == 1)
printf ("%s is keyword\n", buffer);
else
printf ("%s is indentifier\n", buffer);
}
}

fclose(fp);
return 0;
}

Input File (Source Code): The following file “program.c” is created as source file to be used as input
in bin folder of Turbo C++ folder.
#include<stdio.h>
void main ()
{
int a, b;
printf (“Enter Any two numbers”);
scanf (“%d%d”, &a,&b);
printf (“Sum = %d”, a+b);
}
OUTPUT:
Experiment-02
Aim: Case study of working of virtual machine.
ABOUT THE EXPERIMENT: A virtual machine (VM) is an operating system (OS) or application
environment that is installed on software, which imitates dedicated hardware. The end user has the same
experience on a virtual machine as they would have on dedicated hardware.
What is Virtualization?
Virtualization is the process of creating a software-based (or virtual) representation of something rather
than a physical one. Virtualization can apply to applications, servers, storage, and networks and is the
single most effective way to reduce IT expenses while boosting efficiency and agility for all size
businesses.
Benefits of Virtualization
Virtualization can increase IT agility, flexibility, and scalability while creating significant cost savings.
Workloads get deployed faster, performance and availability increases and operations become
automated, resulting in IT that's simpler to manage and less costly to own and operate. Additional
benefits include:
• Reduce capital and operating costs.
• Minimize or eliminate downtime.
• Increase IT productivity, efficiency, agility and responsiveness.
• Provision applications and resources faster.
• Enable business continuity and disaster recovery.
• Simplify data centre management.
• Build a true Software-Defined Data Centre
How Virtualization Works?
At the heart of virtualization is the “virtual machine” (VM), a tightly isolated software container with
an operating system and application inside. Because each virtual machine is completely separate and
independent, many of them can run simultaneously on a single computer. A thin layer of software called
a hypervisor decouples the virtual machines from the host. And it dynamically allocates computing
resources to each virtual machine as needed. This architecture redefines your computing equation and
delivers: • Many applications on each server – Since each virtual machine encapsulates an entire
machine, you can run many applications and operating systems on one physical server at the same time.
• Maximum server utilization, minimum server count – Every physical machine is used to its full
capacity, allowing you to significantly reduce costs by deploying fewer servers overall. • Faster, easier
application and resource provisioning – VMs are self-contained software files that can be manipulated
with copy-and-paste ease. This brings unprecedented simplicity, speed and flexibility to IT provisioning
and management. You can even transfer running VMs from one physical server to another—a process
known as live migration. You can also virtualized business-critical apps to improve performance,
reliability, and scalability while reducing costs.
IT organizations are challenged by the limitations of today’s x86 servers, which are designed to run just
one operating system and application at a time. As a result, even small data centers have to deploy many
servers, each operating at just 5 to 15 percent of capacity—highly inefficient by any
standard. Virtualization uses software to simulate the existence of hardware and create a
virtual computer system. Doing this allows businesses to run more than one virtual system – and
multiple operating systems and applications -- on a single server. This can provide economies of scale
and greater efficiency.

The Virtual Machine


A virtual computer system is known as a “virtual machine” (VM): a tightly isolated software container
with an operating system and application inside. Each self-contained VM is completely independent.
Putting multiple VMs on a single computer enables several operating systems and applications to run
on just one physical server, or “host”.
A thin layer of software called a hypervisor decouples the virtual machines from the host and
dynamically allocates computing resources to each virtual machine as needed.

Key Properties of Virtual Machines


VMs have the following characteristics, which offer several benefits.
Partitioning
• Run multiple operating systems on one physical machine
• Divide system resources between virtual machines
Isolation
• Provide fault and security isolation at the hardware level
• Preserve performance with advanced resource controls
Encapsulation
• Save the entire state of a virtual machine to files
• Move and copy virtual machines as easily as moving and copying files
Hardware Independence
• Provision or migrate any virtual machine to any physical server
Server Consolidation
• Using server virtualization, a company can maximize the use of its server resources and reduce
the number of servers required. The result is server consolidation, which improves efficiency
and cuts costs.
It’s Not Cloud Computing
• Cloud computing is not the same thing as virtualization; rather, it’s something you can do using
virtualization. Cloud computing describes the delivery of shared computing resources (software
and/or data) on demand through the Internet.
Experiment-03
Aim: Memory Implementation of 2D and 3D Array

A. Memory Implementation of 2D Array.

ALGORITHM:
Step1: Start.
Step2: Declare and initialize a 2D Array.
Step3: Print the Memory location and values at specific location in this array. (using Nested for)
Step4: Stop.

Software Used:Turbo C / Turbo C++ /Code Block

PROGRAM CODE:
#include <stdio.h>
void main ()
{
int a [2][3] = {{1, 2, 3}, {4, 5, 6}};
int i, j;
/* Displaying the Memory location and values at specific location of Array */
for (i=0; i<2; ++i)
{
for (j=0; j<3; ++j)
{
printf ("\n Element a[%d] [%d], Memory Location %ld and Value %d “, i, j, &a[i][j], a[i][j]);
}
}
}
OUTPUT:

CONCLUSION: Memory is allocated in row major order.


B. Memory Implementation of 3D Array.

ALGORITHM:
Step1: Start.
Step2: Declare and initialize a 3D Array.
Step3: Print the Memory location and values at specific location in this array. (using Nested for)
Step4: Stop.
Software Used:Turbo C / Turbo C++ / Code Block
PROGRAM CODE:
#include <stdio.h>
void main ()
{
int a [2][2][2] = {{{1, 2}, {3,4}}, {{5, 6}, {7,8}}};
int i, j, k;
/* Displaying the Memory location and values at specific location of Array */
for (i=0; i<2; ++i)
{
for (j=0; j<2; ++j)
{
for (k=0; k<2; ++k)
{
printf ("\n Element a[%d] [%d] [%d], Memory Location %ld and Value %d”, i, j, &a[i][j][k],
a[i][j][k]);
}
}
}
}
OUTPUT:

CONCLUSION: Memory is allocated in row major order.


Experiment-04
Aim: Design a web page in PHP.
ABOUT THE EXPERIMENT: PHP is a server-side scripting language. that is used to develop Static
websites or Dynamic websites or Web applications. PHP stands for Hypertext Pre-processor, that earlier
stood for Personal Home Pages. PHP scripts can only be interpreted on a server that has PHP installed.
The client computers accessing the PHP scripts require a web browser only. A PHP file contains PHP
tags and ends with the extension ".php".

STEPS TO PERFORM EXPERIMENT:


Step 1: Create a file named [Link] and put it in your web server's root directory
(DOCUMENT_ROOT) with the following content:

Our first PHP script: [Link]

<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>

Use your browser to access the file with your web server's URL, ending with the /[Link] file
reference. When developing locally this URL will be something like [Link] or
[Link] but this depends on the web server's configuration. If everything is configured
correctly, this file will be parsed by PHP and its equivalent code in html is as follows:

<html>
<head>
<title>PHP Test</title>
</head>
<body>
<p>Hello World</p>
</body>
</html>
OUTPUT:
Experiment-05
Aim: Implementation of pointers in C++.
ABOUT THE EXPERIMENT: A pointer is a variable whose value is the address of another
variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a
pointer before using it to store any variable address. The general form of a pointer variable declaration
is –
datatype *var_name;
ALGORITHM:
Step1: Start.
Step2: Declare and initialize a variable.
Step3: Declare a pointer variable and store the address of variable in it.
Step4: Print the address of variable, value of variable, value at pointer, address of pointer and value at
address hold by pointer.
Step5: Stop.
Software Used:Turbo C++/ Code Block
PROGRAM CODE:
#include <iostream>
using namespace std;
int main ()
{
int a=10;
int * mypointer;
mypointer = &a;
cout << "\n address of variable a is " << &a;
cout << "\n value of variable a is " << a;
cout << "\n value at pointer mypointer is " << mypointer;
cout << "\n address of pointer mypointer is " << &mypointer;
cout << "'\n value at address hold by pointer mypointer is” <<*mypointer;
return 0;
}
OUTPUT:
Experiment-06

Aim: Write a program in Java to implement exception handling.


Software Used:Java / JCreater
A. Code to handle division by zero exception.
PROGRAM CODE:
import [Link].*;
class Division {
public static void main (String [] args) {
int a, b, result;
Scanner input = new Scanner ([Link]);
[Link]("Input two integers");
a = [Link]();
b = [Link]();
// try block
try {
result = a / b;
[Link]("Result = " + result);
}
// catch block
catch (ArithmeticException e) {
[Link]("Exception caught: Division by zero.");
}
}
}

OUTPUT:

B. Code to handle ArrayIndexOutOfBoundsException


PROGRAM CODE:
import [Link].*;
class Exceptions {
public static void main (String [] args) {
String languages [] = {“C", "C++", "Java", "Perl", "Python”};
try {
for (int c = 1; c <= 5; c++) {
[Link](languages[c]);}
}
catch (Exception e) {
[Link](e);
}
}
}
OUTPUT:

C. Code to implement Finally block in Java


PROGRAM CODE:
import [Link].*;
class Allocate {
public static void main (String [] args) {
try {
long data [] = new long [1000000000];
}
catch (Exception e) {
[Link](e);
}
finally {
[Link]("finally block will execute always.");
}
}
}
OUTPUT:
Experiment-07
Aim: Write a program in C++ to implement different parameter passing Methods.
ABOUT THE EXPERIMENT: The following four types of parameter passing methods defined in
PPL:
o Pass by Value: This method uses in-mode semantics.
o Pass by Result: This method uses out-mode semantics.
o Pass by Value Result: This method uses in-out mode semantics.
o Pass by Reference: This method also uses in-out mode semantics.
C++ supports pass by value, pass by value result as pass by address and pass by reference methods.
Software Used:Turbo C++/ Code Block
A. CODE to implement Pass by Value method.
PROGRAM CODE:
#include <iostream>
using namespace std;
void swap (int a, int b)
{
int t = a;
a = b;
b = t;
cout<<"\n inside function a =” <<a<<”and b =” << b;}
int main ()
{
int x = 5, y = 7;
cout<<” \n Values before calling function swap () x =” <<x<<”and y =” << y;
swap (x, y); //Pass by Value
cout<<” \n Values after return back from function swap () x =” <<x<<”and y =” << y;
return 0;
}
OUTPUT:
B. CODE to implement Pass by Value Result method.

PROGRAM CODE:
#include <iostream>
using namespace std;
void swap (int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
cout<<"\n inside function a =” <<*a<<”and b =” << *b;
}
int main ()
{
int x = 5, y = 7;
cout<<” \n Values before calling function swap () x =” <<x<<”and y =” << y;
swap (&x, &y); //Pass by address
cout<<” \n Values after return back from function swap () x =” <<x<<”and y =” << y;
return 0;
}
OUTPUT:

C. CODE to implement Pass by Reference method.

PROGRAM CODE:
#include <iostream>
using namespace std;
void swap (int &a, int &b)
{
int t = a;
a = b;
b = t;
cout<<"\n inside function a =” <<a<<”and b =” << b;
}
int main ()
{
int x = 5, y = 7;
cout<<” \n Values before calling function swap () x =” <<x<<”and y =” << y;
swap (x, y); //Pass by reference
cout<<” \n Values after return back from function swap () x =” <<x<<”and y =” << y;
return 0;
}
OUTPUT:
Experiment-08
Aim: Write a program in Java to implement concurrent execution of a job using threads.
Software Used:Java / JCreater
A. Create a Thread by Implementing a Runnable Interface
PROGRAM CODE:
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo (String name) {
threadName = name;
[Link]("Creating " + threadName);
}
public void run () {
[Link]("Running " + threadName);
try {
for (int i = 4; i > 0; i--) {
[Link]("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
[Link](50);
}
} catch (InterruptedException e) {
[Link]("Thread " + threadName + " interrupted.");
}
[Link]("Thread " + threadName + " exiting.");
}
public void start () {
[Link]("Starting " + threadName);
if (t == null) {
t = new Thread (this, threadName);
[Link] ();
}
}
}
public class TestThread {
public static void main (String args []) {
RunnableDemo R1 = new RunnableDemo(“Thread-1");
[Link]();
RunnableDemo R2 = new RunnableDemo(“Thread-2");
[Link]();
}
}

OUTPUT:

B. Create a Thread by Extending a Thread Class


PROGRAM CODE:
class ThreadDemo extends Thread {
private String threadName;
ThreadDemo (String name) {
threadName = name;
[Link]("Creating " + threadName);
}

public void run () {


[Link]("Running " + threadName);
try {
for (int i = 4; i > 0; i--) {
[Link]("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
[Link](50);
}
} catch (InterruptedException e) {
[Link]("Thread " + threadName + " interrupted.");
}
[Link]("Thread " + threadName + " exiting.");
}
}
public class TestThread {
public static void main (String args []) {
ThreadDemo T1 = new ThreadDemo(“Thread-1");
T1. start ();
ThreadDemo T2 = new ThreadDemo(“Thread-2");
T2. start ();
}
}

OUTPUT:
Experiment-09
Aim: Implement different types of functions used in Prolog.
ABOUT THE EXPERIMENT: In computer programming language: Declarative languages. Logic
programming languages, of which PROLOG (programming in logic) is the best known, state a
program as a set of logical relations. Prolog is used for pattern matching over natural language parse
trees.
A Prolog program consists of a number of clauses. Each clause is either a fact or a rule. After
a Prolog program is loaded (or consulted) in a Prolog interpreter, users can submit goals or queries,
and the Prolog interpreter will give results (answers) according to the facts and rules.
Some example programs are as follows:
1 Find the last element of a list.
?- my_last(X,[a,b,c,d]).
X=d
2 Find the K'th element of a list.
The first element in the list is number 1.
?- element_at(X,[a,b,c,d,e],3).
X=c
3 Duplicate the elements of a list.
?- dupli([a,b,c,c,d],X).
X = [a,a,b,b,c,c,c,c,d,d]
4. Split a list into two parts; the length of the first part is given.
?- split([a,b,c,d,e,f,g,h,i,k],3,L1,L2).
L1 = [a,b,c]
L2 = [d,e,f,g,h,i,k]
5. Create a list containing all integers within a given range.
?- range(4,9,L).
L = [4,5,6,7,8,9]
6. Determine whether a given integer number is prime.
?- is_prime(7).
Yes
7. Determine the greatest common divisor of two positive integer numbers.
?- gcd(36, 63, G).
G=9
8. Truth tables for logical expressions.
?- table(A,B,and(A,or(A,B))).
true true true
true fail true
fail true fail
fail fail fail
• Program to find factorial in Prolog.
Software Used: Prolog/ Visual Prolog IDE
PROGRAM CODE:
predicates
go
fact(integer,integer)
clauses
go:-
write("Give the no:"),
readint(X),
Z=1,
fact(X,Z).

fact(1,Z):-
write("The result:",Z).

fact(X,Z):-
Y=Z*X,
XX=X-1,
fact(XX,Y).

OUTPUT:
Give the no: 5
The result: 120
Experiment-10
Aim: Implement Inheritance, Encapsulation & Polymorphism in C#.
Software Used: Visual Studio 2015
A. Program to implement Inheritance in C#
PROGRAM CODE:
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
protected double length;
protected double width;
public Rectangle (double l, double w) {
length = l;
width = w;
}
public double GetArea () {
return length * width;
}
public void Display () {
[Link]("Length: {0}", length);
[Link]("Width: {0}", width);
[Link]("Area: {0}", GetArea ());
}
}//end class Rectangle
class Tabletop: Rectangle {
private double cost;
public Tabletop (double l, double w): base (l, w) {}
public double GetCost () {
double cost;
cost = GetArea () * 70;
return cost;
}
public void Display () {
[Link]();
[Link]("Cost: {0}", GetCost ());
}
}
class ExecuteRectangle {
static void Main (string [] args) {
Tabletop t = new Tabletop (4.5, 7.5);
[Link]();
[Link]();
}
}
}
OUTPUT:

B. Programs to implement Encapsulation in C#

Encapsulation is implemented by using access specifiers. An access specifier defines the scope and
visibility of a class member. C# supports the following access specifiers −

• Public
• Private
• Protected
• Internal
• Protected internal
1. Public Access Specifier
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
public double length;
public double width;
public double GetArea () {
return length * width;
}
public void Display () {
[Link]("Length: {0}", length);
[Link]("Width: {0}", width);
[Link]("Area: {0}", GetArea ());
}
}//end class Rectangle
class ExecuteRectangle {
static void Main (string [] args) {
Rectangle r = new Rectangle ();
[Link] = 4.5;
[Link] = 3.5;
[Link]();
[Link]();
}
}
}

OUTPUT:

2. Private Access Specifier


using System;
namespace RectangleApplication {
class Rectangle {
//member variables
private double length;
private double width;
public void Acceptdetails () {
[Link]("Enter Length: ");
length = [Link]([Link]());
[Link]("Enter Width: ");
width = [Link]([Link]());
}
public double GetArea () {
return length * width;
}
public void Display () {
[Link]("Length: {0}", length);
[Link]("Width: {0}", width);
[Link]("Area: {0}", GetArea ());
}
}//end class Rectangle
class ExecuteRectangle {
static void Main (string [] args) {
Rectangle r = new Rectangle ();
[Link]();
[Link]();
[Link]();
}
}
}
OUTPUT:
3. Internal Access Specifier
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
internal double length;
internal double width;
double GetArea () {
return length * width;}
public void Display () {
[Link]("Length: {0}", length);
[Link]("Width: {0}", width);
[Link]("Area: {0}", GetArea ());
}
}//end class Rectangle
class ExecuteRectangle {
static void Main (string [] args) {
Rectangle r = new Rectangle ();
[Link] = 4.5;
[Link] = 3.5;
[Link]();
[Link]();
}
}
}
OUTPUT:
C. Program to implement Polymorphism in C#

Polymorphism can be static or dynamic. In static polymorphism, the response to a function is


determined at the compile time. In dynamic polymorphism, it is decided at run-time.

Static Polymorphism
The mechanism of linking a function with an object during compile time is called early binding. It is
also called static binding. C# provides two techniques to implement static polymorphism function
overloading and Operator overloading.
1- Static Polymorphism (Function Overloading)
using System;
namespace PolymorphismApplication {
class Printdata {
void print (int i) {
[Link]("Printing int: {0}", i);
}
void print (double f) {
[Link]("Printing float: {0}”, f);
}
void print (string s) {
[Link]("Printing string: {0}", s);
}
static void Main (string [] args) {
Printdata p = new Printdata ();

// Call print to print integer


[Link] (5);
// Call print to print float
[Link] (500.263);
// Call print to print string
[Link] ("Hello C++");
[Link]();
}
}
}
OUTPUT:

2- Dynamic Polymorphism
using System;
namespace PolymorphismApplication {
abstract class Shape {
public abstract int area ();
}

class Rectangle: Shape {


private int length;
private int width;

public Rectangle (int a = 0, int b = 0) {


length = a;
width = b;
}
public override int area () {
[Link]("Rectangle class area:");
return (width * length);
}
}
class RectangleTester {
static void Main (string [] args) {
Rectangle r = new Rectangle (10, 7);
double a = [Link]();
[Link]("Area: {0}”, a);
[Link]();
}
}
}

OUTPUT:
Experiment-11
Aim: Write a program to find factorial of a number in LISP.
Software Used: LISP Executer
A. Program to find factorial of a number in LISP.
PROGRAM CODE:
(define (factorial n)
(define (iter product counter)
(if (> counter n)
product
(iter (* counter product) (+ counter 1))
))
(iter 1 1))

(display (factorial 5))

OUTPUT:
120
B. Program to find factorial of a number in LISP using recursion.
PROGRAM CODE:
(define (factorial n)
(if (= n 1)
1
(* n (factorial (- n 1)))
))

(display (factorial 5))

OUTPUT:
120

You might also like