PPL File DHRUV GOEL 44114802717

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

PRINCIPLE OF PROGRAMMING LANGUAGES

LAB

ETCS-458

Faculty Name: Ms. Zameer Fatima Student name: Dhruv Goel

Roll No.: 44114802717

Semester: 8th

Group: C8

Maharaja Agrasen Institute of Technology, PSP Area,

Sector – 22, Rohini, New Delhi – 110085


MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY
VISION
To nurture young minds in a learning environment of high academic value and imbibe spiritual
and ethical values with technological and management competence.

MISSION
The Institute shall endeavour to incorporate the following basic missions in the teaching
methodology:
Engineering Hardware – Software Symbiosis
Practical exercises in all Engineering and Management disciplines shall be carried out by
Hardware equipment as well as the related software enabling deeper understanding of basic
concepts and encouraging inquisitive nature.
Life – Long Learning
The Institute strives to match technological advancements and encourage students to keep
updating their knowledge for enhancing their skills and inculcating their habit of continuous
learning.
Liberalization and Globalization
The Institute endeavour’s to enhance technical and management skills of students so that they
are intellectually capable and competent professionals with Industrial Aptitude to face the
challenges of globalization.
Diversification
Engineering, Technology and Management disciplines have diverse fields of studies with
different attributes. The aim is to create a synergy of the above attributes by encouraging
analytical thinking.
Digitization of Learning Processes
The Institute provides seamless opportunities for innovative learning in all Engineering and
Management disciplines through digitization of learning processes using analysis, synthesis,
simulation, graphics, tutorials and related tools to create a platform for multi-disciplinary
approach.
Entrepreneurship
The Institute strives to develop potential Engineers and Managers by enhancing their skills and
research capabilities so that they become successful entrepreneurs and responsible citizens.
MAHARAJA AGRASEN INSTITUTE OF
TECHNOLOGY

COMPUTER SCIENCE & ENGINEERING DEPARTMENT


VISION
To Produce “Critical thinkers of Innovative Technology”

MISSION
To provide an excellent learning environment across the computer science discipline
to inculcate professional behaviour, strong ethical values, innovative research
capabilities and leadership abilities which enable them to become
successful entrepreneurs in this globalized world.

1. To nurture an excellent learning environment that helps students to enhance


their problem-solving skills and to prepare students to be lifelong learners by
offering a solid theoretical foundation with applied computing experiences
and educating them about their professional, and ethical responsibilities.
2. To establish Industry-Institute Interaction, making students ready for the
industrial environment and being successful in their professional lives.
3. To promote research activities in the emerging areas of technology
convergence.
4. To build engineers who can look into technical aspects of an engineering
solution thereby setting a ground for producing successful entrepreneurs.

PRINCIPLE OF PROGRAMMING LANGUAGES LAB


(ETCS -458)
Lab Assessment Sheet

Student Enrolment No: 44114802717


Student Name: Dhruv Goel

S.No Experiment Marks Signature


Total
with date
Marks
R1 R2 R3 R4 R5

Implement all major functions of


1 string.h in single C program using
switch case to select specific function
from user choice (like strlen, strcat,
strcpy, strcmp, strrev)
Write a program (WAP) in C to
2 reverse a linked list iterative and
recursive.
WAP in C to implement iterative
3 Towers of Hanoi.

WAP in C++ to count the nos. of an


4 object of a class with the help of static
data members, function and
constructor.
WAP in C++ & Java to declare a class
5 Time with data members mm for
minutes, ss for seconds and hh for
hours. Define a parameterized
constructor to assign time to its
objects. Add two-time objects using
member function and assign to third
objects. Implement all possible cases
of time.
WAP in C++ to define a class
6 Complex to represent a set of all
complex numbers. Overload ‘+’
operator to add two complex numbers
using member function of the class and
overload ‘*’ operator to multiply two
complex numbers using the friend
function of the class complex.
Write a program to display 10
7 questions at random out of exp.8-50
questions (do not display the answer of
these questions to the user now).
Implement producer-consumer
8 problem using threads

There are 200 questions on a 3hr


9 examination. Among these questions
are 50 mathematics problems. It is
suggested that twice as much time be
spent on each maths problem as for
each other's questions. WAP which
calculates how many minutes should
be spent on mathematics problems.
User enters the elements in a m x n
10 matrix, where m is the number of rows
and n is the number of columns.
Values of m and n are also entered by
the user. Now WAP in C and JAVA
which find out the position of the
element which is smallest in the row
and largest in the column.

Overall Comments:

Faculty Name: Ms. Zameer Fatima


Signature:
EXPERIMENT NO. 1
AIM: - Implement all major functions of string.h in single C program using switch case to
select specific function from user choice (like strlen, strcat, strcpy, strcmp, strrev)

