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

HMR

INSTITUTE OF TECHNOLOGY &


MANAGEMENT
HAMIDPUR, DELHI 110036
Affiliated to
GURU GOBIND SINGH INDRAPRASTHA
UNIVERSITY
Sector - 16C Dwarka, Delhi - 110075, India

Laboratory File

PRINCIPLES OF PROGRAMMING
LANGUAGES LAB
Paper Code- ETCS-458

Bachelor of Technology
In
Computer Science & Engineering
2020-2024

Submitted to Submitted by
Ms.Gurpreet Kaur Peeyush Kumar Singh
Asstt. Professor CSE 8B
CSE Department 05513302720
LIST OF EXPERIMENTS

S.No. Experiment Performed Checked Signature


on on
1 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)
2 Write a program (WAP) in C to reverse a linked list
iterative and recursive.
3 WAP in C to implement iterative Towers of Hanoi.

4 WAP in C++ to count the no.s of object of a class with the


help of static data member, funtion and constructor.
5 WAP in C++ & Java to declare a class Time with data
members mm for minutes, ss for seconds and hh for hours.
Define a parameterize 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.
6 WAP in C++ to define a class Complex to represents 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 friend function of the class complex.
7 Implement simple multi-threaded server to perform all
mathematics operation parallel in Java.
8 Write a program in to prepare a list of 50 questions and
their answers.
9 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).
10 Implement producer-consumer problem using threads.
Experiment 1
Aim – To 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 <stdlib.h>
#include<string.h>