CODE: -

#include<stdio.h>
#include<string.h>
void main(){
char str[50];
char temp[20];
char choice, ch;
//printf("For ")
puts("To get the length of string, choose 'L'."); //strlen();//
puts("To convert the whole string in lower case, choose 'l'."); //strlwr();
puts("To convert the whole string in upper case, choose 'U'."); //strupr();
puts("To append a string behind other, choose 'A'."); //strcat();//
puts("To copy a string into another, choose 'c'."); //strcpy();//
puts("To compare two strings, choose 'C'."); //strcmp();//
puts("To find out first ocurence of given character in a string, choose 'O'"); //strchr();
puts("To find out first ocurence of given string in another string, choose 'S'");
//strstr();
puts("To reverse the string, choose 'R'"); //strrev();//
printf("\nEnter Your Choice: ");
scanf("%c", &choice);
switch(choice){
case 'L':
printf("\nEnter The String To Get Its Length: ");
scanf("%s", str);
printf("The Length Of The Entered String Is: %d", strlen(str));
break;
case 'l':
printf("\nEnter The String To Convert It Into Lower Case : ");
scanf("%s", str);
printf("The Entered String In Lowercase: %s", strlwr(str));
break;
case 'U':
printf("\nEnter The String To Convert It Into Upper Case : ");
scanf("%s", str);
printf("\nThe Entered String In Lowercase: %s", strupr(str));
break;
case 'A':
printf("\nEnter The First String: ");
scanf("%s", str);
printf("Enter The Second String To Append It Behind First One: ");
scanf("%s", temp);
strcat(str, temp);
printf("\nNow, The First String Is: %s", str);
break;
case 'c':
printf("\nEnter The First String: ");
scanf("%s", str);
printf("Enter The Second String: ");
scanf("%s", temp);
strcpy(str, temp);
printf("\nNow, The First String Is: %s", str);
printf("\nAnd, The Second String Is: %s", temp);
break;
case 'C':
printf("\nEnter The First String: ");
scanf("%s", str);
printf("Enter The Second String: ");
scanf("%s", temp);
if(strcmp(str, temp)==0)printf("\nBoth Strings Are Similar.");
else printf("\nBoth Strings Are Different.");
break;
case 'O':
printf("\nEnter The String: ");
scanf("%s", str);
printf("Enter The Character To Be Searched: ");
scanf("%c", &ch);
printf("\nThe First Occurence of Character Is At: %s", strchr(str, ch));
break;
case 'S':
printf("\nEnter The String: ");
scanf("%s", str);
printf("Enter The String To Be Searched: ");
scanf("%s", temp);
printf("\nThe First Occurence of Character Is At: %s", strstr(str,
temp));
break;
case 'R':
printf("\nEnter The String To Get Its Reverse: ");
scanf("%s", str);
printf("\nThe Reverse Of The Entered String Is: %s", strrev(str));
break;
default:
printf("\nYou Entered A Wrong Choise.");
break;
}

}
OUTPUT
EXPERIMENT NO. 2
AIM: - Write a program (WAP) in C to reverse a linked list iterative and recursive.

CODE: -

// Iterative C program to reverse a linked list


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

/* Link list node */


struct Node
{
int data;
struct Node* next;
};

/* Function to reverse the linked list */


void recursiveReverse(struct Node* head, struct Node** headRef)
{
struct Node* first;
struct Node* rest;
// empty list base case
if (head == NULL)
return;

first = head; // suppose first = {1, 2, 3}


rest = first->next; // rest = {2, 3}

// base case: List has only one node


if (rest == NULL)
{
// fix the head pointer here
*headRef = first;
return;
}

// Recursively reverse the smaller {2, 3} case


// after: rest = {3, 2}
recursiveReverse(rest, headRef);

// put the first elem on the end of the list


rest->next = first;
first->next = NULL; // (tricky step -- make a drawing)
}
void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next = NULL;
printf("\n\nReversing Linked List Ittereatively...\n");
while (current != NULL)
{
// Store next
next = current->next;

// Reverse current node's pointer


current->next = prev;

// Move pointers one position ahead.


prev = current;
current = next;
}
*head_ref = prev;
}

/* Function to push a node */


void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}

/* Function to print linked list */


void printList(struct Node *head)
{
struct Node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}

int main()
{
/* Start with the empty list */
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);

printf("Given linked list\n");


printList(head);

//reverse(&head);
printf("\n\nReversing LinkedList Recursivly....\n");
recursiveReverse(head, &head);

printf("\nReversed Linked list \n");


printList(head);
getchar();
}

OUTPUT: -
EXPERIMENT NO. 3
AIM: - WAP in C to implement iterative Towers of Hanoi.

CODE: -

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>

// A structure to represent a stack


struct Stack
{
unsigned capacity;
int top;
int *array;
};

// function to create a stack of given capacity.


struct Stack* createStack(unsigned capacity)
{
struct Stack* stack =
(struct Stack*) malloc(sizeof(struct Stack));
stack -> capacity = capacity;
stack -> top = -1;
stack -> array =
(int*) malloc(stack -> capacity * sizeof(int));
return stack;
}

// Stack is full when top is equal to the last index


int isFull(struct Stack* stack)
{
return (stack->top == stack->capacity - 1);
}

// Stack is empty when top is equal to -1


int isEmpty(struct Stack* stack)
{
return (stack->top == -1);
}

// Function to add an item to stack. It increases


// top by 1
void push(struct Stack *stack, int item)
{
if (isFull(stack))
return;
stack -> array[++stack -> top] = item;
}

// Function to remove an item from stack. It


// decreases top by 1
int pop(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack -> array[stack -> top--];
}

//Function to show the movement of disks


void moveDisk(char fromPeg, char toPeg, int disk)
{
printf("Move the disk %d from \'%c\' to \'%c\'\n",
disk, fromPeg, toPeg);
}

// Function to implement legal movement between


// two poles
void moveDisksBetweenTwoPoles(struct Stack *src,
struct Stack *dest, char s, char d)
{
int pole1TopDisk = pop(src);
int pole2TopDisk = pop(dest);

// When pole 1 is empty


if (pole1TopDisk == INT_MIN)
{
push(src, pole2TopDisk);
moveDisk(d, s, pole2TopDisk);
}

// When pole2 pole is empty


else if (pole2TopDisk == INT_MIN)
{
push(dest, pole1TopDisk);
moveDisk(s, d, pole1TopDisk);
}

// When top disk of pole1 > top disk of pole2


else if (pole1TopDisk > pole2TopDisk)
{
push(src, pole1TopDisk);
push(src, pole2TopDisk);
moveDisk(d, s, pole2TopDisk);
}

// When top disk of pole1 < top disk of pole2


else
{
push(dest, pole2TopDisk);
push(dest, pole1TopDisk);
moveDisk(s, d, pole1TopDisk);
}
}

//Function to implement TOH puzzle


void tohIterative(int num_of_disks, struct Stack
*src, struct Stack *aux,
struct Stack *dest)
{
int i, total_num_of_moves;
char s = 'S', d = 'D', a = 'A';

//If number of disks is even, then interchange


//destination pole and auxiliary pole
if (num_of_disks % 2 == 0)
{
char temp = d;
d = a;
a = temp;
}
total_num_of_moves = pow(2, num_of_disks) - 1;

//Larger disks will be pushed first


for (i = num_of_disks; i >= 1; i--)
push(src, i);

for (i = 1; i <= total_num_of_moves; i++)


{
if (i % 3 == 1)
moveDisksBetweenTwoPoles(src, dest, s, d);

else if (i % 3 == 2)
moveDisksBetweenTwoPoles(src, aux, s, a);

else if (i % 3 == 0)
moveDisksBetweenTwoPoles(aux, dest, a, d);
}
}

// Driver Program
int main()
{
// Input: number of disks
unsigned num_of_disks = 3;

struct Stack *src, *dest, *aux;


// Create three stacks of size 'num_of_disks'
// to hold the disks
src = createStack(num_of_disks);
aux = createStack(num_of_disks);
dest = createStack(num_of_disks);

tohIterative(num_of_disks, src, aux, dest);


return 0;
}

OUTPUT: -
EXPERIMENT NO. 4
AIM: - WAP in C++ to count the nos. of an object of a class with the help of static data
members, function and constructor.

CODE: -

#include <iostream>
using namespace std;

class Counter
{
private:
//static data member as count
static int count;

public:
//default constructor
Counter()
{ count++; }
//static member function
static void Print()
{
cout<<"\nTotal objects are: "<<count;
}
};

//count initialization with 0


int Counter :: count = 0;

int main()
{
Counter OB1;
OB1.Print();

Counter OB2;
OB2.Print();

Counter OB3;
OB3.Print();

return 0;
}
OUTPUT: -
EXPERIMENT NO. 5
AIM: - WAP in C++ & Java to declare a class Time with data members mm for minutes, ss
for seconds and hh for hours. Define a parameterized constructor to assign time to its objects.
Add two-time objects using member function and assign to third objects. Implement all
possible cases of time.

CODE: -