int main()
{
int ch;
char s1[50],s2[50],c;
do
{
system("cls");
printf("\n\n Program to implement major functions of string.h");
printf("\n ^^^^^^^ ^^ ^^^^^^^^^ ^^^^^ ^^^^^^^^^ ^^ ^^^^^^^^");
printf("\n\n 1. Strlen");
printf("\n\n 2. Strcat");
printf("\n\n 3. Strcpy");
printf("\n\n 4. Strcmp");
printf("\n\n 5. Strrev");
printf("\n\n Enter your choice:- ");
scanf("%d",&ch);
fflush(stdin);
switch(ch)
{
case 1:
printf("\n\n Enter a string (max length - 50) : ");
gets(s1);
printf("\n Length of string '%s' is %d",s1,strlen(s1));
break;
case 2:
printf("\n\n Enter first string (max length - 50) : ");
gets(s1);
printf("\n\n Enter second string (max length - 50) : ");
gets(s2);
printf("\n After concatenation, Result = %s",strcat(s1,s2));
break;
case 3:
printf("\n\n Enter first string (max length - 50) : ");
gets(s1);
printf("\n\n Enter second string (max length - 50) : ");
gets(s2);
printf("\n After copying second string into first:-");
strcpy(s1,s2);
printf("\n\n First String = %s",s1);
printf("\n\n Second String = %s",s2);
break;
case 4:
printf("\n\n Enter first string (max length - 50) : ");
gets(s1);
printf("\n\n Enter second string (max length - 50) : ");
gets(s2);
if(strcmp(s1,s2)==0)
{
printf("\n\n Both strings are equal");
}
else
{
printf("\n\n Both strings are not equal");
}
break;
case 5:
printf("\n\n Enter a string (max length - 50) : ");
gets(s1);
char s[50];
strcpy(s,s1);
printf("\n Reverse of string '%s' is %s",s,strrev(s1));
break;
default:
printf("\n Wrong choice");
break;
};
printf("\n\n Do you want to continue ? (y/n) : ");
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
return 0;
}
Output –
Experiment 2
Aim – Write a program (WAP) in C to reverse a linked list iterative and recursive.

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

typedef struct node


{
int i;
struct node *next;
}node1;

void reverselinkedlist(node1 *head)


{
if(head->next==NULL)
{
printf("%d->",head->i);
}
else
{
reverselinkedlist(head->next);
printf("%d->",head->i);
}
}

int main()
{
char hh;
do
{
char ch;
node1 *head=NULL,*tail=NULL;
do
{
system("cls");
printf("\n\n Program to reverse a linked list (Iterative and Recursive)");
printf("\n ^^^^^^^ ^^ ^^^^^^^ ^ ^^^^^^ ^^^^ ^^^^^^^^^^ ^^^ ^^^^^^^^^^");
printf("\n\n Creating linked list...");
printf("\n\n Enter an integer - ");
if(head==NULL)
{
head = malloc(sizeof(node1));
scanf("%d",&head->i);
head->next=NULL;
tail = head;
}
else
{
node1 *n1 = malloc(sizeof(node1));
scanf("%d",&n1->i);
n1->next=NULL;
tail->next=n1;
tail=n1;
}
printf("\n Linked list is - \n\n");
node1 *n2=head;
printf(" ");
while(n2!=NULL)
{
printf("%d->",n2->i);
n2 = n2->next;
}
printf("null");
printf("\n\n Do you want to enter more elements in the list (y/n) ? ");
fflush(stdin);
scanf("%c",&ch);
}while(ch=='y'||ch=='Y');
char ch1;
do
{
int choice;
system("cls");
printf("\n\n Entered Linked List is -");
node1 *n2=head;
printf(" ");
while(n2!=NULL)
{
printf("%d->",n2->i);
n2 = n2->next;
}
printf("null");
printf("\n\n 1. Reverse a linked list iteratively");
printf("\n\n 2. Reverse a linked list recursively");
printf("\n\n Enter your choice - ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("");
node1 *n2 = head;
node1 *c,*chead=NULL;
while(n2!=NULL)
{
c = malloc(sizeof(node1));
c->i = n2->i;
if(chead==NULL)
{
c->next = NULL;
chead = c;
}
else
{
c->next = chead;
chead = c;
}
n2 = n2->next;
}
node1 *x = chead;
printf("\n Reversed linked list is : ");
while(x!=NULL)
{
printf("%d->",x->i);
x=x->next;
}
printf("null");
break;
case 2:
printf("\n Reversed linked list is : ");
reverselinkedlist(head);
printf("null");
break;
default:
printf("\n Wrong choice");
break;
}
printf("\n\n Do you want to reverse linked list again using a different choice (y/n) ? ");
fflush(stdin);
scanf("%c",&ch1);
}while((ch1=='Y')||(ch1=='y'));
printf("\n Do you want to run program again (y/n) ? ");
fflush(stdin);
scanf("%c",&hh);
}while((hh=='y')||(hh=='Y'));
return 0;
}
Output –
Experiment 3
Aim – Write a Program in C to implement iterative Towers of Hanoi

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

typedef struct stack


{
int top;
int limit;
int *array;
}mystack;

void push(mystack *s,int i)


{
if(s->top==s->limit-1)
{
return;
}
else
{
s->array[++s->top]=i;
}
}

int pop(mystack *s)


{
if(s->top==-1)
{
return INT_MIN;
}
else
{
return s->array[s->top--];
}
}

void move(mystack *s1,mystack *s2,char s,char d)


{
int p = pop(s1);
int q = pop(s2);
if(p==INT_MIN)
{
push(s1,q);
printmoveresult(q,d,s);
}
else if(q==INT_MIN)
{
push(s2,p);
printmoveresult(p,s,d);
}
else if(p>q)
{
push(s1,p);
push(s1,q);
printmoveresult(q,d,s);
}
else
{
push(s2,q);
push(s2,p);
printmoveresult(p,s,d);
}
}

void printmoveresult(int disk,char a,char b)


{
printf("\n Move the disk %d from %c to %c",disk,a,b);
}

mystack *createstack(int limit)


{
mystack *s = (mystack *)malloc(sizeof(mystack));
s->top=-1;
s->limit=limit;
s->array = (int *)malloc(limit*sizeof(int));
return s;
}

int main()
{
int nod,nom,i;
mystack *a,*b,*c;
char d1='A',d2='B',d3='C',ch;
do
{
system("cls");
printf("\n\n Program to implement Tower of Hanoi Algorithm iteratively");
printf("\n ^^^^^^^ ^^ ^^^^^^^^^ ^^^^^ ^^ ^^^^^ ^^^^^^^^^ ^^^^^^^^^^^");
printf("\n\n We have 3 stands A, B and C and we are considering that initially all the rings are
in stand A and\n our target is to move all rings from A to C using B as an auxiliary ring stand. \
n\n Enter the number of disks - ");
scanf("%d",&nod);
a = createstack(nod);
b = createstack(nod);
c = createstack(nod);
for(i=nod;i>=1;i--)
{
push(a,i);
}
if(nod%2==0)
{
d2='C';
d3='B';
}
nom = pow(2,nod)-1;
printf("\n Steps to be followed :- \n");
for(i=1;i<=nom;i++)
{
if(i%3==1)
{
move(a,c,d1,d3);
}
else if(i%3==2)
{
move(a,b,d1,d2);
}
else if(i%3==0)
{
move(b,c,d2,d3);
}
}
printf("\n\n Total no. of moves = %d",nom);
printf("\n\n Do you want to continue (y/n) ? ");
fflush(stdin);
scanf("%c",&ch);
}while((ch=='y')||(ch=='Y'));
return 0;
}
Output –
Experiment 4
Aim – Write a Program in C++ to count the no.s of object of a class with the help of static data
member, funtion and constructor

Code –
#include <iostream>

using namespace std;

class A
{
static int t,l;
public:
A()
{
l++;
t++;
}
~A()
{
l--;
}
static void display()
{
cout<<"\n\n Total no. of objects made till now = "<<t;
cout<<"\n\n Total no. of live objects = "<<l;
}
};

int A::t=0;
int A::l=0;

int main()
{
cout<<"\n\n Program to count no. of objects of a class using static data member, function and
constructor";
cout<<"\n ^^^^^^^ ^^ ^^^^^ ^^^ ^^ ^^^^^^^ ^^ ^ ^^^^^ ^^^^^ ^^^^^^ ^^^^ ^^^^^^^ ^^^^^^^^
^^^ ^^^^^^^^^^^";
cout<<"\n\n Without any object....";
A::display();
{
A a1;
cout<<"\n\n One object made....";
A::display();
}
cout<<"\n\n Object destroyed....";
A::display();
cout<<"\n";
return 0;
}
Output –
Experiment 5
Aim – Write a Program in C++ & Java to declare a class Time with data members mm for
minutes, ss for seconds and hh for hours. Define a parameterize 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>
#include<stdlib.h>

using namespace std;

class Time
{
int hh,mm,ss;
public:
Time(int hh,int mm,int ss)
{
this->hh = hh;
this->mm = mm;
this->ss = ss;
}
int gethh()
{
return hh;
}
int getmm()
{
return mm;
}
int getss()
{
return ss;
}
Time add(Time t)
{
int h1 = this->hh+t.gethh();
int m1 = this->mm+t.getmm();
int s1 = this->ss+t.getss();
if(s1>=60)
{
m1 = m1 + (s1/60);
s1 = s1%60;
}
if(m1>=60)
{
h1 = h1 + (m1/60);
m1 = m1%60;
}
Time t1(h1,m1,s1);
return t1;
}
void display()
{
cout<<"\n After addition:- ";
cout<<"\n\n Total Hours: "<<hh;
cout<<"\n Total Minutes: "<<mm;
cout<<"\n Total Seconds: "<<ss;
}
};
int main()
{
char ch;
do
{
int h,m,s;
system("cls");
cout<<"\n\n Program to create a class Time with a parameterized constructor for initialization
and\n ^^^^^^^ ^^ ^^^^^^ ^ ^^^^^ ^^^^ ^^^^ ^ ^^^^^^^^^^^^^ ^^^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^
^^^\n assign addition of 2 objects of Class Time to third object using member function\n ^^^^^^
^^^^^^^^ ^^ ^ ^^^^^^^ ^^ ^^^^^ ^^^^ ^^ ^^^^^ ^^^^^^ ^^^^^ ^^^^^^ ^^^^^^^^";
cout<<"\n\n Enter time for first object...";
cout<<"\n\n Hours:";
cin>>h;
cout<<" Minutes:";
cin>>m;
cout<<" Seconds:";
cin>>s;
Time t1(h,m,s);
cout<<"\n Enter time for second object...";
cout<<"\n\n Hours:";
cin>>h;
cout<<" Minutes:";
cin>>m;
cout<<" Seconds:";
cin>>s;
Time t2(h,m,s);
Time t3 = t1.add(t2);
t3.display();
cout<<"\n\n Do you want to continue (y/n) ?";
cin>>ch;
}while((ch=='y')||(ch=='Y'));
return 0;
}
Output –
Experiment 6
Aim – Write a Program in C++ to define a class Complex to represents 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 friend function of the
class complex.
Code –
#include<iostream>
#include<stdlib.h>
#include<stdio.h>

using namespace std;

class Complex
{
int real,imaginary;
public:
Complex(int r,int i)
{
real = r;
imaginary = i;
}
int getreal()
{
return real;
}
int getimaginary()
{
return imaginary;
}
operator+(Complex c1)
{
real = real+c1.getreal();
imaginary = imaginary+c1.getimaginary();
}
void display()
{
cout<<real<<"+"<<imaginary<<"i";
}
friend Complex operator *(Complex c1, Complex c2)
{
Complex c3(0,0);
c3.real = (c1.real*c2.real)-(c1.imaginary*c2.imaginary);
c3.imaginary = (c1.real*c2.imaginary)+(c1.imaginary*c2.real);
return c3;
}
};
int main()
{
char ch;
do
{
int i;
system("cls");
cout<<"\n\n Program to define a class complex and overload + operator as member function
and friend function *\n ^^^^^^^ ^^ ^^^^^^ ^ ^^^^^ ^^^^^^^ ^^^ ^^^^^^^^ ^ ^^^^^^^^ ^^ ^^^^^^
^^^^^^^^ ^^^ ^^^^^^ ^^^^^^^^ ^\n to perform addition and multiplication of complex numbers
entered\n ^^ ^^^^^^^ ^^^^^^^^ ^^^ ^^^^^^^^^^^^^^ ^^ ^^^^^^^ ^^^^^^^ ^^^^^^^";
int real,imaginary;
cout<<"\n\n Enter real and imaginary parts of first complex number :- ";
cin>>real>>imaginary;
Complex c1(real,imaginary);
cout<<"\n Enter real and imaginary parts of second complex number :- ";
cin>>real>>imaginary;
Complex c2(real,imaginary);
cout<<"\n 1. Addition";
cout<<"\n\n 2. Multiplication";
cout<<"\n\n Enter your choice :- ";
cin>>i;
fflush(stdin);
if(i==1)
{
c1+c2;
cout<<"\n After addition of both complex numbers using member function of first one....";
cout<<"\n\n First Complex Number:- ";
c1.display();
cout<<"\n\n Second Complex Number:- ";
c2.display();
}
else if(i==2)
{
Complex c3 = c1*c2;
cout<<"\n After multiplication of both complex numbers using member function of first
one....";
cout<<"\n\n First Complex Number:- ";
c1.display();
cout<<"\n\n Second Complex Number:- ";
c2.display();
cout<<"\n\n Third Complex Number:- ";
c3.display();
}
else
{
cout<<"\n\n Wrong Choice";
}
cout<<"\n\n Do you want to continue (y/n) ? ";
cin>>ch;
}while((ch=='y')||(ch=='Y'));
return 0;
}
Output –

.
Experiment 7
Aim – Implement simple multi-threaded server to perform all mathematics operation parallel in
Java.

Code –
Server Program :
import java.io.*;
import java.net.*;

public class Server1 {

public static void main(String args[]) {


int port = 6789;
Server1 server = new Server1( port );
server.startServer();
}

// declare a server socket and a client socket for the server

ServerSocket echoServer = null;


Socket clientSocket = null;
int port;

public Server1( int port ) {


this.port = port;
}

public void stopServer() {


System.out.println( "Server cleaning up." );
System.exit(0);
}

public void startServer() {


// Try to open a server socket on the given port
// Note that we can't choose a port less than 1024 if we are not
// privileged users (root)

try {
echoServer = new ServerSocket(port);
}
catch (IOException e) {
System.out.println(e);
}

System.out.println( "Waiting for connections....\n" );

// Create a socket object from the ServerSocket to listen and accept connections.
// Use Server1Connection to process the connection.

while ( true ) {
try {
clientSocket = echoServer.accept();
new Thread(new Server1Connection(clientSocket, this)).start();
}
catch (IOException e) {
System.out.println(e);
}
}
}

class Server1Connection implements Runnable{


BufferedReader is;
PrintStream os;
Socket clientSocket;
Server1 server;

public Server1Connection(Socket clientSocket, Server1 server) {


this.clientSocket = clientSocket;
this.server = server;
System.out.println("Connection established with a Client");
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}

public void run() {


String line;
try {
boolean serverStop = false;

while (true) {
line = is.readLine();
// System.out.println( "Received " + line );
int n = Integer.parseInt(line);
if ( n == 6 ) {
System.out.println("Disconnecting from Clients and Stopping Server");
serverStop = true;
break;
}
if ( n == 5 ) {
System.out.println("Disconnecting from Client");
break;
}
if(n==1)
{
System.out.println(" Doing Addition...");
//os.println("" + n*n );
int first = Integer.parseInt(is.readLine());
int second =Integer.parseInt(is.readLine());
os.println("sum");
os.println(""+String.valueOf(first+second));
}
else if(n==2)
{
System.out.println(" Doing Subtraction...");
int first = Integer.parseInt(is.readLine());
int second =Integer.parseInt(is.readLine());
os.println("sub");
os.println(""+String.valueOf(first-second));
}
else if(n==3)
{
System.out.println(" Doing Multiplication...");
int first = Integer.parseInt(is.readLine());
int second =Integer.parseInt(is.readLine());
os.println("mul");
os.println(""+String.valueOf(first*second));
}
else if(n==4)
{
System.out.println(" Doing Division...");
int first = Integer.parseInt(is.readLine());
int second =Integer.parseInt(is.readLine());
os.println("div");
os.println(""+String.valueOf(first/second));
}
else
{
os.println("Wrong");
System.out.println(" Wrong option choosed by Client");
}
}

System.out.println( "Connection closed." );


is.close();
os.close();
clientSocket.close();

if ( serverStop ) server.stopServer();
} catch (IOException e) {
System.out.println(e);
}
}
}
Client Program :
import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) {

String hostname = "localhost";


int port = 6789;

// declaration section:
// clientSocket: our client socket
// os: output stream
// is: input stream

Socket clientSocket = null;


DataOutputStream os = null;
BufferedReader is = null;

// Initialization section:
// Try to open a socket on the given port
// Try to open input and output streams

try {
clientSocket = new Socket(hostname, port);
os = new DataOutputStream(clientSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + hostname);
}

// If everything has been initialized then we want to write some data


// to the socket we have opened a connection to on the given port

if (clientSocket == null || os == null || is == null) {


System.err.println( "Something is wrong. One variable is null." );
return;
}

try {
while ( true ) {
//Runtime.getRuntime().exec("cls");
try
{
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
catch(Exception e)
{
}
System.out.println("\n Calculator");
System.out.println(" ^^^^^^^^^^");
System.out.println("\n 1.Add");
System.out.println(" 2.Subtract");
System.out.println(" 3.Multiply");
System.out.println(" 4.Divide");
System.out.println(" 5.Disconnect from server");
System.out.println(" 6.Disconnect and stop server");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String keyboardInput = br.readLine();
os.writeBytes( keyboardInput + "\n" );

int n = Integer.parseInt( keyboardInput );


if ( n == 5 || n == 6 ) {
break;
}
else if(n==1||n==2||n==3||n==4)
{
System.out.println(" Enter A = ");
String first = br.readLine();
System.out.println(" Enter B = ");
String second = br.readLine();
os.writeBytes(first+"\n");
os.writeBytes(second+"\n");
}

String responseLine = is.readLine();


if(responseLine.equals("sum"))
{
String result = is.readLine();
System.out.println(" A+B = "+result);
}
else if(responseLine.equals("sub"))
{
String result = is.readLine();
System.out.println(" A-B = "+result);
}
else if(responseLine.equals("mul"))
{
String result = is.readLine();
System.out.println(" A*B = "+result);
}
else if(responseLine.equals("div"))
{
String result = is.readLine();
System.out.println(" A/B = "+result);
}
else
{
System.out.println(" Wrong Option..! Please Enter Again");
}
br.readLine();
}
// clean up:
// close the output stream
// close the input stream
// close the socket

os.close();
is.close();
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
Output –
Experiment 8
Aim – Write a program in to prepare a list of 50 questions and their answers.

Code –
import java.util.Scanner;
public class p2 {
public static void main(String args[]){
String question[] = new String[50];
String answer[] = new String[50];
Scanner sc = new Scanner(System.in);
System.out.println("Program to prepare a list of 50 questions and their answers");
System.out.println("^^^^^^^ ^^ ^^^^^^^ ^ ^^^^ ^^ ^^ ^^^^^^^^^ ^^^ ^^^^^
^^^^^^^");
for(int i=0;i<50;i++){
System.out.println("Enter Question No. "+String.valueOf(i+1)+" - ");
question[i]=sc.nextLine();
System.out.println("Enter Answer for Question No.
"+String.valueOf(i+1)+" - ");
answer[i]=sc.nextLine();
}
System.out.println();
System.out.println("List Prepared is given as -");
for(int i=0;i<50;i++){
System.out.println();
System.out.println("Question No. "+String.valueOf(i+1)+" -
"+question[i]);
System.out.println("Answer for Question No. "+String.valueOf(i+1)+" -
"+answer[i]);
}
}}
Output –
Experiment 9
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 –

java.util.Random;
public class p3 {
public static void main(String args[])
{
String questions[] = new String[50];
questions[0] = "Which Indian company recently buys Oakley Court in UK for Rs 256
crore?";
questions[1] = "What is the name of Congress Rajya Sabha MP who recently gets 4 year
jail?";
questions[2] = "How many percent quotas for locals in 12 Delhi University colleges?";
questions[3] = "Which Company launched Flying Spur in India for just at Rs.3.1 crore in
2013?";
questions[4] = "Which University scientists found world's sharpest X-ray beam?";
questions[5] = "What is the name of current captain of Australia who recently misses
India tour due to back injury?";
questions[6] = "Which Bollywood actor recently gets 14 day parole on health grounds in
2013?";
questions[7] = "In 2013 how many dreaded SIMI terrorists slip away from Madhya
Pradesh jail?";
questions[8] = "Which Court in 2013 sent contempt notice to General V K Singh?";
questions[9] = "What is the name of former telecom minister who booked by Crime
Branch of India in BSNL case?";
questions[10] = "Which Indian state hikes bus fares by 30 percent from 1 October?";
questions[11] = "Which two countries signed a landmark civil nuclear deal after 5
years?";
questions[12] = "Which team became the first team to make into the semi-finals of
Champions League Twenty20 2013?";
questions[13] = "Which Indian Player recently won the Pan Pacific Open doubles title?";
questions[14] = "Which Political party recently suspended MP Kunal Ghosh?";
questions[15] = "Who has been recently won the Miss World crown 2013?";
questions[16] = "What is the name of Muzaffarnagar SSP who has been recently
removed from post?";
questions[17] = "Which State court sent Let bomb expert Tunda to 3 day police
custody?";
questions[18] = "Which Indian Player recently enters the final of youth boxing
championships?";
questions[19] = "Which Player recently hits century as Delhi reaches the final of
Challenger Trophy";
questions[20] = "Which Pakistani girl recently honoured with human rights
Politkovskaya Award?";
questions[21] = "Which Indian Badminton player faces life ban over Indian Badminton
League row?";
questions[22] = "What is the name of senior Hindustani classical vocalist who recently
passes away?";
questions[23] = "Which Bollywood actor told to pay Rs 2.90 lakh per month to wife and
son?";
questions[24] = "Which Cricket team recently beat Trinidad and Tobago by six wickets
to enter the final of Champions League Twenty20?";
questions[25] = "Who is the current Human Resource Development minister of India?";
questions[26] = "What is the name of Indian-American who led the trade promotion arm
of the US Commerce Department named by US President Barack Obama?";
questions[27] = "Which Cricketer recently completed a milestone of 50,000 runs in all
forms of recognised cricket?";
questions[28] = "Which former Prime Minster's elder son recently joins BJP?";
questions[29] = "How many militants killed by Indian army on Kashmir LoC?";
questions[30] = "Who has been recently honoured with P L Roy CSR Award?";
questions[31] = "Who has been recently appointed as first women chairman of State
Bank of India?";
questions[32] = "What is the name of BJP general secretary who recently questioned by
CBI in Prajapati murder case?";
questions[33] = "Who has been recently awarded with IPI award for excellence in
Journalism?";
questions[34] = "Who is the current secretary of Badminton Association of India?";
questions[35] = "How many US based scientists recently win Nobel Prize in medicine
for work on traffic control system of cells?";
questions[36] = "How much kilogram gold recently seized from aircraft in Chennai?";
questions[37] = "Which Bollywood actress recently arrested by Mumbai Police for
abusing cops?";
questions[38] = "Which former mines minister named in illegal mining case?";
questions[39] = "Who became the first four- star officer of Pakistan to receive an
extension from an elected government after his tenure as the army chief ended in 2010?";
questions[40] = "Who is the COAL MINISTER OF INDIA?";
questions[41] = "Who is the CHEIF OF I.B?";
questions[42] = "Who received the first NOBLE for INDIA?";
questions[43] = "Who is the AUTHOR OF 'WINGS OF FIRE' ?";
questions[44] = "Who is the PRESIDENT OF BANGLADESH?";
questions[45] = "Who is the SPEAKER OF LOK SABHA?";
questions[46] = "The author of the book Midnight's Children is?";
questions[47] = "For how many years, Hyderabad will be the capital of both Telangana
and Andhra Pradesh?";
questions[48] = "Who win the United Nations' Special Envoy for Global Education's
Youth Courage Award for Education?";
questions[49] = "Who is the chief of panel committee to scrutinize new bank licences?";

System.out.println("Program to generate 10 random questions out of 50");


System.out.println("^^^^^^^ ^^ ^^^^^^^^ ^^ ^^^^^^ ^^^^^^^^^ ^^^ ^^ ^^");

for(int i=0;i<10;i++)
{
System.out.println("Q"+String.valueOf(i+1)+":- "+questions[new Random().nextInt(4)+(5*i)]);
}

}
}
Output –
Experiment 10
Aim – Implement producer-consumer problem using threads.

Code –

class Q
{
int n;
boolean valueset = false;
synchronized void get()
{
if(!valueset)
{
try {
System.out.println("Got: "+n);
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
valueset=false;
notify();
}
synchronized void put(int n)
{
this.n=n;
if(valueset)
{
try {
System.out.println("Put: "+n);
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
valueset=true;
notify();
}
}

class Producer implements Runnable


{
Q q;
Producer(Q q)
{
this.q = q;
new Thread(this,"Producer").start();
}
@Override
public void run() {
int i=0;
while(true)
{
q.put(i++);
}
}
}

class Consumer implements Runnable


{
Q q;
Consumer(Q q)
{
this.q = q;
new Thread(this,"Consumer").start();
}
@Override
public void run() {
while(true)
{
q.get();
}
}
}

public class p4 {

public static void main(String args[])


{
Q q = new Q();
new Producer(q);
new Consumer(q);}}
Output –

You might also like