#include<iostream>
using namespace std;
class Time
{
int hh,mm,ss;
public:
Time(){}
Time(int hh, int mm, int ss)
{
this->hh=hh;
this->mm=mm;
this->ss=ss;
}
void disp()
{
cout<<hh<<":"<<mm<<":"<<ss;

}
void sum(Time t1,Time t2)
{
ss=t1.ss+t2.ss;
mm=ss/60;
ss=ss%60;
mm=mm+t1.mm+t2.mm;
hh=mm/60;
mm=mm%60;
hh=hh+t1.hh+t2.hh;
}

};
int main(){
Time t1(2,22,34);
cout<<"The Time T1 Is: ";
t1.disp();
Time t2(4, 33, 50);
cout<<"\n\nThe Time T2 Is: ";
t2.disp();
Time t3;
t3.sum(t1,t2);
cout<<"\n\nThe Resultant Time Is: ";
t3.disp();
}

OUTPUT: -
EXPERIMENT NO. 6
AIM: - WAP in C++ to define a class Complex to represent a set of all complex numbers.
Overload ‘+’ operator to add two complex numbers using member function of the class and
overload ‘*’ operator to multiply two complex numbers using the friend function of the class
complex.

CODE: -

#include<iostream>
using namespace std;

class Complex
{
int real,img;
public:
Complex(){};
Complex(int i,int j)
{
real=i;
img=j;

}
void show()
{
cout<<real<<" + i"<<img;
}
Complex operator +(Complex obj){
Complex temp;
temp.real=real+obj.real;
temp.img=img+obj.img;
return(temp);
}
Complex operator *(Complex);
};
Complex Complex::operator *(Complex c)
{
double real1,real2;
real1=real;
real2=c.real;
real=(real*c.real)-(img*c.img);
img=(real1*c.img)+(img*real2);
Complex temp;
temp.real=real;
temp.img=img;
return temp;
}
int main()
{
Complex c1(5,6), c2(7,8), c3, c4;
cout<<"The 1st no. is: ";
c1.show();
cout<<"\n\nThe 2nd no. is: ";
c2.show();
c3=c1+c2;
cout<<"\n\nSum is: ";
c3.show();
c4=c1*c2;
cout<<"\n\nMultiplication is: ";
c4.show();
}

OUTPUT: -
EXPERIMENT NO. 7
AIM: - Write a program to display 10 questions at random out of exp.8-50 questions (do not
display the answer of these questions to the user now).

CODE: -
import csv
quiz_dic={}
i=1
with open('output.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print("\nQue#%d: "%i, end="")
print(row['Questions'])
i=i+1

OUTPUT: -
EXPERIMENT NO. 8
AIM: - Implement producer-consumer problem using threads.

CODE: -
import java.util.LinkedList;
public class Threadexample
{
public static void main(String[] args)
throws InterruptedException
{
final PC pc = new PC();
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
public static class PC
{
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
public void produce() throws InterruptedException
{
int value = 0;
while (true)
{
synchronized (this)
{
while (list.size()==capacity)
wait();
System.out.println("Producer produced-"
+
value);
list.add(value++);
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException
{
while (true)
{
synchronized (this)
{
while (list.size()==0)
wait();
int val = list.removeFirst();
System.out.println("Consumer consumed-"

+ val);
notify();
Thread.sleep(1000);
}
}
}
}
}

OUTPUT: -
EXPERIMENT NO. 9
AIM: - There are 200 questions on a 3hr examination. Among these questions are 50
mathematics problems. It is suggested that twice as much time be spent on each maths problem
as for each other's questions. WAP which calculates how many minutes should be spent on
mathematics problems.

CODE: -
public class Program1 {

public static void main(String[] args) {


final int time= 3*60*60;
int mathsQues= 50, ques= 150, t;
t= time/(ques + 2*mathsQues);
System.out.println("Time for mathematics= "+(mathsQues*2*t)/60 + " minutes");

OUTPUT: -
EXPERIMENT NO. 10
AIM: - User enters the elements in a m x n matrix, where m is the number of rows and n is
the number of columns. Values of m and n are also entered by the user. Now WAP in C and
JAVA which find out the position of the element which is smallest in the row and largest in
the column.
CODE: -

import java.util.Scanner;

public class Program2 {

public static void main(String[] args) {


int m,n;
System.out.println("Enter no. of rows:");
Scanner sc= new Scanner(System.in);
m= sc.nextInt();
System.out.println("Enter no. of columns:");
n= sc.nextInt();
int A[][]= new int[m][n];
System.out.println("Enter the matrix elements:");
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
A[i][j]= sc.nextInt();
}
}
int X=0,y=0,min=100,max=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(min>A[i][j]){
min=A[i][j];
y=j;
}
}
System.out.println("index of smallest element in "+i+" row is: "+y);
}
for(int j=0;j<m;j++){
for(int i=0;i<n;i++){
if(max<A[i][j]){
max=A[i][j];
X=i;
}
}
System.out.println("index of largest element in "+j+" column is: "+X);
}

}
}

OUTPUT: -

You might also like