CODE:
clc
clear all
close all
sn = 0;
f=input('Enter The Sampling Frequency Where f = 0.8 or 0.6 or 0.4 or 0.2 := ');
n=input('Enter The Order Of Filter Where n = 16 or 32 or 64 or 128 or 256 := ');
disp(' For Hamming Window ');
for i=1:256
sn(i) = ((4*sin(2*pi*(f)*i)) + ((4/3)*sin(2*pi*3*(f)*i))+((4/5)*sin(2*pi*5*(f)*i))+((4/7)*sin(2*pi*7*(f)*i)));
end
subplot(3,2,1);
plot(sn);grid;
axis([0 150 -10 10]);
%Create a filter and use sn as input
wn = 0.2 * pi; %Cutoff frequency
win=hanning(n+1);
b = fir1(n,wn,'high',win);
%Creating FIR HP filter with hamming window
hs = filter(b,1,sn);
%Plot the output
subplot(3,2,2);
plot(hs);grid;
axis([0 150 -10 10]);
title('Output of the FIR HP filter');
%Plot the magnitude response of the filter
subplot(3,2,3);
[H,F] = freqz(b,1,256);
% returns the frequency response vector H and the corresponding angular frequency vector F
plot(F,20 * log10(abs(H)));grid;
xlabel('Normalized F (rad/sample)');
ylabel('Magnitude (dB)');
title('Magnitude Response');
%Plot the phase response of the filter
subplot(3,2,4);
plot(F,unwrap(angle(H))*180/pi); grid;
xlabel('Normalized F (rad/sample)');
ylabel('Phase (degrees)');
title('Phase Response');
%Plot the filter
subplot(3,2,5);
plot(b);grid;
xlabel('Filter using hamming window');
fvtool(b);
Wednesday, November 18, 2009
Program to design Lowpass FIR Filter using Hamming Windows
CODE
clc
clear all
close all
sn = 0;
f=input('Enter The Sampling Frequency Where f = 0.8 or 0.6 or 0.4 or 0.2 := ');
n=input('Enter The Order Of Filter Where n = 16 or 32 or 64 or 128 or 256 := ');
disp(' For Hamming Window ‘);
windowtype=input('Enter The Type Of Window: =');
for i=1:256
sn(i) = ((4*sin(2*pi*(f)*i)) + ((4/3)*sin(2*pi*3*(f)*i))+((4/5)*sin(2*pi*5*(f)*i))+((4/7)*sin(2*pi*7*(f)*i)));
end
subplot(3,2,1);
plot(sn);grid;
axis([0 150 -10 10]);
%Create a filter and use sn as input
wn = 0.2 * pi; %Cutoff frequency
win=hamming(n+1);
b = fir1(n,wn,win);
%Creating FIR LP filter with hamming window
hs = filter(b,1,sn);
%Plot the output
subplot(3,2,2);
plot(hs);grid;
axis([0 150 -10 10]);
title('Output of the FIR LP filter');
%Plot the magnitude response of the filter
subplot(3,2,3);
[H,F] = freqz(b,1,256);
% returns the frequency response vector H and the corresponding angular frequency vector F
plot(F,20 * log10(abs(H)));grid;
xlabel('Normalized F (rad/sample)');
ylabel('Magnitude (dB)');
title('Magnitude Response');
%Plot the phase response of the filter
subplot(3,2,4);
plot(F,unwrap(angle(H))*180/pi); grid;
xlabel('Normalized F (rad/sample)');
ylabel('Phase (degrees)');
title('Phase Response');
%Plot the filter
subplot(3,2,5);
plot(hs);grid;
xlabel('Filter using hamming window');
fvtool(b);
clc
clear all
close all
sn = 0;
f=input('Enter The Sampling Frequency Where f = 0.8 or 0.6 or 0.4 or 0.2 := ');
n=input('Enter The Order Of Filter Where n = 16 or 32 or 64 or 128 or 256 := ');
disp(' For Hamming Window ‘);
windowtype=input('Enter The Type Of Window: =');
for i=1:256
sn(i) = ((4*sin(2*pi*(f)*i)) + ((4/3)*sin(2*pi*3*(f)*i))+((4/5)*sin(2*pi*5*(f)*i))+((4/7)*sin(2*pi*7*(f)*i)));
end
subplot(3,2,1);
plot(sn);grid;
axis([0 150 -10 10]);
%Create a filter and use sn as input
wn = 0.2 * pi; %Cutoff frequency
win=hamming(n+1);
b = fir1(n,wn,win);
%Creating FIR LP filter with hamming window
hs = filter(b,1,sn);
%Plot the output
subplot(3,2,2);
plot(hs);grid;
axis([0 150 -10 10]);
title('Output of the FIR LP filter');
%Plot the magnitude response of the filter
subplot(3,2,3);
[H,F] = freqz(b,1,256);
% returns the frequency response vector H and the corresponding angular frequency vector F
plot(F,20 * log10(abs(H)));grid;
xlabel('Normalized F (rad/sample)');
ylabel('Magnitude (dB)');
title('Magnitude Response');
%Plot the phase response of the filter
subplot(3,2,4);
plot(F,unwrap(angle(H))*180/pi); grid;
xlabel('Normalized F (rad/sample)');
ylabel('Phase (degrees)');
title('Phase Response');
%Plot the filter
subplot(3,2,5);
plot(hs);grid;
xlabel('Filter using hamming window');
fvtool(b);
Program to perform 2-D Cross Correlation & Auto Correlation
CODE
clc
clear all
close all
x=[1 2;3 4]
h=[5 6;7 8]
y=xcorr2(x,h);
disp('Cross Correlation');
disp(y);
y1=xcorr2(x);
disp('Auto Correlation');
disp(y1);
clc
clear all
close all
x=[1 2;3 4]
h=[5 6;7 8]
y=xcorr2(x,h);
disp('Cross Correlation');
disp(y);
y1=xcorr2(x);
disp('Auto Correlation');
disp(y1);
To perform Circular Convolution
CODE
%x(n)--> Input Sequence% Given-->[1 2 4]
%h(n)--> Impulse Response% Given-->[1 2]
clc
clear all
close all
x=input('Enter x(n) : = ');
h=input('Enter h(n) := ');
N1=length(x);
N2=length(h);
N=max(N1,N2);
y=conv(x,h); %stores value according to linear conv.
ly=length(y);
for i=1:1:N
if(N+i<=ly)
r(i)=y(i)+y(N+i);
else
r(i)=y(i);
end
end
disp(r)
%x(n)--> Input Sequence% Given-->[1 2 4]
%h(n)--> Impulse Response% Given-->[1 2]
clc
clear all
close all
x=input('Enter x(n) : = ');
h=input('Enter h(n) := ');
N1=length(x);
N2=length(h);
N=max(N1,N2);
y=conv(x,h); %stores value according to linear conv.
ly=length(y);
for i=1:1:N
if(N+i<=ly)
r(i)=y(i)+y(N+i);
else
r(i)=y(i);
end
end
disp(r)
Write a program to perform 2-Dimensional Linear Convolution
CODE:
clc
clear all
close all
x=[1 2;3 4];
h=[5 6;7 8];
y=conv2(x,h);
disp(y)
subplot(3,1,1);plot(x);title('Input Sequence');
subplot(3,1,2);plot(h);title('Impulse Response');
subplot(3,1,3);plot(y);title('Output Sequence');
clc
clear all
close all
x=[1 2;3 4];
h=[5 6;7 8];
y=conv2(x,h);
disp(y)
subplot(3,1,1);plot(x);title('Input Sequence');
subplot(3,1,2);plot(h);title('Impulse Response');
subplot(3,1,3);plot(y);title('Output Sequence');
Write a program to perform 1-Dimensional Linear Convolution.
CODE
%x(n)--> Input Sequence% Given-->[1 1 1 1 1]
%h(n)--> Impulse Response% Given-->[1 2 3 4 5 6 7 8]
clc
clear all
close all
x=[1 1 1 1 1];
h=[1 2 3 4 5 6 7 8];
y=conv(x,h);
figure;
subplot(3,1,1);stem(x);
xlabel('n---->');
ylabel('Amplitude---->');
title('Input Sequence');
subplot(3,1,2);stem(h);
xlabel('n---->');
ylabel('Amplitude---->');
title('Impulse Response');
subplot(3,1,3);stem(y);
xlabel('n---->');
ylabel('Amplitude---->');
title('Output Sequence');
%x(n)--> Input Sequence% Given-->[1 1 1 1 1]
%h(n)--> Impulse Response% Given-->[1 2 3 4 5 6 7 8]
clc
clear all
close all
x=[1 1 1 1 1];
h=[1 2 3 4 5 6 7 8];
y=conv(x,h);
figure;
subplot(3,1,1);stem(x);
xlabel('n---->');
ylabel('Amplitude---->');
title('Input Sequence');
subplot(3,1,2);stem(h);
xlabel('n---->');
ylabel('Amplitude---->');
title('Impulse Response');
subplot(3,1,3);stem(y);
xlabel('n---->');
ylabel('Amplitude---->');
title('Output Sequence');
Program to read a .wav file, plot the graph & play the file.
CODE
InputFilename = 'chord.wav';
[inspeech, Fs, bits] = wavread(InputFilename);
figure(1);
subplot(3,1,1);
plot(inspeech);
grid;
soundsc(inspeech, Fs);
InputFilename = 'chord.wav';
[inspeech, Fs, bits] = wavread(InputFilename);
figure(1);
subplot(3,1,1);
plot(inspeech);
grid;
soundsc(inspeech, Fs);
Program for generating basic functions. Unit Imupulse
CODE
clc
clear all
close all
n=6;
%To Generate Unit Impulse Siganl%
x=-2:1:2;
y=[zeros(1,2),ones(1),zeros(1,2)];
subplot(2,2,1);stem(x,y);
ylabel('Amplitude---->');
xlabel('n---->');
title('Unit Impulse Signal');
%To Generate Unit Step Signal%
t=0:1:n-1;
y1=ones(1,n);
subplot(2,2,2);stem(t,y1);
ylabel('Amplitude---->');
xlabel('n---->');
title('Unit Step Signal');
%To Generate Ramp Signal%
t1=0:1:n;
subplot(2,2,3);stem(t1,t1);
ylabel('Amplitude---->');
xlabel('n---->');
title('Ramp Sequence');
%To Generate Exponentional Sequence%
y2=exp(-1*t1);
subplot(2,2,4);stem(t1,y2);
ylabel('Amplitude---->');
xlabel('n---->');
title('Exponentional Sequence');
%To Generate Sine Sequence%
pause
t2=0:0.01:pi;
y3=sin(2*pi*t2);figure(2);
subplot(2,1,1);plot(t2,y3);
ylabel('Amplitude---->');
xlabel('n---->');
title('Sine Sequence');
%To Generate Cose Sequence%
t2=0:0.01:pi;
y3=cos(2*pi*t2);
subplot(2,1,2);plot(t2,y3);
ylabel('Amplitude---->');
xlabel('n---->');
title('Cose Sequence');
clc
clear all
close all
n=6;
%To Generate Unit Impulse Siganl%
x=-2:1:2;
y=[zeros(1,2),ones(1),zeros(1,2)];
subplot(2,2,1);stem(x,y);
ylabel('Amplitude---->');
xlabel('n---->');
title('Unit Impulse Signal');
%To Generate Unit Step Signal%
t=0:1:n-1;
y1=ones(1,n);
subplot(2,2,2);stem(t,y1);
ylabel('Amplitude---->');
xlabel('n---->');
title('Unit Step Signal');
%To Generate Ramp Signal%
t1=0:1:n;
subplot(2,2,3);stem(t1,t1);
ylabel('Amplitude---->');
xlabel('n---->');
title('Ramp Sequence');
%To Generate Exponentional Sequence%
y2=exp(-1*t1);
subplot(2,2,4);stem(t1,y2);
ylabel('Amplitude---->');
xlabel('n---->');
title('Exponentional Sequence');
%To Generate Sine Sequence%
pause
t2=0:0.01:pi;
y3=sin(2*pi*t2);figure(2);
subplot(2,1,1);plot(t2,y3);
ylabel('Amplitude---->');
xlabel('n---->');
title('Sine Sequence');
%To Generate Cose Sequence%
t2=0:0.01:pi;
y3=cos(2*pi*t2);
subplot(2,1,2);plot(t2,y3);
ylabel('Amplitude---->');
xlabel('n---->');
title('Cose Sequence');
Low pass Median filter on image with salt and pepper noise
CODE
clear all
clc
a = imread('cameraman.tif');
p = imnoise(a,'salt & pepper',0.02'); %Adding noise
q = double(p);
[row col] = size(q);
for i=2:1:row-1
for j=2:1:col-1
%To make a 3x3 mask into 1x9 mask
q1=[ q(i-1,j-1) q(i-1,j) q(i-1,j+1) q(i,j-1) q(i,j) q(i,j+1) q(i+1,j-1) q(i+1,j)
q(i+1,j+1) ];
q2=sort(q1);
median=q2(5); %The fifth value is the median
q3(i,j)=median;
end
end
figure(1)
imshow(uint8(p))
title('Image after ''Salt & Pepper'' Noise')
figure(2)
imshow(uint8(q3))
title('Image after cleaning the ''salt & pepper'' noise using ''Low pass Median Filtering'' technique')
clear all
clc
a = imread('cameraman.tif');
p = imnoise(a,'salt & pepper',0.02'); %Adding noise
q = double(p);
[row col] = size(q);
for i=2:1:row-1
for j=2:1:col-1
%To make a 3x3 mask into 1x9 mask
q1=[ q(i-1,j-1) q(i-1,j) q(i-1,j+1) q(i,j-1) q(i,j) q(i,j+1) q(i+1,j-1) q(i+1,j)
q(i+1,j+1) ];
q2=sort(q1);
median=q2(5); %The fifth value is the median
q3(i,j)=median;
end
end
figure(1)
imshow(uint8(p))
title('Image after ''Salt & Pepper'' Noise')
figure(2)
imshow(uint8(q3))
title('Image after cleaning the ''salt & pepper'' noise using ''Low pass Median Filtering'' technique')
High Pass Filter in Spatial Domain
CODE
% High pass filter done on an image
clear all
clc
a = imread('cameraman.tif');
p = double(a);
w=[-1 -1 -1;-1 8 -1;-1 -1 -1] %Creating the high pass average mask
[row col]=size(p)
for i=2:1:row-1
for j=2:1:col-1
p1(i,j) =[ (w(1) * p(i-1,j-1)) + (w(2) * p(i-1,j)) + (w(3) * p(i-1,j+1)) + (w(4) *
p(i,j-1)) + (w(5) * p(i,j)) + (w(6) * p(i,j+1)) + (w(7) * p(i+1,j-1)) + (w(8) * p(i+1,j)) + (w(9) * p(i+1,j+1)) ];
end
end
figure(1)
imshow(uint8(p))
title('Original Image');
figure(2)
imshow(uint8(p1))
title('Image after ''High Pass'' Filtering');
% High pass filter done on an image
clear all
clc
a = imread('cameraman.tif');
p = double(a);
w=[-1 -1 -1;-1 8 -1;-1 -1 -1] %Creating the high pass average mask
[row col]=size(p)
for i=2:1:row-1
for j=2:1:col-1
p1(i,j) =[ (w(1) * p(i-1,j-1)) + (w(2) * p(i-1,j)) + (w(3) * p(i-1,j+1)) + (w(4) *
p(i,j-1)) + (w(5) * p(i,j)) + (w(6) * p(i,j+1)) + (w(7) * p(i+1,j-1)) + (w(8) * p(i+1,j)) + (w(9) * p(i+1,j+1)) ];
end
end
figure(1)
imshow(uint8(p))
title('Original Image');
figure(2)
imshow(uint8(p1))
title('Image after ''High Pass'' Filtering');
Low Pass Filter in Spatial domain
CODE
% Low pass Average filter used on an image with Gaussian noise
clear all
clc
a = imread('cameraman.tif');
p = imnoise(a,'gaussian'); %Adding noise
q = double(p);
[row col]=size(q)
w = [1 1 1;1 1 1;1 1 1]/9 %Creating the low pass average mask
for i=2:1:row-1
for j=2:1:col-1
q1(i,j) = [ (w(1) * q(i-1,j-1)) + (w(2) * q(i-1,j)) + (w(3) * q(i-1,j+1)) + (w(4)
* q(i,j-1)) + (w(5) * q(i,j)) + (w(6) * q(i,j+1)) + (w(7) * q(i+1,j-1))
+ (w(8) * q(i+1,j)) + (w(9) * q(i+1,j+1)) ];
end
end
figure(1)
imshow(uint8(q))
title('Original Image with Gaussian Noise');
figure(2)
imshow(uint8(q1))
title('Image after using Low Pass Average Filter on Gaussian Noised image');
% Low pass Average filter used on an image with Gaussian noise
clear all
clc
a = imread('cameraman.tif');
p = imnoise(a,'gaussian'); %Adding noise
q = double(p);
[row col]=size(q)
w = [1 1 1;1 1 1;1 1 1]/9 %Creating the low pass average mask
for i=2:1:row-1
for j=2:1:col-1
q1(i,j) = [ (w(1) * q(i-1,j-1)) + (w(2) * q(i-1,j)) + (w(3) * q(i-1,j+1)) + (w(4)
* q(i,j-1)) + (w(5) * q(i,j)) + (w(6) * q(i,j+1)) + (w(7) * q(i+1,j-1))
+ (w(8) * q(i+1,j)) + (w(9) * q(i+1,j+1)) ];
end
end
figure(1)
imshow(uint8(q))
title('Original Image with Gaussian Noise');
figure(2)
imshow(uint8(q1))
title('Image after using Low Pass Average Filter on Gaussian Noised image');
Write a program to demonstrate Histogram Equalization
CODE
% Histogram Equalization%
f = imread('tire.tif');
g = histeq(f);
title('Histogram');
subplot(2,2,1);
imshow(f);
title('Input Image');
subplot(2,2,2);
imhist(f);
title('Histogram');
subplot(2,2,3);
imshow(g);
title('Image after Histogram Equalization');
subplot(2,2,4);
imhist(g);
title('Histogram');
% Histogram Equalization%
f = imread('tire.tif');
g = histeq(f);
title('Histogram');
subplot(2,2,1);
imshow(f);
title('Input Image');
subplot(2,2,2);
imhist(f);
title('Histogram');
subplot(2,2,3);
imshow(g);
title('Image after Histogram Equalization');
subplot(2,2,4);
imhist(g);
title('Histogram');
Write a program to demonstrate Dynamic Range Compression
% Dynamic Range Compression
clear all ;
clc;
aa=imread('saturn.tif');
a=double(aa);
[row,col]=size(a);
for x=1:1:row
for y=1:1:col
c(x,y)=a(x,y)*((-1)^(x+y));%%Needed to center transform%%
end
end
d=abs(fft2(c));
d_log=log(1+d);
%%Plotting
figure(1);
colormap(gray);
imagesc(d);
figure(2);
colormap(gray);
imagesc(d_log);
clear all ;
clc;
aa=imread('saturn.tif');
a=double(aa);
[row,col]=size(a);
for x=1:1:row
for y=1:1:col
c(x,y)=a(x,y)*((-1)^(x+y));%%Needed to center transform%%
end
end
d=abs(fft2(c));
d_log=log(1+d);
%%Plotting
figure(1);
colormap(gray);
imagesc(d);
figure(2);
colormap(gray);
imagesc(d_log);
To Demonstrate adding, deleting, and updating in Persistent database
PROBLEM STATEMENT
Create an application to perform the following operations on a persistent database
1. Adding Records
2. Deleting Records
3. Updating Records
CODE
import java.io.*;
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
public class RemoveRecordDemo extends MIDlet implements ItemStateListener, CommandListener
{
private Display display;
private Form frmMain;
private FormAdd frmAdd;
private List list = new List("All records ",List.IMPLICIT);
private Command cmdAdd, cmdExit, cmdDelete, cmdBack1,
cmdUpdate;
private Vector vecOP;
private ChoiceGroup chgOP;
protected DisplayManager displayMgr;
private RecordStore rs;
private static final String strREC_STORE_OP = "OPList";
private boolean flagSortByPriority = false,
flagShowPriority = true;
private ByteArrayInputStream istrmBytes = null;
private DataInputStream istrmDataType = null;
String strOP;
int strRecordId;
byte[] recData = new byte[250];
ByteArrayOutputStream ostrmBytes = null;
DataOutputStream ostrmDataType = null;
private RecordEnumeration e = null;
private ComparatorInt comp = null;
public RemoveRecordDemo()
{
// Indicating the object to be Displayed
display = Display.getDisplay(this);
//initializing Form’s object
frmMain = new Form("");
frmAdd = new FormAdd("Add record", this);
//Initializing choice group
chgOP = new ChoiceGroup("", Choice.MULTIPLE);
vecOP = new Vector();
//Initailizing Command button
cmdAdd = new Command("Add record", Command.SCREEN, 2);
cmdDelete = new Command("Delete record", Command.SCREEN, 2);
cmdExit = new Command("Exit", Command.EXIT, 1);
cmdBack1 = new Command("back", Command.BACK, 1);
cmdUpdate = new Command("Update record", Command.SCREEN, 2);
frmMain.addCommand(cmdBack1);
//Adding list to form
list.addCommand(cmdAdd);
list.addCommand(cmdUpdate);
list.addCommand(cmdDelete);
list.addCommand(cmdExit);
list.setCommandListener(this);
frmMain.append(chgOP);
// Adding Command Listner
frmMain.setCommandListener(this);
frmMain.setItemStateListener(this);
displayMgr = new DisplayManager(display, list);
rs = openRecStore(strREC_STORE_OP);
initInputStreams();
initOutputStreams();
initEnumeration();
writeRMS2Vector();
rebuildOPList();
}
public void startApp()
{
display.setCurrent(list);
}
public void destroyApp(boolean unconditional)
{
if (comp != null)
comp.compareIntClose();
if (e != null)
e.destroy();
try
{
if (istrmDataType != null)
istrmDataType.close();
if (istrmBytes != null)
istrmBytes.close();
if (ostrmDataType != null)
ostrmDataType.close();
if (ostrmBytes != null)
ostrmBytes.close();
}
catch (Exception e)
{
System.out.println(e.toString());
}
closeRecStore(rs);
}
public void pauseApp(){}
private void initInputStreams()
{
istrmBytes = new ByteArrayInputStream(recData);
istrmDataType = new DataInputStream(istrmBytes);
}
private void initOutputStreams()
{
ostrmBytes = new ByteArrayOutputStream();
ostrmDataType = new DataOutputStream(ostrmBytes);
}
private void initEnumeration()
{
if (flagSortByPriority)
comp = new ComparatorInt();
else
comp = null;
try
{
e = rs.enumerateRecords(null, comp, false);
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
private RecordStore openRecStore(String name)
{
try
{
return RecordStore.openRecordStore(name, true);
}
catch (Exception e)
{
System.out.println(e.toString());
return null;
}
}
private void closeRecStore(RecordStore rs)
{
try
{
rs.closeRecordStore();
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
private void deleteRecStore(String name)
{
try
{
RecordStore.deleteRecordStore(name);
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
protected void addOPItem(String Name, String Address, String phonenum)
{
if (strOP == "A")
{
try
{
ostrmBytes.reset();
ostrmDataType.writeUTF(Name);
ostrmDataType.writeUTF(Address);
ostrmDataType.writeUTF(phonenum);
ostrmDataType.flush();
byte[] record = ostrmBytes.toByteArray();
int recordId = rs.addRecord
(record, 0, record.length);
OPItem item = new OPItem
(Name, Address, phonenum, recordId);
vecOP.addElement(item);
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
else if (strOP == "U")
{
try
{
ostrmBytes.reset();
ostrmDataType.writeUTF(Name);
ostrmDataType.writeUTF(Address);
ostrmDataType.writeUTF(phonenum);
ostrmDataType.flush();
byte[] record = ostrmBytes.toByteArray();
rs.setRecord(strRecordId, record, 0, record.length);
OPItem item = new OPItem
(Name, Address, phonenum, strRecordId);
vecOP.addElement(item);
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
writeRMS2Vector();
rebuildOPList();
}
private void writeRMS2Vector()
{
vecOP.removeAllElements();
try
{
e.rebuild();
while (e.hasNextElement())
{
istrmBytes.reset();
int id = e.nextRecordId();
rs.getRecord(id, recData, 0);
OPItem item = new OPItem(istrmDataType.readUTF(),
istrmDataType.readUTF(),
istrmDataType.readUTF(), id);
vecOP.addElement(item);
}
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
protected void rebuildOPList()
{
for (int i = chgOP.size(); i > 0; i--)
chgOP.delete(i - 1);
list.deleteAll();
OPItem item;
String phonenum;
String Name;
String Address;
StringBuffer strb;
for (int i = 0; i < vecOP.size(); i++)
{
item = (OPItem)vecOP.elementAt(i);
phonenum = item.getphonenum();
Name = item.getName();
Address = item.getAddress();
strb = new StringBuffer();
strb.append(Name + " " + Address + " " + phonenum);
list.append(strb.toString(), null);
chgOP.append(strb.toString(), null);
}
}
public void itemStateChanged(Item item)
{
ChoiceGroup cg;
cg = (ChoiceGroup)item;
boolean selected[] = new boolean[cg.size()];
cg.getSelectedFlags(selected);
for (int i = 0; i < cg.size(); i++)
{
if (selected[i])
{
OPItem opitem = (OPItem)vecOP.elementAt(i);
if (strOP == "D")
{
try
{
rs.deleteRecord(opitem.getRecordId());
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
if (strOP == "U")
{
displayMgr.pushDisplayable(frmAdd);
frmAdd.setTitle("Update record");
try
{
frmAdd.tfName.setString(opitem.getName()); frmAdd.tfAddress.setString(opitem.getAddress());
frmAdd.tfPhonenum.setString(opitem.getphonenum());
strRecordId = opitem.getRecordId();
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
break;
}
}
writeRMS2Vector();
rebuildOPList();
}
public void commandAction(Command c, Displayable d)
{
if (c == cmdExit)
{
destroyApp(false);
notifyDestroyed();
}
else
{
if (c == cmdAdd)
{
strOP = "A";
frmAdd.setTitle("Add record");
frmAdd.tfName.setString("");
frmAdd.tfAddress.setString("");
frmAdd.tfPhonenum.setString("");
displayMgr.pushDisplayable(frmAdd);
}
else if (c == cmdDelete)
{
strOP = "D";
frmMain.setTitle("Delete record");
displayMgr.pushDisplayable(frmMain);
}
else if (c == cmdUpdate)
{
strOP = "U";
frmMain.setTitle("Update record");
displayMgr.pushDisplayable(frmMain);
}
else if (c == cmdBack1)
{
displayMgr.popDisplayable();
}
}
}
}
class DisplayManager extends Stack
{
// Reference to Display object
private Display display;
// Main displayable for MIDlet
private Displayable mainDisplayable;
private Alert alStackError; // Alert for error conditions
/* Display manager constructor */
public DisplayManager(Display display, Displayable mainDisplayable)
{
// Only one display object per midlet, this is it
this.display = display;
this.mainDisplayable = mainDisplayable;
// Create an alert displayed when an error occurs
alStackError = new Alert("Displayable Stack Error");
alStackError.setTimeout(Alert.FOREVER); // Modal
}
public void pushDisplayable(Displayable newDisplayable)
{
//System.out.println("pushDisplayable");
push(display.getCurrent());
display.setCurrent(newDisplayable);
}
/*Return to the main displayable object of MIDlet*/
public void home()
{
while (elementCount > 1)
pop();
display.setCurrent(mainDisplayable);
}
/* Pop displayable from stack and set as active */
public void popDisplayable()
{
// If the stack is not empty, pop next displayable
if (empty() == false)
display.setCurrent((Displayable)pop());
else
// On error show an alert
// Once acknowldeged, set 'mainDisplayable' as active
display.setCurrent(alStackError, mainDisplayable);
}
}
class FormAdd extends Form implements CommandListener
{
private Command cmBack,cmSave;
protected TextField tfName;
protected TextField tfAddress;
protected TextField tfPhonenum;
//protected ChoiceGroup cgPriority;
private RemoveRecordDemo midlet;
public FormAdd(String title, RemoveRecordDemo midlet)
{
// Call the Form constructor
super(title);
// Save reference to MIDlet so we can access
// the display manager class and rms
this.midlet = midlet;
//Initailizing Command buttons
cmSave = new Command("Save", Command.SCREEN, 1);
cmBack = new Command("Back", Command.BACK, 2);
// Create textfield for entering todo items
tfName = new TextField
("Name", null, 15, TextField.ANY);
tfAddress = new TextField
("Address", null, 250, TextField.ANY);
tfPhonenum = new TextField
("Phonenum", null, 15, TextField.PHONENUMBER);
// Create choicegroup and append options (no images)
//cgPriority = new ChoiceGroup("Priority", Choice.EXCLUSIVE);
// Add buttons to form
addCommand(cmSave);
addCommand(cmBack);
append(tfName);
append(tfAddress);
append(tfPhonenum);
setCommandListener(this);
}
public void commandAction(Command c, Displayable s)
{
if (c == cmSave)
{
// Add a new todo item
/* Notice we bump priority by 1. This is because the choicegroup entries start at zero. We would like the records in the rms to store priorities starting at 1. Thus, if a user requests to display priorities on the todo list, the highest priority is 1 (not zero)*/
midlet.addOPItem(tfName.getString(), tfAddress.getString(), tfPhonenum.getString());
}
// Any other event and we go back to the main form...
// Pop the last displayable off the stack
midlet.displayMgr.popDisplayable();
}
}
class ComparatorInt implements RecordComparator
{
// Read from a specified byte array
private byte[] record = new byte[10];
// Read Java data types from the above byte array
private ByteArrayInputStream strmBytes = null;
private DataInputStream strmDataType = null;
public void compareIntClose()
{
try
{
if (strmBytes != null)
strmBytes.close();
if (strmDataType != null)
strmDataType.close();
}
catch (Exception e)
{}
}
public int compare(byte[] rec1, byte[] rec2)
{
int x1, x2;
try
{
//If either record is larger than our buffer, reallocate
int maxsize = Math.max(rec1.length, rec2.length);
if (maxsize > record.length)
record = new byte[maxsize];
// Read record #1
// We want the priority which is first "field"
strmBytes = new ByteArrayInputStream(rec1);
strmDataType = new DataInputStream(strmBytes);
x1 = strmDataType.readInt();
// Read record #2
strmBytes = new ByteArrayInputStream(rec2);
strmDataType = new DataInputStream(strmBytes);
x2 = strmDataType.readInt();
// Compare record #1 and #2
if (x1 == x2)
return RecordComparator.EQUIVALENT;
else if (x1 < x2)
return RecordComparator.PRECEDES;
else
return RecordComparator.FOLLOWS;
}
catch (Exception e)
{
return RecordComparator.EQUIVALENT;
}
}
}
class OPItem
{
private String phonenum;
private String Name;
private String Address;
private int recordId;
public OPItem(String Name,String Address, String phonenum, int recordId)
{
this.Name = Name;
this.Address = Address;
this.phonenum = phonenum;
this.recordId = recordId;
}
public String getphonenum()
{
return phonenum;
}
public void setphonenum(String phonenum)
{
// setphonenum
this.phonenum = phonenum;
}
public String getAddress()
{
//getAddress
return Address;
}
public void setAddress(String Address)
{
// setAddress
this.Address = Address;
}
public String getName()
{
// getName
return Name;
}
public void setName(String Name)
{
// setName
this.Name = Name;
}
public int getRecordId()
{
// getRecordId
return recordId;
}
}
Create an application to perform the following operations on a persistent database
1. Adding Records
2. Deleting Records
3. Updating Records
CODE
import java.io.*;
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
public class RemoveRecordDemo extends MIDlet implements ItemStateListener, CommandListener
{
private Display display;
private Form frmMain;
private FormAdd frmAdd;
private List list = new List("All records ",List.IMPLICIT);
private Command cmdAdd, cmdExit, cmdDelete, cmdBack1,
cmdUpdate;
private Vector vecOP;
private ChoiceGroup chgOP;
protected DisplayManager displayMgr;
private RecordStore rs;
private static final String strREC_STORE_OP = "OPList";
private boolean flagSortByPriority = false,
flagShowPriority = true;
private ByteArrayInputStream istrmBytes = null;
private DataInputStream istrmDataType = null;
String strOP;
int strRecordId;
byte[] recData = new byte[250];
ByteArrayOutputStream ostrmBytes = null;
DataOutputStream ostrmDataType = null;
private RecordEnumeration e = null;
private ComparatorInt comp = null;
public RemoveRecordDemo()
{
// Indicating the object to be Displayed
display = Display.getDisplay(this);
//initializing Form’s object
frmMain = new Form("");
frmAdd = new FormAdd("Add record", this);
//Initializing choice group
chgOP = new ChoiceGroup("", Choice.MULTIPLE);
vecOP = new Vector();
//Initailizing Command button
cmdAdd = new Command("Add record", Command.SCREEN, 2);
cmdDelete = new Command("Delete record", Command.SCREEN, 2);
cmdExit = new Command("Exit", Command.EXIT, 1);
cmdBack1 = new Command("back", Command.BACK, 1);
cmdUpdate = new Command("Update record", Command.SCREEN, 2);
frmMain.addCommand(cmdBack1);
//Adding list to form
list.addCommand(cmdAdd);
list.addCommand(cmdUpdate);
list.addCommand(cmdDelete);
list.addCommand(cmdExit);
list.setCommandListener(this);
frmMain.append(chgOP);
// Adding Command Listner
frmMain.setCommandListener(this);
frmMain.setItemStateListener(this);
displayMgr = new DisplayManager(display, list);
rs = openRecStore(strREC_STORE_OP);
initInputStreams();
initOutputStreams();
initEnumeration();
writeRMS2Vector();
rebuildOPList();
}
public void startApp()
{
display.setCurrent(list);
}
public void destroyApp(boolean unconditional)
{
if (comp != null)
comp.compareIntClose();
if (e != null)
e.destroy();
try
{
if (istrmDataType != null)
istrmDataType.close();
if (istrmBytes != null)
istrmBytes.close();
if (ostrmDataType != null)
ostrmDataType.close();
if (ostrmBytes != null)
ostrmBytes.close();
}
catch (Exception e)
{
System.out.println(e.toString());
}
closeRecStore(rs);
}
public void pauseApp(){}
private void initInputStreams()
{
istrmBytes = new ByteArrayInputStream(recData);
istrmDataType = new DataInputStream(istrmBytes);
}
private void initOutputStreams()
{
ostrmBytes = new ByteArrayOutputStream();
ostrmDataType = new DataOutputStream(ostrmBytes);
}
private void initEnumeration()
{
if (flagSortByPriority)
comp = new ComparatorInt();
else
comp = null;
try
{
e = rs.enumerateRecords(null, comp, false);
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
private RecordStore openRecStore(String name)
{
try
{
return RecordStore.openRecordStore(name, true);
}
catch (Exception e)
{
System.out.println(e.toString());
return null;
}
}
private void closeRecStore(RecordStore rs)
{
try
{
rs.closeRecordStore();
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
private void deleteRecStore(String name)
{
try
{
RecordStore.deleteRecordStore(name);
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
protected void addOPItem(String Name, String Address, String phonenum)
{
if (strOP == "A")
{
try
{
ostrmBytes.reset();
ostrmDataType.writeUTF(Name);
ostrmDataType.writeUTF(Address);
ostrmDataType.writeUTF(phonenum);
ostrmDataType.flush();
byte[] record = ostrmBytes.toByteArray();
int recordId = rs.addRecord
(record, 0, record.length);
OPItem item = new OPItem
(Name, Address, phonenum, recordId);
vecOP.addElement(item);
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
else if (strOP == "U")
{
try
{
ostrmBytes.reset();
ostrmDataType.writeUTF(Name);
ostrmDataType.writeUTF(Address);
ostrmDataType.writeUTF(phonenum);
ostrmDataType.flush();
byte[] record = ostrmBytes.toByteArray();
rs.setRecord(strRecordId, record, 0, record.length);
OPItem item = new OPItem
(Name, Address, phonenum, strRecordId);
vecOP.addElement(item);
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
writeRMS2Vector();
rebuildOPList();
}
private void writeRMS2Vector()
{
vecOP.removeAllElements();
try
{
e.rebuild();
while (e.hasNextElement())
{
istrmBytes.reset();
int id = e.nextRecordId();
rs.getRecord(id, recData, 0);
OPItem item = new OPItem(istrmDataType.readUTF(),
istrmDataType.readUTF(),
istrmDataType.readUTF(), id);
vecOP.addElement(item);
}
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
protected void rebuildOPList()
{
for (int i = chgOP.size(); i > 0; i--)
chgOP.delete(i - 1);
list.deleteAll();
OPItem item;
String phonenum;
String Name;
String Address;
StringBuffer strb;
for (int i = 0; i < vecOP.size(); i++)
{
item = (OPItem)vecOP.elementAt(i);
phonenum = item.getphonenum();
Name = item.getName();
Address = item.getAddress();
strb = new StringBuffer();
strb.append(Name + " " + Address + " " + phonenum);
list.append(strb.toString(), null);
chgOP.append(strb.toString(), null);
}
}
public void itemStateChanged(Item item)
{
ChoiceGroup cg;
cg = (ChoiceGroup)item;
boolean selected[] = new boolean[cg.size()];
cg.getSelectedFlags(selected);
for (int i = 0; i < cg.size(); i++)
{
if (selected[i])
{
OPItem opitem = (OPItem)vecOP.elementAt(i);
if (strOP == "D")
{
try
{
rs.deleteRecord(opitem.getRecordId());
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
if (strOP == "U")
{
displayMgr.pushDisplayable(frmAdd);
frmAdd.setTitle("Update record");
try
{
frmAdd.tfName.setString(opitem.getName()); frmAdd.tfAddress.setString(opitem.getAddress());
frmAdd.tfPhonenum.setString(opitem.getphonenum());
strRecordId = opitem.getRecordId();
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
break;
}
}
writeRMS2Vector();
rebuildOPList();
}
public void commandAction(Command c, Displayable d)
{
if (c == cmdExit)
{
destroyApp(false);
notifyDestroyed();
}
else
{
if (c == cmdAdd)
{
strOP = "A";
frmAdd.setTitle("Add record");
frmAdd.tfName.setString("");
frmAdd.tfAddress.setString("");
frmAdd.tfPhonenum.setString("");
displayMgr.pushDisplayable(frmAdd);
}
else if (c == cmdDelete)
{
strOP = "D";
frmMain.setTitle("Delete record");
displayMgr.pushDisplayable(frmMain);
}
else if (c == cmdUpdate)
{
strOP = "U";
frmMain.setTitle("Update record");
displayMgr.pushDisplayable(frmMain);
}
else if (c == cmdBack1)
{
displayMgr.popDisplayable();
}
}
}
}
class DisplayManager extends Stack
{
// Reference to Display object
private Display display;
// Main displayable for MIDlet
private Displayable mainDisplayable;
private Alert alStackError; // Alert for error conditions
/* Display manager constructor */
public DisplayManager(Display display, Displayable mainDisplayable)
{
// Only one display object per midlet, this is it
this.display = display;
this.mainDisplayable = mainDisplayable;
// Create an alert displayed when an error occurs
alStackError = new Alert("Displayable Stack Error");
alStackError.setTimeout(Alert.FOREVER); // Modal
}
public void pushDisplayable(Displayable newDisplayable)
{
//System.out.println("pushDisplayable");
push(display.getCurrent());
display.setCurrent(newDisplayable);
}
/*Return to the main displayable object of MIDlet*/
public void home()
{
while (elementCount > 1)
pop();
display.setCurrent(mainDisplayable);
}
/* Pop displayable from stack and set as active */
public void popDisplayable()
{
// If the stack is not empty, pop next displayable
if (empty() == false)
display.setCurrent((Displayable)pop());
else
// On error show an alert
// Once acknowldeged, set 'mainDisplayable' as active
display.setCurrent(alStackError, mainDisplayable);
}
}
class FormAdd extends Form implements CommandListener
{
private Command cmBack,cmSave;
protected TextField tfName;
protected TextField tfAddress;
protected TextField tfPhonenum;
//protected ChoiceGroup cgPriority;
private RemoveRecordDemo midlet;
public FormAdd(String title, RemoveRecordDemo midlet)
{
// Call the Form constructor
super(title);
// Save reference to MIDlet so we can access
// the display manager class and rms
this.midlet = midlet;
//Initailizing Command buttons
cmSave = new Command("Save", Command.SCREEN, 1);
cmBack = new Command("Back", Command.BACK, 2);
// Create textfield for entering todo items
tfName = new TextField
("Name", null, 15, TextField.ANY);
tfAddress = new TextField
("Address", null, 250, TextField.ANY);
tfPhonenum = new TextField
("Phonenum", null, 15, TextField.PHONENUMBER);
// Create choicegroup and append options (no images)
//cgPriority = new ChoiceGroup("Priority", Choice.EXCLUSIVE);
// Add buttons to form
addCommand(cmSave);
addCommand(cmBack);
append(tfName);
append(tfAddress);
append(tfPhonenum);
setCommandListener(this);
}
public void commandAction(Command c, Displayable s)
{
if (c == cmSave)
{
// Add a new todo item
/* Notice we bump priority by 1. This is because the choicegroup entries start at zero. We would like the records in the rms to store priorities starting at 1. Thus, if a user requests to display priorities on the todo list, the highest priority is 1 (not zero)*/
midlet.addOPItem(tfName.getString(), tfAddress.getString(), tfPhonenum.getString());
}
// Any other event and we go back to the main form...
// Pop the last displayable off the stack
midlet.displayMgr.popDisplayable();
}
}
class ComparatorInt implements RecordComparator
{
// Read from a specified byte array
private byte[] record = new byte[10];
// Read Java data types from the above byte array
private ByteArrayInputStream strmBytes = null;
private DataInputStream strmDataType = null;
public void compareIntClose()
{
try
{
if (strmBytes != null)
strmBytes.close();
if (strmDataType != null)
strmDataType.close();
}
catch (Exception e)
{}
}
public int compare(byte[] rec1, byte[] rec2)
{
int x1, x2;
try
{
//If either record is larger than our buffer, reallocate
int maxsize = Math.max(rec1.length, rec2.length);
if (maxsize > record.length)
record = new byte[maxsize];
// Read record #1
// We want the priority which is first "field"
strmBytes = new ByteArrayInputStream(rec1);
strmDataType = new DataInputStream(strmBytes);
x1 = strmDataType.readInt();
// Read record #2
strmBytes = new ByteArrayInputStream(rec2);
strmDataType = new DataInputStream(strmBytes);
x2 = strmDataType.readInt();
// Compare record #1 and #2
if (x1 == x2)
return RecordComparator.EQUIVALENT;
else if (x1 < x2)
return RecordComparator.PRECEDES;
else
return RecordComparator.FOLLOWS;
}
catch (Exception e)
{
return RecordComparator.EQUIVALENT;
}
}
}
class OPItem
{
private String phonenum;
private String Name;
private String Address;
private int recordId;
public OPItem(String Name,String Address, String phonenum, int recordId)
{
this.Name = Name;
this.Address = Address;
this.phonenum = phonenum;
this.recordId = recordId;
}
public String getphonenum()
{
return phonenum;
}
public void setphonenum(String phonenum)
{
// setphonenum
this.phonenum = phonenum;
}
public String getAddress()
{
//getAddress
return Address;
}
public void setAddress(String Address)
{
// setAddress
this.Address = Address;
}
public String getName()
{
// getName
return Name;
}
public void setName(String Name)
{
// setName
this.Name = Name;
}
public int getRecordId()
{
// getRecordId
return recordId;
}
}
To Demonstrate Searching the word
PROBLEM STATEMET
Create an application in j2me to demonstrate that will search for a word present in the given paragraph with 2 options:
a. case sensitive
b. case insensitive
CODE
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class SearchMidlet extends MIDlet implements CommandListener
{
private Display display;
private Form frm1, frm2;
private TextField txtfsearch;
private Command cmdquit;
private Command cmdback;
private Command cmdsearch;
private String strSearch;
private String strFind;
private String strAlert = "The Searched word position is ";
private ChoiceGroup chgsearchcase;
private Alert alert;
private int fromIndex = 0;
private boolean flag = true;
public SearchMidlet()
{
// Indicating the object to be Displayed
display = Display.getDisplay(this);
//initializing Form’s object
frm1 = new Form("MIDP");
frm2 = new Form("Search Utility");
strSearch = "The J2ME Wireless Toolkit is a set of tools that makes it possible to createapplications for mobile phones and other wireless devices. Although it is based on the Mobile Information Device Profile (MIDP) 2.0, the J2ME Wireless Toolkit also supports a handful of optional packages, making it a widely capable development toolkit.";
//Initailizing TextField’s objects.
txtfsearch = new TextField("Search : ", "", 12, TextField.ANY);
//Initailizing save Command button
cmdquit = new Command("Quit", Command.EXIT, 0);
cmdback = new Command("Back", Command.EXIT, 1);
cmdsearch = new Command("Search", Command.SCREEN, 0);
chgsearchcase = new ChoiceGroup
("Search Case :", Choice.EXCLUSIVE);
//Adding Choice Group to form
chgsearchcase.append("Case Sensetive", null);
chgsearchcase.append("Case Insensetive", null);
//Initailizing Alert object
alert = new Alert
("Search Alert", "", null, AlertType.CONFIRMATION);
//Adding TextFeilds and Commands to from
frm1.addCommand(cmdquit);
frm1.addCommand(cmdsearch);
frm1.append(strSearch);
frm2.addCommand(cmdsearch);
frm2.addCommand(cmdback);
frm2.append(txtfsearch);
frm2.append(chgsearchcase);
frm2.append("");
frm2.append("");
alert.addCommand(cmdsearch);
alert.addCommand(cmdback);
// Adding Command Listner
frm1.setCommandListener(this);
frm2.setCommandListener(this);
alert.setCommandListener(this);
}
public void startApp()
{
// Indicating the object to be Displayed
display.setCurrent(frm1);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command, Displayable displayable)
{
if(command == cmdquit)
{
// Indicating the object to be Displayed
destroyApp(false);
notifyDestroyed();
}
else if(command == cmdsearch)
{
// Indicating the object to be Displayed
if(displayable==frm1)
display.setCurrent(frm2);
}
else if(displayable == frm2)
{
strFind = txtfsearch.getString();
searchUtility();
}
else if(displayable == alert)
{
searchUtility();
}
}
else if(command == cmdback)
{
if(displayable == frm2)
{
display.setCurrent(frm1);
}
else if(displayable == alert)
{
display.setCurrent(frm2); strAlert =
""; flag = true;
}
}
}
public void searchUtility()
{
if(chgsearchcase.getSelectedIndex() == 0)
{
if(flag)
{
fromIndex = strSearch.indexOf(strFind);
flag = false;
}
else
fromIndex = strSearch.indexOf
(strFind, fromIndex + strFind.length());
if(fromIndex != -1)
{
strAlert += String.valueOf(fromIndex) + "\n";
alert.setString(strAlert);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
else
frm2.append(strFind + " does not found.");
}
else
{
if(flag)
{
strFind = strFind.toLowerCase();
strSearch = strSearch.toLowerCase();
fromIndex = strSearch.indexOf(strFind);
flag = false;
}
else
fromIndex = strSearch.indexOf
(strFind, fromIndex + strFind.length());
if(fromIndex != -1)
{
strAlert += String.valueOf
(fromIndex) + "\n";
alert.setString(strAlert);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
else
frm2.append(strFind + " does not found.");
}
}
}
Create an application in j2me to demonstrate that will search for a word present in the given paragraph with 2 options:
a. case sensitive
b. case insensitive
CODE
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class SearchMidlet extends MIDlet implements CommandListener
{
private Display display;
private Form frm1, frm2;
private TextField txtfsearch;
private Command cmdquit;
private Command cmdback;
private Command cmdsearch;
private String strSearch;
private String strFind;
private String strAlert = "The Searched word position is ";
private ChoiceGroup chgsearchcase;
private Alert alert;
private int fromIndex = 0;
private boolean flag = true;
public SearchMidlet()
{
// Indicating the object to be Displayed
display = Display.getDisplay(this);
//initializing Form’s object
frm1 = new Form("MIDP");
frm2 = new Form("Search Utility");
strSearch = "The J2ME Wireless Toolkit is a set of tools that makes it possible to createapplications for mobile phones and other wireless devices. Although it is based on the Mobile Information Device Profile (MIDP) 2.0, the J2ME Wireless Toolkit also supports a handful of optional packages, making it a widely capable development toolkit.";
//Initailizing TextField’s objects.
txtfsearch = new TextField("Search : ", "", 12, TextField.ANY);
//Initailizing save Command button
cmdquit = new Command("Quit", Command.EXIT, 0);
cmdback = new Command("Back", Command.EXIT, 1);
cmdsearch = new Command("Search", Command.SCREEN, 0);
chgsearchcase = new ChoiceGroup
("Search Case :", Choice.EXCLUSIVE);
//Adding Choice Group to form
chgsearchcase.append("Case Sensetive", null);
chgsearchcase.append("Case Insensetive", null);
//Initailizing Alert object
alert = new Alert
("Search Alert", "", null, AlertType.CONFIRMATION);
//Adding TextFeilds and Commands to from
frm1.addCommand(cmdquit);
frm1.addCommand(cmdsearch);
frm1.append(strSearch);
frm2.addCommand(cmdsearch);
frm2.addCommand(cmdback);
frm2.append(txtfsearch);
frm2.append(chgsearchcase);
frm2.append("");
frm2.append("");
alert.addCommand(cmdsearch);
alert.addCommand(cmdback);
// Adding Command Listner
frm1.setCommandListener(this);
frm2.setCommandListener(this);
alert.setCommandListener(this);
}
public void startApp()
{
// Indicating the object to be Displayed
display.setCurrent(frm1);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command, Displayable displayable)
{
if(command == cmdquit)
{
// Indicating the object to be Displayed
destroyApp(false);
notifyDestroyed();
}
else if(command == cmdsearch)
{
// Indicating the object to be Displayed
if(displayable==frm1)
display.setCurrent(frm2);
}
else if(displayable == frm2)
{
strFind = txtfsearch.getString();
searchUtility();
}
else if(displayable == alert)
{
searchUtility();
}
}
else if(command == cmdback)
{
if(displayable == frm2)
{
display.setCurrent(frm1);
}
else if(displayable == alert)
{
display.setCurrent(frm2); strAlert =
""; flag = true;
}
}
}
public void searchUtility()
{
if(chgsearchcase.getSelectedIndex() == 0)
{
if(flag)
{
fromIndex = strSearch.indexOf(strFind);
flag = false;
}
else
fromIndex = strSearch.indexOf
(strFind, fromIndex + strFind.length());
if(fromIndex != -1)
{
strAlert += String.valueOf(fromIndex) + "\n";
alert.setString(strAlert);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
else
frm2.append(strFind + " does not found.");
}
else
{
if(flag)
{
strFind = strFind.toLowerCase();
strSearch = strSearch.toLowerCase();
fromIndex = strSearch.indexOf(strFind);
flag = false;
}
else
fromIndex = strSearch.indexOf
(strFind, fromIndex + strFind.length());
if(fromIndex != -1)
{
strAlert += String.valueOf
(fromIndex) + "\n";
alert.setString(strAlert);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
else
frm2.append(strFind + " does not found.");
}
}
}
To Demonstrate Geometric Figure
PROBLEM STATEMENT
Create an application in j2me to demonstrate different events shapes, circle, square, rectangle, triangle on canvas.
CODE
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class practical8 extends MIDlet implements CommandListener
{
Display display;
public mycanvas can;
public practical8()
{
display=Display.getDisplay(this);
can=new mycanvas(this);
display.setCurrent(can);
}
public void startApp()
{
display.setCurrent(can);
}
public void pauseApp(){}
public void destroyApp(boolean unconditional) throws MIDletStateChangeException
{
destroyApp(false);
notifyDestroyed();
}
public void finishp()
{
// Indicating the object to be Displayed
notifyDestroyed();
}
public void commandAction(Command c, Displayable d)
{
}
}
class mycanvas extends Canvas implements CommandListener
{
//declearing & Initailizing Command buttons
private Command cmdexit;
practical8 p;
int i;
String str1="Press 1 for Square";
String str2="Press 2 for Rectangle";
String str3="Press 3 for Traingle";
String str4="Press 4 for Circle";
public mycanvas(practical8 p)
{
this.p= p;
//Initailizing exit Command button
cmdexit=new Command("EXIT",Command.EXIT,1);
//Adding Command buttons to the Canvas
addCommand(cmdexit);
// Adding Command Listner
setCommandListener(this);
}
protected void paint (Graphics g)
{
g.setColor(0xffffff);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0xff000000);
g.drawString(str1,50,230,Graphics.BOTTOM|Graphics.LEF);
g.drawString(str2,50,241,Graphics.BOTTOM|Graphics.LEFT);
g.drawString(str3,50,252,Graphics.BOTTOM|Graphics.LEFT);
g.drawString(str4,50,263,Graphics.BOTTOM|Graphics.LEFT);
if(i==1)
{
g.setColor(0xff0000);
g.drawRect(getWidth()/4,getWidth()/4,getWidth()/4,
getHeight()/5);
repaint();
}
if(i==2)
{
g.setColor(0xff0000);
g.drawRect(getHeight()/4, getWidth()/2,(getHeight()/4)+2,
(getWidth()/2)+2);
repaint();
}
if(i==4)
{
g.setColor(0xff0000);
g.drawArc(getWidth()/4,getWidth()/4,getWidth()/4,
getWidth()/4,360,-360);
repaint();
}
if(i==3)
{
g.setColor(0xff0000);
g.drawLine(30,getHeight()/2,
getWidth()-50,getHeight()/2);
g.drawLine(30,getHeight()/4,
getWidth()-50,getHeight()/2);
g.drawLine(30,getHeight()/2,30,getHeight()/4);
repaint();
}
}
public void commandAction(Command c, Displayable d)
{
if(c==cmdexit)
{
p.finishp();
}
repaint();
}
protected void keyPressed(int key)
{
try
{
switch ( key )
{
case KEY_NUM1:
i=1;
break;
case KEY_NUM2:
i=2;
break;
case KEY_NUM3:
i=3;
break;
case KEY_NUM4:
i=4;
break;
}
}
catch(Exception e){}
repaint();
}
}
Create an application in j2me to demonstrate different events shapes, circle, square, rectangle, triangle on canvas.
CODE
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class practical8 extends MIDlet implements CommandListener
{
Display display;
public mycanvas can;
public practical8()
{
display=Display.getDisplay(this);
can=new mycanvas(this);
display.setCurrent(can);
}
public void startApp()
{
display.setCurrent(can);
}
public void pauseApp(){}
public void destroyApp(boolean unconditional) throws MIDletStateChangeException
{
destroyApp(false);
notifyDestroyed();
}
public void finishp()
{
// Indicating the object to be Displayed
notifyDestroyed();
}
public void commandAction(Command c, Displayable d)
{
}
}
class mycanvas extends Canvas implements CommandListener
{
//declearing & Initailizing Command buttons
private Command cmdexit;
practical8 p;
int i;
String str1="Press 1 for Square";
String str2="Press 2 for Rectangle";
String str3="Press 3 for Traingle";
String str4="Press 4 for Circle";
public mycanvas(practical8 p)
{
this.p= p;
//Initailizing exit Command button
cmdexit=new Command("EXIT",Command.EXIT,1);
//Adding Command buttons to the Canvas
addCommand(cmdexit);
// Adding Command Listner
setCommandListener(this);
}
protected void paint (Graphics g)
{
g.setColor(0xffffff);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0xff000000);
g.drawString(str1,50,230,Graphics.BOTTOM|Graphics.LEF);
g.drawString(str2,50,241,Graphics.BOTTOM|Graphics.LEFT);
g.drawString(str3,50,252,Graphics.BOTTOM|Graphics.LEFT);
g.drawString(str4,50,263,Graphics.BOTTOM|Graphics.LEFT);
if(i==1)
{
g.setColor(0xff0000);
g.drawRect(getWidth()/4,getWidth()/4,getWidth()/4,
getHeight()/5);
repaint();
}
if(i==2)
{
g.setColor(0xff0000);
g.drawRect(getHeight()/4, getWidth()/2,(getHeight()/4)+2,
(getWidth()/2)+2);
repaint();
}
if(i==4)
{
g.setColor(0xff0000);
g.drawArc(getWidth()/4,getWidth()/4,getWidth()/4,
getWidth()/4,360,-360);
repaint();
}
if(i==3)
{
g.setColor(0xff0000);
g.drawLine(30,getHeight()/2,
getWidth()-50,getHeight()/2);
g.drawLine(30,getHeight()/4,
getWidth()-50,getHeight()/2);
g.drawLine(30,getHeight()/2,30,getHeight()/4);
repaint();
}
}
public void commandAction(Command c, Displayable d)
{
if(c==cmdexit)
{
p.finishp();
}
repaint();
}
protected void keyPressed(int key)
{
try
{
switch ( key )
{
case KEY_NUM1:
i=1;
break;
case KEY_NUM2:
i=2;
break;
case KEY_NUM3:
i=3;
break;
case KEY_NUM4:
i=4;
break;
}
}
catch(Exception e){}
repaint();
}
}
To Demonstrate Key Pressed
PROBLEM STATEMENT
Create an application in j2me to demonstrate Different picture by pressing selected button.
CODE
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class practical7 extends MIDlet
{
//Declaring Display’s object
Display display;
//Declaring mycanvas’s object
public mycanvas can;
String s;
public practical7()
{
// Indicating the object to be Displayed
display=Display.getDisplay(this);
//Initailizing mycanvas object.
can=new mycanvas(this);
// setting the mycanvas object to Display to get Displayed
display.setCurrent(can);
}
public void startApp()
{
// setting the mycanvas object to Display to get Displayed
display.setCurrent(can);
}
public void pauseApp(){}
public void destroyApp(boolean unconditional)
{
// Indicating the object to be Displayed
destroyApp(false);
notifyDestroyed();
}
public void exitMIDlet()
{
// Indicating the object to be Displayed
destroyApp(true);
notifyDestroyed();
}
}
class mycanvas extends Canvas implements CommandListener
{
private Command exit;
private static Image image;
private practical7 prac7;
public mycanvas (practical7 prac7)
{
this.prac7 = prac7;
//Initailizing exit Command button
exit = new Command("Exit", Command.EXIT, 1);
addCommand(exit);
// Adding Command Listner
setCommandListener(this);
try
{
// create the image and assign it to the variable
image of the type Image
image = Image.createImage("/0.png");
}
catch(Exception ex)
{
//message get displayed if the image is not get assigned properly.
System.out.println("Image not found : " + ex);
}
}
protected void paint(Graphics g)
{
repaint();
// Drawing a WHTE Rectangle for the Background
g.setColor(255,255,255);
g.fillRect(0, 0, getWidth(), getHeight());
try
{
//displaying the image at the center of the screen
g.drawImage(image, 100,100,g.TOP|g.HCENTER);
}
catch (Exception e){}
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
prac7.exitMIDlet();
}
}
protected void keyPressed(int key)
{
try
{
//capture user response when key pressed & accordingly display the images
switch ( key )
{
case KEY_NUM1:
image = Image.createImage("/1.png");
break;
case KEY_NUM2:
image = Image.createImage("/2.png");
break;
case KEY_NUM3:
image = Image.createImage("/3.png");
break;
case KEY_NUM4:
image = Image.createImage("/4.png");
break;
case KEY_NUM5:
image = Image.createImage("/5.png");
break;
case KEY_NUM6:
image = Image.createImage("/6.png");
break;
case KEY_NUM7:
image = Image.createImage("/7.png");
break;
case KEY_NUM8:
image = Image.createImage("/8.png");
break;
case KEY_NUM9:
image = Image.createImage("/9.png");
break;
case KEY_NUM0:
image = Image.createImage("/2.png");
break;
}
}
catch(Exception e){}
repaint();
}
}
Create an application in j2me to demonstrate Different picture by pressing selected button.
CODE
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class practical7 extends MIDlet
{
//Declaring Display’s object
Display display;
//Declaring mycanvas’s object
public mycanvas can;
String s;
public practical7()
{
// Indicating the object to be Displayed
display=Display.getDisplay(this);
//Initailizing mycanvas object.
can=new mycanvas(this);
// setting the mycanvas object to Display to get Displayed
display.setCurrent(can);
}
public void startApp()
{
// setting the mycanvas object to Display to get Displayed
display.setCurrent(can);
}
public void pauseApp(){}
public void destroyApp(boolean unconditional)
{
// Indicating the object to be Displayed
destroyApp(false);
notifyDestroyed();
}
public void exitMIDlet()
{
// Indicating the object to be Displayed
destroyApp(true);
notifyDestroyed();
}
}
class mycanvas extends Canvas implements CommandListener
{
private Command exit;
private static Image image;
private practical7 prac7;
public mycanvas (practical7 prac7)
{
this.prac7 = prac7;
//Initailizing exit Command button
exit = new Command("Exit", Command.EXIT, 1);
addCommand(exit);
// Adding Command Listner
setCommandListener(this);
try
{
// create the image and assign it to the variable
image of the type Image
image = Image.createImage("/0.png");
}
catch(Exception ex)
{
//message get displayed if the image is not get assigned properly.
System.out.println("Image not found : " + ex);
}
}
protected void paint(Graphics g)
{
repaint();
// Drawing a WHTE Rectangle for the Background
g.setColor(255,255,255);
g.fillRect(0, 0, getWidth(), getHeight());
try
{
//displaying the image at the center of the screen
g.drawImage(image, 100,100,g.TOP|g.HCENTER);
}
catch (Exception e){}
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
prac7.exitMIDlet();
}
}
protected void keyPressed(int key)
{
try
{
//capture user response when key pressed & accordingly display the images
switch ( key )
{
case KEY_NUM1:
image = Image.createImage("/1.png");
break;
case KEY_NUM2:
image = Image.createImage("/2.png");
break;
case KEY_NUM3:
image = Image.createImage("/3.png");
break;
case KEY_NUM4:
image = Image.createImage("/4.png");
break;
case KEY_NUM5:
image = Image.createImage("/5.png");
break;
case KEY_NUM6:
image = Image.createImage("/6.png");
break;
case KEY_NUM7:
image = Image.createImage("/7.png");
break;
case KEY_NUM8:
image = Image.createImage("/8.png");
break;
case KEY_NUM9:
image = Image.createImage("/9.png");
break;
case KEY_NUM0:
image = Image.createImage("/2.png");
break;
}
}
catch(Exception e){}
repaint();
}
}
To Demonstrate Dialog Box
PROBLEM STATEMENT
Write an application to demonstrate a dialog box.
CODE
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class practical6 extends MIDlet implements CommandListener
{
Form form1;
Display display;
Command save;
public TextField tfname,tfoc,tfcolor,tfgame;
String s="Saving Data...........";
Alert al;
public practical6()
{
try
{
// Indicating the object to be Displayed
display=Display.getDisplay(this);
//initializing Form’s object
form1=new Form("");
//Initailizing save Command button
save=new Command("SAVE",Command.ITEM,1);
//Initailizing TextField’s objects.
tfname=new TextField
("Enter Name:","",15,TextField.ANY);
tfoc=new TextField("Enter OCCUPATION","",20,TextField.ANY);
tfcolor=new TextField("Enter Favourite Color","",8,TextField.ANY);
tfgame=new TextField("Enter Favourite Game","",10,TextField.ANY);
//Adding TextFeilds and Commands to from1
form1.append(tfname);
form1.append(tfoc);
form1.append(tfcolor);
form1.append(tfgame);
form1.addCommand(save);
//Initailizing Image object.
Image im = Image.createImage("/p2.gif");
//Initailizing Alert object for image saving Conformation.
al=new Alert("New Alert", " Saving Data...........", im, AlertType.CONFIRMATION);
// Adding Command Listner
form1.setCommandListener(this);
}
catch(Exception e)
{
// message is displayed if the error occurs while reading the file .
System.out.println("Unable to read png image.");
}
}
public void startApp()
{
// Indicating the object to be Displayed
display.setCurrent(form1);
}
public void pauseApp(){}
public void destroyApp(boolean Unconditional)
{
// Indicating the object to be Displayed
destroyApp(false);
notifyDestroyed();
}
public void endp()
{
// Indicating the object to be Displayed
destroyApp(false);
notifyDestroyed();
}
public void commandAction(Command c, Displayable d)
{
if(c==save)
{
display.setCurrent(al, form1);
al.setTimeout(Alert.FOREVER);
}
}
}
Write an application to demonstrate a dialog box.
CODE
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class practical6 extends MIDlet implements CommandListener
{
Form form1;
Display display;
Command save;
public TextField tfname,tfoc,tfcolor,tfgame;
String s="Saving Data...........";
Alert al;
public practical6()
{
try
{
// Indicating the object to be Displayed
display=Display.getDisplay(this);
//initializing Form’s object
form1=new Form("");
//Initailizing save Command button
save=new Command("SAVE",Command.ITEM,1);
//Initailizing TextField’s objects.
tfname=new TextField
("Enter Name:","",15,TextField.ANY);
tfoc=new TextField("Enter OCCUPATION","",20,TextField.ANY);
tfcolor=new TextField("Enter Favourite Color","",8,TextField.ANY);
tfgame=new TextField("Enter Favourite Game","",10,TextField.ANY);
//Adding TextFeilds and Commands to from1
form1.append(tfname);
form1.append(tfoc);
form1.append(tfcolor);
form1.append(tfgame);
form1.addCommand(save);
//Initailizing Image object.
Image im = Image.createImage("/p2.gif");
//Initailizing Alert object for image saving Conformation.
al=new Alert("New Alert", " Saving Data...........", im, AlertType.CONFIRMATION);
// Adding Command Listner
form1.setCommandListener(this);
}
catch(Exception e)
{
// message is displayed if the error occurs while reading the file .
System.out.println("Unable to read png image.");
}
}
public void startApp()
{
// Indicating the object to be Displayed
display.setCurrent(form1);
}
public void pauseApp(){}
public void destroyApp(boolean Unconditional)
{
// Indicating the object to be Displayed
destroyApp(false);
notifyDestroyed();
}
public void endp()
{
// Indicating the object to be Displayed
destroyApp(false);
notifyDestroyed();
}
public void commandAction(Command c, Displayable d)
{
if(c==save)
{
display.setCurrent(al, form1);
al.setTimeout(Alert.FOREVER);
}
}
}
To demonstrate different “INPUT BOXES”
PROBLEM STATEMENT
Write a program in J2ME to demonstrate different input boxes.
1.Edit Box(Text Box)
2.Buttons
3.Radio Buttons
4.Check Box
5.List Box.
CODE
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Practical3 extends MIDlet implements CommandListener
{
private Command exit,next;
private TextField tb1;
private Form frm1;
private Display display;
private ChoiceGroup rb;
private ChoiceGroup cb;
private List list;
private Alert alert;
private String[] options={"Option A","Option B"};
public Practical3()
{
next=new Command("NEXT",Command.SCREEN,0);
exit=new Command("Exit",Command.SCREEN,0);
frm1=new Form("Practical3");
tb1=new TextField("Enter Name","",30,TextField.ANY);
rb=new ChoiceGroup("Option",Choice.EXCLUSIVE);
rb.append("Male",null);
rb.append("Female",null);
cb=new ChoiceGroup("Option",Choice.MULTIPLE);
cb.append("Red",null);
cb.append("Green",null);
list=new List("Menu:",List.IMPLICIT,options,null);
list.addCommand(next);
list.setCommandListener(this);
frm1.append(tb1);
frm1.append(rb);
frm1.append(cb);
frm1.addCommand(exit);
frm1.setCommandListener(this);
public void startApp()
{
display=Display.getDisplay(this);
display.setCurrent(list);
}
public void pauseApp(){ }
public void destroyApp(boolean b){ }
public void commandAction(Command c,Displayable d)
{
if(c==next)
{
alert=new Alert("Next Form","Moving To Next Form",null,null);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert,frm1);
}
if(c==exit)
{
destroyApp(true);
notifyDestroyed();
}
}
}
Write a program in J2ME to demonstrate different input boxes.
1.Edit Box(Text Box)
2.Buttons
3.Radio Buttons
4.Check Box
5.List Box.
CODE
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Practical3 extends MIDlet implements CommandListener
{
private Command exit,next;
private TextField tb1;
private Form frm1;
private Display display;
private ChoiceGroup rb;
private ChoiceGroup cb;
private List list;
private Alert alert;
private String[] options={"Option A","Option B"};
public Practical3()
{
next=new Command("NEXT",Command.SCREEN,0);
exit=new Command("Exit",Command.SCREEN,0);
frm1=new Form("Practical3");
tb1=new TextField("Enter Name","",30,TextField.ANY);
rb=new ChoiceGroup("Option",Choice.EXCLUSIVE);
rb.append("Male",null);
rb.append("Female",null);
cb=new ChoiceGroup("Option",Choice.MULTIPLE);
cb.append("Red",null);
cb.append("Green",null);
list=new List("Menu:",List.IMPLICIT,options,null);
list.addCommand(next);
list.setCommandListener(this);
frm1.append(tb1);
frm1.append(rb);
frm1.append(cb);
frm1.addCommand(exit);
frm1.setCommandListener(this);
public void startApp()
{
display=Display.getDisplay(this);
display.setCurrent(list);
}
public void pauseApp(){ }
public void destroyApp(boolean b){ }
public void commandAction(Command c,Displayable d)
{
if(c==next)
{
alert=new Alert("Next Form","Moving To Next Form",null,null);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert,frm1);
}
if(c==exit)
{
destroyApp(true);
notifyDestroyed();
}
}
}
Bouncing Ball
PROBLEM STATEMENT
Create an application to demonstrate Bouncing Ball, create a menu for the above with 2 options: start and stop to pause and resume the bouncing ball.
CODE
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class BouncingBallMidlet extends MIDlet {
//Declaring BouncingBallCanvas object
private BouncingBallCanvas bbc;
//Declaring Display object
private Display display;
public BouncingBallMidlet()
{
//Initailizing BouncingBallCanvas object.
bbc = new BouncingBallCanvas(this);
}
public void startApp()
{
// Indicating the object to be Displayed
display = Display.getDisplay(this);
display.setCurrent(bbc);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void exitButton()
{
// Indicating the object to be Displayed
destroyApp(false);
notifyDestroyed();
}
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.Random;
public class BouncingBallCanvas extends Canvas implements CommandListener, Runnable
{
BouncingBallMidlet bbm;
Display display;
Command quitCommand;
Command startCommand;
Command pauseCommand;
//Declaring Random’s object
Random rand;
//Declaring Thread’s object
Thread t;
int stopFlag;
int x, y;
int dx, dy;
int r, gr, b;
public BouncingBallCanvas()
{
}
public BouncingBallCanvas(BouncingBallMidlet bbm)
{
this.bbm = bbm;
// Indicating the object to be Displayed
display = Display.getDisplay(bbm);
//Initailizing Random’s object.
rand = new Random();
//Initailizing Command buttons
quitCommand = new Command("Quit", Command.EXIT, 0);
startCommand = new Command("Start", Command.SCREEN, 0);
pauseCommand = new Command("Pause", Command.STOP, 0);
//Adding Command to current form
addCommand(quitCommand);
addCommand(pauseCommand);
// Adding Command Listner
setCommandListener(this);
//Initailizing Thread’s object.
t = new Thread(this);
stopFlag = 0;
dx = 10;
dy = 10;
x = 8;
y = 12;
//Generating the Random number in the range of 0 to 255 and assigning it to the variable.
r = gr = b = Math.abs(rand.nextInt()%255);
//Starting the Thread t
t.start();
}
protected void paint(Graphics g)
{
g.setColor(255, 255, 255);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(r, gr, b);
g.fillArc(x , y, 20, 20, 0, 360);
if (x > getWidth()-23 || x < 8)
{
dx = -dx;
r = Math.abs(rand.nextInt()%255);
gr = Math.abs(rand.nextInt()%255);
b = Math.abs(rand.nextInt()%255);
}
if (y > getHeight()-21 || y < 12)
{
dy = -dy;
r = Math.abs(rand.nextInt()%255);
gr = Math.abs(rand.nextInt()%255);
b = Math.abs(rand.nextInt()%255);
}
x += dx;
y += dy;
}
//Condition to get and check the user input
Command getCurrentCommand()
{
switch(stopFlag)
{
case 0:
return pauseCommand;
case 1:
return startCommand;
default:
return startCommand;
}
}
public void commandAction(Command command, Displayabl displayable)
{
addCommand(getCurrentCommand());
if(command == quitCommand)
{
bbm.exitButton();
}
else if(command == startCommand)
{
t = new Thread(this);
stopFlag = 0;
this.removeCommand(startCommand);
addCommand(pauseCommand);
t.start();
}
else if(command == pauseCommand)
{
stopFlag = 1;
t = null;
this.removeCommand(pauseCommand);
addCommand(startCommand);
}
}
public void run()
{
for( ; ; )
{
try
{
repaint();
//Thread is sleep for 170 mill second
Thread.sleep(170);
if(stopFlag == 1)
break;
}
catch(InterruptedException ie)
{
}
}
}
}
Create an application to demonstrate Bouncing Ball, create a menu for the above with 2 options: start and stop to pause and resume the bouncing ball.
CODE
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class BouncingBallMidlet extends MIDlet {
//Declaring BouncingBallCanvas object
private BouncingBallCanvas bbc;
//Declaring Display object
private Display display;
public BouncingBallMidlet()
{
//Initailizing BouncingBallCanvas object.
bbc = new BouncingBallCanvas(this);
}
public void startApp()
{
// Indicating the object to be Displayed
display = Display.getDisplay(this);
display.setCurrent(bbc);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void exitButton()
{
// Indicating the object to be Displayed
destroyApp(false);
notifyDestroyed();
}
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.Random;
public class BouncingBallCanvas extends Canvas implements CommandListener, Runnable
{
BouncingBallMidlet bbm;
Display display;
Command quitCommand;
Command startCommand;
Command pauseCommand;
//Declaring Random’s object
Random rand;
//Declaring Thread’s object
Thread t;
int stopFlag;
int x, y;
int dx, dy;
int r, gr, b;
public BouncingBallCanvas()
{
}
public BouncingBallCanvas(BouncingBallMidlet bbm)
{
this.bbm = bbm;
// Indicating the object to be Displayed
display = Display.getDisplay(bbm);
//Initailizing Random’s object.
rand = new Random();
//Initailizing Command buttons
quitCommand = new Command("Quit", Command.EXIT, 0);
startCommand = new Command("Start", Command.SCREEN, 0);
pauseCommand = new Command("Pause", Command.STOP, 0);
//Adding Command to current form
addCommand(quitCommand);
addCommand(pauseCommand);
// Adding Command Listner
setCommandListener(this);
//Initailizing Thread’s object.
t = new Thread(this);
stopFlag = 0;
dx = 10;
dy = 10;
x = 8;
y = 12;
//Generating the Random number in the range of 0 to 255 and assigning it to the variable.
r = gr = b = Math.abs(rand.nextInt()%255);
//Starting the Thread t
t.start();
}
protected void paint(Graphics g)
{
g.setColor(255, 255, 255);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(r, gr, b);
g.fillArc(x , y, 20, 20, 0, 360);
if (x > getWidth()-23 || x < 8)
{
dx = -dx;
r = Math.abs(rand.nextInt()%255);
gr = Math.abs(rand.nextInt()%255);
b = Math.abs(rand.nextInt()%255);
}
if (y > getHeight()-21 || y < 12)
{
dy = -dy;
r = Math.abs(rand.nextInt()%255);
gr = Math.abs(rand.nextInt()%255);
b = Math.abs(rand.nextInt()%255);
}
x += dx;
y += dy;
}
//Condition to get and check the user input
Command getCurrentCommand()
{
switch(stopFlag)
{
case 0:
return pauseCommand;
case 1:
return startCommand;
default:
return startCommand;
}
}
public void commandAction(Command command, Displayabl displayable)
{
addCommand(getCurrentCommand());
if(command == quitCommand)
{
bbm.exitButton();
}
else if(command == startCommand)
{
t = new Thread(this);
stopFlag = 0;
this.removeCommand(startCommand);
addCommand(pauseCommand);
t.start();
}
else if(command == pauseCommand)
{
stopFlag = 1;
t = null;
this.removeCommand(pauseCommand);
addCommand(startCommand);
}
}
public void run()
{
for( ; ; )
{
try
{
repaint();
//Thread is sleep for 170 mill second
Thread.sleep(170);
if(stopFlag == 1)
break;
}
catch(InterruptedException ie)
{
}
}
}
}
To demonstrate “TIMER”
PROBLEM STATEMENT
Create an application to display text moving across the screen ad change the background along the moving text.
CODE
//MovingBannerMidlet.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MovingBannerMidlet extends MIDlet {
//Declaring object/s
MovingBannerCanvas mbc;
Display display;
public MovingBannerMidlet()
{
//Initailizing MovingBannerCanvas object.
mbc = new MovingBannerCanvas(this);
}
public void startApp()
{
// Indicating the object to be Displayed
display = Display.getDisplay(this);
display.setCurrent(mbc);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void exitButton()
{
// Notifying that the object is Destroyed
destroyApp(false);
notifyDestroyed();
}
}
//MovingBannerCanvas.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;
public class MovingBannerCanvas extends Canvas implements CommandListener, Runnable {
//Declaring Objects and variables
MovingBannerMidlet mbm;
Display display;
Command cmdquit;
Command cmdstart;
Command cmdpause;
Random random;
String strmessage = " University Department of Information Technology ";
Thread t = null;
int stopFlag, x, y, z, x1, y1, z1;
public MovingBannerCanvas() { }
public MovingBannerCanvas(MovingBannerMidlet mbm)
{
this.mbm = mbm;
//Initailizing Objects and variables
display = Display.getDisplay(mbm);
cmdquit = new Command("Quit", Command.EXIT, 0);
cmdstart = new Command("Start", Command.SCREEN, 0);
cmdpause = new Command("Pause", Command.STOP, 1);
addCommand(cmdquit);
addCommand(cmdpause);
//Adding Command Listener
setCommandListener(this);
// initializing Random variable
random = new Random();
// initializing Thread to get process the current object
t = new Thread(this);
stopFlag = 0;
//Starting the execution of the thread process
t.start();
}
protected void paint(Graphics g)
{
g.setColor(x = Math.abs(random.nextInt()%255), y = Math.abs(random.nextInt()%255), z = Math.abs(random.nextInt()%255));
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Math.abs(x1 = random.nextInt()%255), y1 = Math.abs(random.nextInt()%255), z1 = Math.abs(random.nextInt()%255));
if(x == x1 | y == y1 | z == z1)
{
g.setColor(Math.abs(random.nextInt()%255), Math.abs(random.nextInt()%255), Math.abs(random.nextInt()%255));
}
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN, Font.SIZE_LARGE));
g.drawString(strmessage, getWidth()/2, getHeight()/2, Graphics.TOP | Graphics.HCENTER );
}
Command getCurrentCommand(){
switch(stopFlag)
{
case 0:
return cmdpause;
case 1:
return cmdstart;
default:
return cmdstart;
}
}
public void commandAction(Command command, Displayable displayable)
{
addCommand(getCurrentCommand());
if(command == cmdquit)
{
bm.exitButton();
}
else if(command == cmdstart)
{
t = new Thread(this);
stopFlag = 0;
this.removeCommand(cmdstart);
addCommand(cmdpause);
t.start();
}
else if(command == cmdpause)
{
stopFlag = 1;
t = null;
this.removeCommand(cmdpause);
addCommand(cmdstart);
}
}
public void run()
{
char ch;
for( ; ; )
{
try
{
Rpaint();
Thread.sleep(250);
ch = strmessage.charAt(0);
strmessage = strmessage.substring(1, strmessage.length());
strmessage += ch;
if(stopFlag == 1)
break;
} catch(InterruptedException ie) {
}
}
}
}
Create an application to display text moving across the screen ad change the background along the moving text.
CODE
//MovingBannerMidlet.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MovingBannerMidlet extends MIDlet {
//Declaring object/s
MovingBannerCanvas mbc;
Display display;
public MovingBannerMidlet()
{
//Initailizing MovingBannerCanvas object.
mbc = new MovingBannerCanvas(this);
}
public void startApp()
{
// Indicating the object to be Displayed
display = Display.getDisplay(this);
display.setCurrent(mbc);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void exitButton()
{
// Notifying that the object is Destroyed
destroyApp(false);
notifyDestroyed();
}
}
//MovingBannerCanvas.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;
public class MovingBannerCanvas extends Canvas implements CommandListener, Runnable {
//Declaring Objects and variables
MovingBannerMidlet mbm;
Display display;
Command cmdquit;
Command cmdstart;
Command cmdpause;
Random random;
String strmessage = " University Department of Information Technology ";
Thread t = null;
int stopFlag, x, y, z, x1, y1, z1;
public MovingBannerCanvas() { }
public MovingBannerCanvas(MovingBannerMidlet mbm)
{
this.mbm = mbm;
//Initailizing Objects and variables
display = Display.getDisplay(mbm);
cmdquit = new Command("Quit", Command.EXIT, 0);
cmdstart = new Command("Start", Command.SCREEN, 0);
cmdpause = new Command("Pause", Command.STOP, 1);
addCommand(cmdquit);
addCommand(cmdpause);
//Adding Command Listener
setCommandListener(this);
// initializing Random variable
random = new Random();
// initializing Thread to get process the current object
t = new Thread(this);
stopFlag = 0;
//Starting the execution of the thread process
t.start();
}
protected void paint(Graphics g)
{
g.setColor(x = Math.abs(random.nextInt()%255), y = Math.abs(random.nextInt()%255), z = Math.abs(random.nextInt()%255));
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Math.abs(x1 = random.nextInt()%255), y1 = Math.abs(random.nextInt()%255), z1 = Math.abs(random.nextInt()%255));
if(x == x1 | y == y1 | z == z1)
{
g.setColor(Math.abs(random.nextInt()%255), Math.abs(random.nextInt()%255), Math.abs(random.nextInt()%255));
}
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN, Font.SIZE_LARGE));
g.drawString(strmessage, getWidth()/2, getHeight()/2, Graphics.TOP | Graphics.HCENTER );
}
Command getCurrentCommand(){
switch(stopFlag)
{
case 0:
return cmdpause;
case 1:
return cmdstart;
default:
return cmdstart;
}
}
public void commandAction(Command command, Displayable displayable)
{
addCommand(getCurrentCommand());
if(command == cmdquit)
{
bm.exitButton();
}
else if(command == cmdstart)
{
t = new Thread(this);
stopFlag = 0;
this.removeCommand(cmdstart);
addCommand(cmdpause);
t.start();
}
else if(command == cmdpause)
{
stopFlag = 1;
t = null;
this.removeCommand(cmdpause);
addCommand(cmdstart);
}
}
public void run()
{
char ch;
for( ; ; )
{
try
{
Rpaint();
Thread.sleep(250);
ch = strmessage.charAt(0);
strmessage = strmessage.substring(1, strmessage.length());
strmessage += ch;
if(stopFlag == 1)
break;
} catch(InterruptedException ie) {
}
}
}
}
To Demonstrate Multiple Forms
PROBLEM STATEMENT
Create an application to draw simple text and perform various operations:
1. Change the Background Color.
2. Change the Text Color (Foreground).
3. Changing the Font Style
4. Change the Font Size of displayed text.
CODE
import javax.microedition.
midlet.*;
import javax.microedition.lcdui.*;
public class Pracs1 extends MIDlet implements CommandListener
{
//Declearing Display object
private Display display;
//Declearing Command objects
private Command cmdexit;
private Command cmdchange;
private Command cmdfontcolor;
private Command cmdfontsize;
private Command cmdfontstyle;
//Declearing Form object
private Form frmMain;
//Declearing TextField object
public TextField txt1;
//Declearing back(User Define Class) object
private back b;
//Declearing size(User define Class) object
private size s;
//Declearing style(User Define Class) object
private style st;
//Declearing Fcolor(User Define Class) object
private Fcolor f;
public Pracs1()
{
//Initailizing Display object
display= Display.getDisplay(this);
//Initailizing TextField object
txt1=new TextField("Enter a valid string to be displayed","",40,TextField.ANY);
//Initailizing Command buttons
cmdchange= new Command("Change BG Color",Command.SCREEN,1);
cmdexit= new Command("Exit", Command.EXIT,2);
cmdfontcolor= new Command(" Change FontColor",Command.SCREEN,2);
cmdfontsize= new Command("Change FontSize", Command.SCREEN,2);
cmdfontstyle= new Command("Change FontStyle", Command.SCREEN,2);
//Initailizing Form
frmMain= new Form("Practical 1");
//Adding Commands to frmf1
frmMain.addCommand(cmdexit);
frmMain.addCommand(cmdfontcolor);
frmMain.addCommand(cmdfontsize);
frmMain.addCommand(cmdfontstyle);
frmMain.addCommand(cmdchange);
//Adding TextField to frmMain
frmMain.append(txt1);
//Setting the CommandListener to form f1
frmMain.setCommandListener(this);
b= new back(this);
s= new size (this);
st= new style(this);
f= new Fcolor(this);
}
public void startApp() throws MIDletStateChangeException
{
//Setting the object to be Displayed
display.setCurrent(frmMain);
}
public void pauseApp()
{
}
public void destroyApp (boolean unconditional)
{
}
public void dgoback()
{
//Setting the object to be Displayed
display.setCurrent(frmMain);
}
public void commandAction (Command c, Displayable d)
{
/*
Setting the object to be Displayed as per the user input */
if (c==cmdfontcolor)
{
display.setCurrent(f);
}
else if (c==cmdfontstyle)
{
display.setCurrent(st);
}
else if ( c==cmdexit)
{
// Notifying that the object is Destroyed
dgoback();
}
else if (c==cmdchange)
{
display.setCurrent(b);
}
else if(c==cmdfontsize)
{
display.setCurrent(s);
}
}
}
class back extends Canvas implements CommandListener
{
private int i;
//Declaring Exit Command button
private Command cmdexit;
//Initailizing Commands buttons
private Command cmdRED = new Command("RED", Command.SCREEN, 1);
private Command cmdGREEN = new Command("GREEN", Command.SCREEN, 1);
private Command cmdBLUE = new Command("BLUE", Command.SCREEN, 1);
//Declaring Pracs1 object
private Pracs1 p;
public back(Pracs1 p)
{
this.p= p;
//Initailizing exit Command button
cmdexit= new Command("Back", Command.EXIT,0);
//Adding Command button to the frmf1
addCommand(cmdexit);
addCommand(cmdRED);
addCommand(cmdGREEN);
addCommand(cmdBLUE);
// Adding Command Listner
setCommandListener(this);
}
protected void paint (Graphics g)
{
// Drawing a Blank White Rectangle for the Background
g.setColor(255,255,255);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
//Drawing the String on the Canvas
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
//Drawing a Rectangle for the Background as per use choice
switch(i)
{
case 1:
// Drawing a RED Rectangle for the Background
g.setColor(255,0,0);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);;
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 2:
// Drawing a BLUE Rectangle for the Background
g.setColor(0,255,0);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 3:
// Drawing a GREEN Rectangle for the Background
g.setColor(0,0,255);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
default:
break;
}
}
public void commandAction(Command c, Displayable d)
{
if(c==cmdexit)
{
p.dgoback();
}
else if (c==cmdRED)
{
i=1;
repaint();
}
else if (c==cmdGREEN)
{
i=2;
repaint();
}
else if (c==cmdBLUE)
{
i=3;
repaint();
}
}
}
class Fcolor extends Canvas implements CommandListener
{
private int i;
private Command cmdexit;
private Command cmdRED = new Command("RED", Command.SCREEN, 1);
private Command cmdGREEN = new Command("GREEN", Command.SCREEN, 1);
private Command cmdBLUE = new Command("BLUE", Command.SCREEN, 1);
private Pracs1 p;
public Fcolor(Pracs1 p)
{
this.p= p;
//Initializing Exit Command buttons
cmdexit= new Command("Back", Command.EXIT,0);
//Adding Command button to the frmf1
addCommand(cmdexit);
addCommand(cmdRED);
addCommand(cmdGREEN);
addCommand(cmdBLUE);
setCommandListener(this);
}
protected void paint (Graphics g)
{
g.setColor(255,255,255);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
switch(i)
{
case 1:
g.setColor(255,0,0);
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 2:
g.setColor(0,255,0);
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 3:
g.setColor(0,0,255);
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
default:
break;
}
}
public void commandAction(Command c, Displayable d)
{
if(c==cmdexit)
{
p.dgoback();
}
else if (c==cmdRED)
{
i=1;
repaint();
}
else if (c==cmdGREEN)
{
i=2;
repaint();
}
else if (c==cmdBLUE)
{
i=3;
repaint();
}
}
}
class style extends Canvas implements CommandListener
{
private int i;
//Declaring Exit Command button
private Command cmdexit;
//Initailizing Command buttons
private Command cmdbold= new Command("BOLD", Command.SCREEN,1);
private Command cmditalic= new Command("ITALIC", Command.SCREEN,1);
private Command cmdunderlined= new Command("UNDERLINED", Command.SCREEN,1);
private Command cmdplain= new Command("PLAIN", Command.SCREEN,1);
//Delearing Pracs1 object
private Pracs1 p;
public style(Pracs1 p)
{
this.p= p;
//Initailizing exit Command button
cmdexit= new Command("Back", Command.EXIT,0);
//Adding Command buttons to the frmf1
addCommand(cmdexit);
addCommand(cmdbold);
addCommand(cmditalic);
addCommand(cmdunderlined);
addCommand(cmdplain);
//Adding Command Listener
setCommandListener(this);
}
public void paint (Graphics g)
{
// Drawing BLACK & WHITE Rectangle for the Background
g.setColor(255,255,255);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
/*
* Setting the Background Color
* Setting the FONT STYLE as per user choice
* Drawing the String on the Canvas
*/
switch(i)
{
case 1:
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_BOLD,Font.SIZE_LARGE));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 2:
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_ITALIC,Font.SIZE_LARGE));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 3:
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_UNDERLINED,Font.SIZE_LARGE));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 4:
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_PLAIN,Font.SIZE_LARGE));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
default:
break;
}
}
public void commandAction(Command c, Displayable d)
{
if(c==cmdexit)
{
p.dgoback();
}
else if (c==cmdbold)
{
i=1;
repaint();
}
else if (c==cmditalic)
{
i=2;
repaint();
}
else if (c==cmdunderlined)
{
i=3;
repaint();
}
else if (c==cmdplain)
{
i=4;
repaint();
}
}
}
class size extends Canvas implements CommandListener
{
private int i;
//Declaring exit Command button
private Command cmdexit;
//Initailizing Command buttons
private Command cmdlarge= new Command("LARGE", Command.SCREEN,0);
private Command cmdmedium= new Command("MEDIUM", Command.SCREEN,0);
private Command cmdsmall= new Command("SMALL", Command.SCREEN,0);
//Declaring Pracs1 objects
private Pracs1 p;
public size(Pracs1 p)
{
this.p= p;
//Initailizing exit Command button
cmdexit= new Command("Back", Command.EXIT,0);
//Adding Command buttons to the frmf1
addCommand(cmdexit);
addCommand(cmdlarge);
addCommand(cmdmedium);
addCommand(cmdsmall);
// Adding Command Listner
setCommandListener(this);
}
protected void paint (Graphics g)
{
g.setColor(255,255,255);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
/*
* Setting the Background Color
* Setting the FONT SIZE as per user choice
* Drawing the String on the Canvas
*/
switch(i)
{
case 1:
// * Setting the Background Color
g.setColor(0,0,0);
// Setting the FONT SIZE as per user choice
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_PLAIN,Font.SIZE_LARGE));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 2:
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_PLAIN,Font.SIZE_MEDIUM));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 3:
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_PLAIN,Font.SIZE_SMALL));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
default:
break;
}
}
public void commandAction(Command c, Displayable d)
{
if(c==cmdexit)
{
p.dgoback();
}
else if (c==cmdlarge)
{
i=1;
repaint();
}
else if (c==cmdmedium)
{
i=2;
repaint();
}
else if (c==cmdsmall)
{
i=3;
repaint();
}
}
}
Create an application to draw simple text and perform various operations:
1. Change the Background Color.
2. Change the Text Color (Foreground).
3. Changing the Font Style
4. Change the Font Size of displayed text.
CODE
import javax.microedition.
midlet.*;
import javax.microedition.lcdui.*;
public class Pracs1 extends MIDlet implements CommandListener
{
//Declearing Display object
private Display display;
//Declearing Command objects
private Command cmdexit;
private Command cmdchange;
private Command cmdfontcolor;
private Command cmdfontsize;
private Command cmdfontstyle;
//Declearing Form object
private Form frmMain;
//Declearing TextField object
public TextField txt1;
//Declearing back(User Define Class) object
private back b;
//Declearing size(User define Class) object
private size s;
//Declearing style(User Define Class) object
private style st;
//Declearing Fcolor(User Define Class) object
private Fcolor f;
public Pracs1()
{
//Initailizing Display object
display= Display.getDisplay(this);
//Initailizing TextField object
txt1=new TextField("Enter a valid string to be displayed","",40,TextField.ANY);
//Initailizing Command buttons
cmdchange= new Command("Change BG Color",Command.SCREEN,1);
cmdexit= new Command("Exit", Command.EXIT,2);
cmdfontcolor= new Command(" Change FontColor",Command.SCREEN,2);
cmdfontsize= new Command("Change FontSize", Command.SCREEN,2);
cmdfontstyle= new Command("Change FontStyle", Command.SCREEN,2);
//Initailizing Form
frmMain= new Form("Practical 1");
//Adding Commands to frmf1
frmMain.addCommand(cmdexit);
frmMain.addCommand(cmdfontcolor);
frmMain.addCommand(cmdfontsize);
frmMain.addCommand(cmdfontstyle);
frmMain.addCommand(cmdchange);
//Adding TextField to frmMain
frmMain.append(txt1);
//Setting the CommandListener to form f1
frmMain.setCommandListener(this);
b= new back(this);
s= new size (this);
st= new style(this);
f= new Fcolor(this);
}
public void startApp() throws MIDletStateChangeException
{
//Setting the object to be Displayed
display.setCurrent(frmMain);
}
public void pauseApp()
{
}
public void destroyApp (boolean unconditional)
{
}
public void dgoback()
{
//Setting the object to be Displayed
display.setCurrent(frmMain);
}
public void commandAction (Command c, Displayable d)
{
/*
Setting the object to be Displayed as per the user input */
if (c==cmdfontcolor)
{
display.setCurrent(f);
}
else if (c==cmdfontstyle)
{
display.setCurrent(st);
}
else if ( c==cmdexit)
{
// Notifying that the object is Destroyed
dgoback();
}
else if (c==cmdchange)
{
display.setCurrent(b);
}
else if(c==cmdfontsize)
{
display.setCurrent(s);
}
}
}
class back extends Canvas implements CommandListener
{
private int i;
//Declaring Exit Command button
private Command cmdexit;
//Initailizing Commands buttons
private Command cmdRED = new Command("RED", Command.SCREEN, 1);
private Command cmdGREEN = new Command("GREEN", Command.SCREEN, 1);
private Command cmdBLUE = new Command("BLUE", Command.SCREEN, 1);
//Declaring Pracs1 object
private Pracs1 p;
public back(Pracs1 p)
{
this.p= p;
//Initailizing exit Command button
cmdexit= new Command("Back", Command.EXIT,0);
//Adding Command button to the frmf1
addCommand(cmdexit);
addCommand(cmdRED);
addCommand(cmdGREEN);
addCommand(cmdBLUE);
// Adding Command Listner
setCommandListener(this);
}
protected void paint (Graphics g)
{
// Drawing a Blank White Rectangle for the Background
g.setColor(255,255,255);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
//Drawing the String on the Canvas
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
//Drawing a Rectangle for the Background as per use choice
switch(i)
{
case 1:
// Drawing a RED Rectangle for the Background
g.setColor(255,0,0);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);;
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 2:
// Drawing a BLUE Rectangle for the Background
g.setColor(0,255,0);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 3:
// Drawing a GREEN Rectangle for the Background
g.setColor(0,0,255);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
default:
break;
}
}
public void commandAction(Command c, Displayable d)
{
if(c==cmdexit)
{
p.dgoback();
}
else if (c==cmdRED)
{
i=1;
repaint();
}
else if (c==cmdGREEN)
{
i=2;
repaint();
}
else if (c==cmdBLUE)
{
i=3;
repaint();
}
}
}
class Fcolor extends Canvas implements CommandListener
{
private int i;
private Command cmdexit;
private Command cmdRED = new Command("RED", Command.SCREEN, 1);
private Command cmdGREEN = new Command("GREEN", Command.SCREEN, 1);
private Command cmdBLUE = new Command("BLUE", Command.SCREEN, 1);
private Pracs1 p;
public Fcolor(Pracs1 p)
{
this.p= p;
//Initializing Exit Command buttons
cmdexit= new Command("Back", Command.EXIT,0);
//Adding Command button to the frmf1
addCommand(cmdexit);
addCommand(cmdRED);
addCommand(cmdGREEN);
addCommand(cmdBLUE);
setCommandListener(this);
}
protected void paint (Graphics g)
{
g.setColor(255,255,255);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
switch(i)
{
case 1:
g.setColor(255,0,0);
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 2:
g.setColor(0,255,0);
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 3:
g.setColor(0,0,255);
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
default:
break;
}
}
public void commandAction(Command c, Displayable d)
{
if(c==cmdexit)
{
p.dgoback();
}
else if (c==cmdRED)
{
i=1;
repaint();
}
else if (c==cmdGREEN)
{
i=2;
repaint();
}
else if (c==cmdBLUE)
{
i=3;
repaint();
}
}
}
class style extends Canvas implements CommandListener
{
private int i;
//Declaring Exit Command button
private Command cmdexit;
//Initailizing Command buttons
private Command cmdbold= new Command("BOLD", Command.SCREEN,1);
private Command cmditalic= new Command("ITALIC", Command.SCREEN,1);
private Command cmdunderlined= new Command("UNDERLINED", Command.SCREEN,1);
private Command cmdplain= new Command("PLAIN", Command.SCREEN,1);
//Delearing Pracs1 object
private Pracs1 p;
public style(Pracs1 p)
{
this.p= p;
//Initailizing exit Command button
cmdexit= new Command("Back", Command.EXIT,0);
//Adding Command buttons to the frmf1
addCommand(cmdexit);
addCommand(cmdbold);
addCommand(cmditalic);
addCommand(cmdunderlined);
addCommand(cmdplain);
//Adding Command Listener
setCommandListener(this);
}
public void paint (Graphics g)
{
// Drawing BLACK & WHITE Rectangle for the Background
g.setColor(255,255,255);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
/*
* Setting the Background Color
* Setting the FONT STYLE as per user choice
* Drawing the String on the Canvas
*/
switch(i)
{
case 1:
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_BOLD,Font.SIZE_LARGE));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 2:
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_ITALIC,Font.SIZE_LARGE));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 3:
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_UNDERLINED,Font.SIZE_LARGE));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 4:
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_PLAIN,Font.SIZE_LARGE));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
default:
break;
}
}
public void commandAction(Command c, Displayable d)
{
if(c==cmdexit)
{
p.dgoback();
}
else if (c==cmdbold)
{
i=1;
repaint();
}
else if (c==cmditalic)
{
i=2;
repaint();
}
else if (c==cmdunderlined)
{
i=3;
repaint();
}
else if (c==cmdplain)
{
i=4;
repaint();
}
}
}
class size extends Canvas implements CommandListener
{
private int i;
//Declaring exit Command button
private Command cmdexit;
//Initailizing Command buttons
private Command cmdlarge= new Command("LARGE", Command.SCREEN,0);
private Command cmdmedium= new Command("MEDIUM", Command.SCREEN,0);
private Command cmdsmall= new Command("SMALL", Command.SCREEN,0);
//Declaring Pracs1 objects
private Pracs1 p;
public size(Pracs1 p)
{
this.p= p;
//Initailizing exit Command button
cmdexit= new Command("Back", Command.EXIT,0);
//Adding Command buttons to the frmf1
addCommand(cmdexit);
addCommand(cmdlarge);
addCommand(cmdmedium);
addCommand(cmdsmall);
// Adding Command Listner
setCommandListener(this);
}
protected void paint (Graphics g)
{
g.setColor(255,255,255);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(0,0,0);
/*
* Setting the Background Color
* Setting the FONT SIZE as per user choice
* Drawing the String on the Canvas
*/
switch(i)
{
case 1:
// * Setting the Background Color
g.setColor(0,0,0);
// Setting the FONT SIZE as per user choice
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_PLAIN,Font.SIZE_LARGE));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 2:
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_PLAIN,Font.SIZE_MEDIUM));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
case 3:
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_PLAIN,Font.SIZE_SMALL));
g.drawString(p.txt1.getString(),120,150,Graphics.TOP|Graphics.RIGHT);
break;
default:
break;
}
}
public void commandAction(Command c, Displayable d)
{
if(c==cmdexit)
{
p.dgoback();
}
else if (c==cmdlarge)
{
i=1;
repaint();
}
else if (c==cmdmedium)
{
i=2;
repaint();
}
else if (c==cmdsmall)
{
i=3;
repaint();
}
}
}
Intensity level slicing with Background and without Background
Note:-Write this code in Matlab
CODE
%Intensity level slicing with background%
clear all ;
clc;
p=imread('lily.tif');
z=double(p);
[row,col]=size(z);
for i=1:1:row
for j=1:1:col
if((z(i,j)>50)) && (z(i,j)<150)
z(i,j)=255;
else
z(i,j)=p(i,j);
end
end
end
figure(1); %-----------Original Image-------------%
imshow(p);
figure(2); %-----------Gray Level Slicing With Background-------------%
imshow(uint8(z));
Intensity Level slicing without background
CODE
%Intensity level slicing without background%
clear all;
clc;
p=imread('lily.tif');
z=double(p);
[row,col]=size(z)
for i=1:1:row
for j=1:1:col
if((z(i,j)>50)) && (z(i,j)<150)
z(i,j)=255;
else
z(i,j)=0;
end
end
end
figure(1); %-----------Original Image-------------%
imshow(p);
figure(2); %-----------Gray Level Slicing Without Background-------------%
imshow(uint8(z));
CODE
%Intensity level slicing with background%
clear all ;
clc;
p=imread('lily.tif');
z=double(p);
[row,col]=size(z);
for i=1:1:row
for j=1:1:col
if((z(i,j)>50)) && (z(i,j)<150)
z(i,j)=255;
else
z(i,j)=p(i,j);
end
end
end
figure(1); %-----------Original Image-------------%
imshow(p);
figure(2); %-----------Gray Level Slicing With Background-------------%
imshow(uint8(z));
Intensity Level slicing without background
CODE
%Intensity level slicing without background%
clear all;
clc;
p=imread('lily.tif');
z=double(p);
[row,col]=size(z)
for i=1:1:row
for j=1:1:col
if((z(i,j)>50)) && (z(i,j)<150)
z(i,j)=255;
else
z(i,j)=0;
end
end
end
figure(1); %-----------Original Image-------------%
imshow(p);
figure(2); %-----------Gray Level Slicing Without Background-------------%
imshow(uint8(z));
Tuesday, November 17, 2009
To perform Bit Plane slicing of a monochrome / 16 / 24 bit bitmap / JPEG / TIFF / GIF / Color image
Note:-Write this code in Matlab
CODE
%Bit plane slicing
clear all ;
clc;
a=imread('saturn.tif');
a=double(a);
r=input('Which Bit Image Do You Want To See 1=MSB 8=LSB');
[row,col]=size(a);
for x=1:1:row
for y=1:1:col
c=dec2bin(a(x,y),8);%Converts Decimal To Binary
d=c(r);
w(x,y)=double(d);%%Since w is Char and cannot Be Plotted
if w(x,y)==49%%Since Double Of d will be either 49 or 48
w(x,y)=255;
else
w(x,y)=0;
end
end
end
figure(1);
imshow(uint8(a));
figure(2);
imshow(uint8(w));
CODE
%Bit plane slicing
clear all ;
clc;
a=imread('saturn.tif');
a=double(a);
r=input('Which Bit Image Do You Want To See 1=MSB 8=LSB');
[row,col]=size(a);
for x=1:1:row
for y=1:1:col
c=dec2bin(a(x,y),8);%Converts Decimal To Binary
d=c(r);
w(x,y)=double(d);%%Since w is Char and cannot Be Plotted
if w(x,y)==49%%Since Double Of d will be either 49 or 48
w(x,y)=255;
else
w(x,y)=0;
end
end
end
figure(1);
imshow(uint8(a));
figure(2);
imshow(uint8(w));
To perform thesholding of a monochrome / 16 / 24 bit bitmap / JPEG / TIFF / GIF / Color image
Note:-Write this code in Matlab
CODE
% thresholding
clf;
clc;
clear all;
close all;
i=imread('camera.bmp');
subplot(1,2,1);
imshow(i);
title('original image');
r1=100;
[r c]=size(i);
for x=1:c
for y=1:r
if (i(y,x) i(y,x)=0;
else
i(y,x)=255;
end
end
end
subplot(1,2,2)
imshow(i);
title('thresholding image');
CODE
% thresholding
clf;
clc;
clear all;
close all;
i=imread('camera.bmp');
subplot(1,2,1);
imshow(i);
title('original image');
r1=100;
[r c]=size(i);
for x=1:c
for y=1:r
if (i(y,x)
else
i(y,x)=255;
end
end
end
subplot(1,2,2)
imshow(i);
title('thresholding image');
To perform Contrast Stretching of a monochrome / 16 /24 bit bitmap / JPEG / TIFF / GIF / Color image
Note:-Write this code in Matlab
CODE
%contrast stretching of image
clf;
clc;
clear all;
close all;
i=imread('camera.bmp');
subplot(1,2,1);
imshow(i);
title('original image');
i=double(i);
r1=100;
r2=150;
s1=175;
s2=250;
MAX=255;
[r c]=size(i);
for x=1:c
for y=1:r
if(i(y,x) < r1)
i(y,x)=(i(y,x)*(s1/r1));
if(i(y,x) < r2)
i(y,x)= s1 + (i(y,x)-r1)*((s2-s1)/(r2-r1));
else
i(y,x)= s2 +((i(y,x)-r2)*((MAX-s2)/(MAX-r2)));
end
end
end
end
i=uint8(i);
subplot(1,2,2)
imshow(i);
title('Contrast stretching image');
CODE
%contrast stretching of image
clf;
clc;
clear all;
close all;
i=imread('camera.bmp');
subplot(1,2,1);
imshow(i);
title('original image');
i=double(i);
r1=100;
r2=150;
s1=175;
s2=250;
MAX=255;
[r c]=size(i);
for x=1:c
for y=1:r
if(i(y,x) < r1)
i(y,x)=(i(y,x)*(s1/r1));
if(i(y,x) < r2)
i(y,x)= s1 + (i(y,x)-r1)*((s2-s1)/(r2-r1));
else
i(y,x)= s2 +((i(y,x)-r2)*((MAX-s2)/(MAX-r2)));
end
end
end
end
i=uint8(i);
subplot(1,2,2)
imshow(i);
title('Contrast stretching image');
To perform Negation of a monochrome / 16 / 24 bit bitmap / JPEG / TIFF / GIF / Color image
Note:- write this code in Matlab
CODE
%To create negative image
clf;
clf;
clear all;
close all;
i=imread('camera.bmp');
subplot(1,2,1);
imshow(i);
title('original image');
i=double(i);
[r c]=size(i);
for x=1:c
for y=1:r
i(y,x)=255-i(y,x);
end
end
i=uint8(i);
subplot(1,2,2)
imshow(i);
title('Negative image');
CODE
%To create negative image
clf;
clf;
clear all;
close all;
i=imread('camera.bmp');
subplot(1,2,1);
imshow(i);
title('original image');
i=double(i);
[r c]=size(i);
for x=1:c
for y=1:r
i(y,x)=255-i(y,x);
end
end
i=uint8(i);
subplot(1,2,2)
imshow(i);
title('Negative image');
To perform Negation of a monochrome / 16 / 24 bit bitmap / JPEG / TIFF / GIF / Color image
This code is in MATLAB
CODE
%To create negative image
clf;
clf;
clear all;
close all;
i=imread('camera.bmp');
subplot(1,2,1);
imshow(i);
title('original image');
i=double(i);
[r c]=size(i);
for x=1:c
for y=1:r
i(y,x)=255-i(y,x);
end
end
i=uint8(i);
subplot(1,2,2)
imshow(i);
title('Negative image');
CODE
%To create negative image
clf;
clf;
clear all;
close all;
i=imread('camera.bmp');
subplot(1,2,1);
imshow(i);
title('original image');
i=double(i);
[r c]=size(i);
for x=1:c
for y=1:r
i(y,x)=255-i(y,x);
end
end
i=uint8(i);
subplot(1,2,2)
imshow(i);
title('Negative image');
Demonstrate all types of 2D Transformation: a) Translation b) Scaling c) Rotation d) Reflection e) Shearing
CODE
#include
#include
#include
#include
#include
void main()
{
int gd=DETECT,i,j,gm,B[5][2],A[5][2],A1[5][2],x,y,tx=0,ty=0,sx=0,sy=0,a;
int rf,sh,shx,shy,yr,xr;
float r;
char ch;
ch= 'y';
enter: clrscr();
initgraph(&gd,&gm,"c:\\tc\\bgi");
x=getmaxx();
y=getmaxy();
setlinestyle(0,0,1);
setcolor(WHITE);
line (x/2,0,x/2,y);
line(0,y/2,x,y/2);
putpixel(x/2,y/2, BLACK);
outtextxy(x/2+2,y/2+2,"0");
putpixel(x/2+40,y/2, BLACK); //lits the pixel
outtextxy(x/2+40,y/2+2,"40");
putpixel(x/2+80,y/2, BLACK);
outtextxy(x/2+80,y/2+2,"80");
putpixel(x/2+120,y/2, BLACK);
outtextxy(x/2+120,y/2+2,"120");
putpixel(x/2+160,y/2, BLACK);
outtextxy(x/2+160,y/2+2,"160");
putpixel(x/2+200,y/2, BLACK);
outtextxy(x/2+200,y/2+2,"200");
putpixel(x/2+240,y/2, BLACK);
outtextxy(x/2+240,y/2+2,"240");
putpixel(x/2-40,y/2, BLACK);
outtextxy(x/2-40,y/2+2,"-40");
putpixel(x/2-80,y/2, BLACK);
outtextxy(x/2-80,y/2+2,"-80");
putpixel(x/2-120,y/2, BLACK);
outtextxy(x/2-120,y/2+2,"-120");
putpixel(x/2-160,y/2, BLACK);
outtextxy(x/2-160,y/2+2,"-160");
putpixel(x/2-200,y/2, BLACK);
outtextxy(x/2-200,y/2+2,"-200");
putpixel(x/2-240,y/2, BLACK);
outtextxy(x/2-240,y/2+2,"-240");
putpixel(x/2,y/2+40, BLACK);
outtextxy(x/2,y/2+40,"-40");
putpixel(x/2,y/2+80, BLACK);
outtextxy(x/2,y/2+80,"-80");
putpixel(x/2,y/2+120, BLACK);
outtextxy(x/2,y/2+120,"-120");
putpixel(x/2,y/2+160, BLACK);
outtextxy(x/2,y/2+160,"-160");
putpixel(x/2,y/2+200, BLACK);
outtextxy(x/2,y/2+200,"-200");
putpixel(x/2,y/2+240, BLACK);
outtextxy(x/2,y/2+240,"-240");
putpixel(x/2,y/2-40, BLACK);
outtextxy(x/2+2,y/2-40,"40");
putpixel(x/2,y/2-80, BLACK);
outtextxy(x/2+2,y/2-80,"80");
putpixel(x/2,y/2-120, BLACK);
outtextxy(x/2+2,y/2-120,"120");
putpixel(x/2,y/2-160, BLACK);
outtextxy(x/2+2,y/2-160,"160");
putpixel(x/2,y/2-200, BLACK);
outtextxy(x/2+2,y/2-200,"200");
putpixel(x/2,y/2-240,);
outtextxy(x/2+2,y/2-240,"240");
line(0,y,x,0);
line(0,0,x,y);
printf("\n1:Translation\n2:Scaling\n3:Rotation\n4:Reflection\n 5:Shearin g\nEnter your choice: ");
scanf("%d",&a);
switch(a)
{
case 1:
printf("enter first co-ordinates: ");
scanf(" %d %d",&A[0][0],&A[0][1]);
printf ("enter second co-ordinates: ");
scanf("%d %d",&A[1][0],&A[1][1]);
printf("enter third co-ordinates: ");
scanf("%d %d",&A[2][0],&A[2][1]);
for(i=0;i<3;i++)
{
A[i][0]=x/2+A[i][0];
A[i][1]=y/2-A[i][1];
}
A[3][0]=A[0][0];
A[3][1]=A[0][1];
setcolor(WHITE);
drawpoly(4,*A);
printf("\nEnter tx ty : ");
scanf("%d %d",&tx,&ty);
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=A[i][0]+tx;
B[i][1]=A[i][1]-ty;
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
break;
case 2:
printf("enter first co-ordinates: ");
scanf(" %d %d",&A[0][0],&A[0][1]);
printf ("enter second co-ordinates: ");
scanf("%d %d",&A[1][0],&A[1][1]);
printf("enter third co-ordinates: ");
scanf("%d %d",&A[2][0],&A[2][1]);
for(i=0;i<3;i++)
{
A1[i][0]=x/2+A[i][0];
A1[i][1]=y/2-A[i][1];
}
A1[3][0]=A1[0][0];
A1[3][1]=A1[0][1];
setcolor(WHITE);
drawpoly(4,*A1);
printf("\nEnter Sx Sy : ");
scanf("%d %d",&sx,&sy);
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=A[i][0]*sx;
B[i][1]=A[i][1]*sy;
}
for(i=0;i<3;i++)
{
B[i][0]=x/2+B[i][0];
B[i][1]=y/2-B[i][1];
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
break;
case 3:
printf("enter first co-ordinates: ");
scanf(" %d %d",&A[0][0],&A[0][1]);
printf ("enter second co-ordinates: ");
scanf("%d %d",&A[1][0],&A[1][1]);
printf("enter third co-ordinates: ");
scanf("%d %d",&A[2][0],&A[2][1]);
for(i=0;i<3;i++)
{
A1[i][0]=x/2+A[i][0];
A1[i][1]=y/2-A[i][1];
}
A1[3][0]=A1[0][0];
A1[3][1]=A1[0][1];
setcolor(WHITE);
drawpoly(4,*A1);
printf("1.Clockwise\n2.Counter clockwise\n");
scanf("%d",&c);
printf("Enter the rotation angle: ");
scanf("%f",&r);
r= r*3.14/180;
if (c==2)
{
for(i=0;i<3;i++)
{
B[i][0]=x/2+(A[i][0]*cos(r)-A[i][1]*sin(r));
B[i][1]=y/2-(A[i][0]*sin(r)+A[i][1]*cos(r));
}
setlinestyle(1,0,1);
setcolor(WHITE);
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
else if (c==1)
{
for(i=0;i<3;i++)
{
B[i][0]=x/2+(A[i][0]*cos(r)+A[i][1]*sin(r));
B[i][1]=y/2-(A[i][1]*cos(r)-A[i][0]*sin(r));
}
setlinestyle(1,0,1);
setcolor(WHITE);
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
break;
case 4:
printf("enter first co-ordinates: ");
scanf(" %d %d",&A[0][0],&A[0][1]);
printf ("enter second co-ordinates: ");
scanf("%d %d",&A[1][0],&A[1][1]);
printf("enter third co-ordinates: ");
scanf("%d %d",&A[2][0],&A[2][1]);
for(i=0;i<3;i++)
{
A1[i][0]=x/2+A[i][0];
A1[i][1]=y/2-A[i][1];
}
A1[3][0]=A1[0][0];
A1[3][1]=A1[0][1];
setcolor(WHITE);
drawpoly(4,*A1);
printf("Reflection along\n1.X-axis\n2.Y-axis\n3.Origin\n4.Line y=x\n5.Line y=-x \n");
scanf("%d",&rf);
if(rf==1)
{
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=A1[i][0];
B[i][1]=y/2+A[i][1];
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
else if(rf==2)
{
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=x/2-A[i][0];
B[i][1]=A1[i][1];
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
else if(rf==3)
{
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=x/2-A[i][0];
B[i][1]=y/2+A[i][1];
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
else if(rf==4)
{
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=x/2+A[i][1];
B[i][1]=y/2-A[i][0];
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
else if(rf==5)
{
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=x/2-A[i][1];
B[i][1]=y/2+A[i][0];
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
break;
case 5:
printf("enter first co-ordinates: ");
scanf(" %d %d",&A[0][0],&A[0][1]);
printf ("enter second co-ordinates: ");
scanf("%d %d",&A[1][0],&A[1][1]);
printf("enter third co-ordinates: ");
scanf("%d %d",&A[2][0],&A[2][1]);
printf("enter fourth co-ordinates: ");
scanf("%d %d",&A[3][0],&A[3][1]);
for(i=0;i<4;i++)
{
A1[i][0]=x/2+A[i][0];
A1[i][1]=y/2-A[i][1];
}
A1[4][0]=A1[0][0];
A1[4][1]=A1[0][1];
setcolor(WHITE);
drawpoly(5,*A1);
printf("1.X-shear\n2.Y-shear\n3.X-shear with Yref\n4.Y-shearwith X-ref \n");
scanf("%d",&sh);
if (sh==1)
{
printf("\nEnter shx :");
scanf("%d",&shx);
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<4;i++)
{
B[i][0]=x/2+(A[i][0]+(A[i][1]*shx));
B[i][1]=A1[i][1];
}
B[4][0]=B[0][0];
B[4][1]=B[0][1];
drawpoly(5,*B);
}
else if(sh==2)
{
printf("\nEnter shy :");
scanf("%d",­);
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<4;i++)
{
B[i][1]=y/2-(A[i][1]+(A[i][0]*shy));
B[i][0]=A1[i][0];
}
B[4][0]=B[0][0];
B[4][1]=B[0][1];
drawpoly(5,*B);
}
else if(sh==3)
{
printf("\nEnter shx and Y-ref: ");
scanf("%d %d",&shx,&yr);
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<4;i++)
{
B[i][0]=x/2+(A[i][0]+(A[i][1]*shx)-(shx*yr));
B[i][1]=A1[i][1];
}
B[4][0]=B[0][0];
B[4][1]=B[0][1];
drawpoly(5,*B);
}
else if(sh==4)
{
printf("\nEnter shy and X-ref: ");
scanf("%d %d",­,&xr);
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<4;i++)
{
B[i][1]=y/2-((A[i][0]*shy)+A[i][1]-(shy*xr));
B[i][0]=A1[i][0];
}
B[4][0]=B[0][0];
B[4][1]=B[0][1];
drawpoly(5,*B);
}
break;
default:
printf("\nEnter a valid choice ");
goto enter;
}
printf("Do u want to continue? y/n ");
scanf("%s",&ch);
if(ch=='y')
{
goto enter;
}
getch();
closegraph();
restorecrtmode();
}
#include
#include
#include
#include
#include
void main()
{
int gd=DETECT,i,j,gm,B[5][2],A[5][2],A1[5][2],x,y,tx=0,ty=0,sx=0,sy=0,a;
int rf,sh,shx,shy,yr,xr;
float r;
char ch;
ch= 'y';
enter: clrscr();
initgraph(&gd,&gm,"c:\\tc\\bgi");
x=getmaxx();
y=getmaxy();
setlinestyle(0,0,1);
setcolor(WHITE);
line (x/2,0,x/2,y);
line(0,y/2,x,y/2);
putpixel(x/2,y/2, BLACK);
outtextxy(x/2+2,y/2+2,"0");
putpixel(x/2+40,y/2, BLACK); //lits the pixel
outtextxy(x/2+40,y/2+2,"40");
putpixel(x/2+80,y/2, BLACK);
outtextxy(x/2+80,y/2+2,"80");
putpixel(x/2+120,y/2, BLACK);
outtextxy(x/2+120,y/2+2,"120");
putpixel(x/2+160,y/2, BLACK);
outtextxy(x/2+160,y/2+2,"160");
putpixel(x/2+200,y/2, BLACK);
outtextxy(x/2+200,y/2+2,"200");
putpixel(x/2+240,y/2, BLACK);
outtextxy(x/2+240,y/2+2,"240");
putpixel(x/2-40,y/2, BLACK);
outtextxy(x/2-40,y/2+2,"-40");
putpixel(x/2-80,y/2, BLACK);
outtextxy(x/2-80,y/2+2,"-80");
putpixel(x/2-120,y/2, BLACK);
outtextxy(x/2-120,y/2+2,"-120");
putpixel(x/2-160,y/2, BLACK);
outtextxy(x/2-160,y/2+2,"-160");
putpixel(x/2-200,y/2, BLACK);
outtextxy(x/2-200,y/2+2,"-200");
putpixel(x/2-240,y/2, BLACK);
outtextxy(x/2-240,y/2+2,"-240");
putpixel(x/2,y/2+40, BLACK);
outtextxy(x/2,y/2+40,"-40");
putpixel(x/2,y/2+80, BLACK);
outtextxy(x/2,y/2+80,"-80");
putpixel(x/2,y/2+120, BLACK);
outtextxy(x/2,y/2+120,"-120");
putpixel(x/2,y/2+160, BLACK);
outtextxy(x/2,y/2+160,"-160");
putpixel(x/2,y/2+200, BLACK);
outtextxy(x/2,y/2+200,"-200");
putpixel(x/2,y/2+240, BLACK);
outtextxy(x/2,y/2+240,"-240");
putpixel(x/2,y/2-40, BLACK);
outtextxy(x/2+2,y/2-40,"40");
putpixel(x/2,y/2-80, BLACK);
outtextxy(x/2+2,y/2-80,"80");
putpixel(x/2,y/2-120, BLACK);
outtextxy(x/2+2,y/2-120,"120");
putpixel(x/2,y/2-160, BLACK);
outtextxy(x/2+2,y/2-160,"160");
putpixel(x/2,y/2-200, BLACK);
outtextxy(x/2+2,y/2-200,"200");
putpixel(x/2,y/2-240,);
outtextxy(x/2+2,y/2-240,"240");
line(0,y,x,0);
line(0,0,x,y);
printf("\n1:Translation\n2:Scaling\n3:Rotation\n4:Reflection\n 5:Shearin g\nEnter your choice: ");
scanf("%d",&a);
switch(a)
{
case 1:
printf("enter first co-ordinates: ");
scanf(" %d %d",&A[0][0],&A[0][1]);
printf ("enter second co-ordinates: ");
scanf("%d %d",&A[1][0],&A[1][1]);
printf("enter third co-ordinates: ");
scanf("%d %d",&A[2][0],&A[2][1]);
for(i=0;i<3;i++)
{
A[i][0]=x/2+A[i][0];
A[i][1]=y/2-A[i][1];
}
A[3][0]=A[0][0];
A[3][1]=A[0][1];
setcolor(WHITE);
drawpoly(4,*A);
printf("\nEnter tx ty : ");
scanf("%d %d",&tx,&ty);
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=A[i][0]+tx;
B[i][1]=A[i][1]-ty;
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
break;
case 2:
printf("enter first co-ordinates: ");
scanf(" %d %d",&A[0][0],&A[0][1]);
printf ("enter second co-ordinates: ");
scanf("%d %d",&A[1][0],&A[1][1]);
printf("enter third co-ordinates: ");
scanf("%d %d",&A[2][0],&A[2][1]);
for(i=0;i<3;i++)
{
A1[i][0]=x/2+A[i][0];
A1[i][1]=y/2-A[i][1];
}
A1[3][0]=A1[0][0];
A1[3][1]=A1[0][1];
setcolor(WHITE);
drawpoly(4,*A1);
printf("\nEnter Sx Sy : ");
scanf("%d %d",&sx,&sy);
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=A[i][0]*sx;
B[i][1]=A[i][1]*sy;
}
for(i=0;i<3;i++)
{
B[i][0]=x/2+B[i][0];
B[i][1]=y/2-B[i][1];
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
break;
case 3:
printf("enter first co-ordinates: ");
scanf(" %d %d",&A[0][0],&A[0][1]);
printf ("enter second co-ordinates: ");
scanf("%d %d",&A[1][0],&A[1][1]);
printf("enter third co-ordinates: ");
scanf("%d %d",&A[2][0],&A[2][1]);
for(i=0;i<3;i++)
{
A1[i][0]=x/2+A[i][0];
A1[i][1]=y/2-A[i][1];
}
A1[3][0]=A1[0][0];
A1[3][1]=A1[0][1];
setcolor(WHITE);
drawpoly(4,*A1);
printf("1.Clockwise\n2.Counter clockwise\n");
scanf("%d",&c);
printf("Enter the rotation angle: ");
scanf("%f",&r);
r= r*3.14/180;
if (c==2)
{
for(i=0;i<3;i++)
{
B[i][0]=x/2+(A[i][0]*cos(r)-A[i][1]*sin(r));
B[i][1]=y/2-(A[i][0]*sin(r)+A[i][1]*cos(r));
}
setlinestyle(1,0,1);
setcolor(WHITE);
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
else if (c==1)
{
for(i=0;i<3;i++)
{
B[i][0]=x/2+(A[i][0]*cos(r)+A[i][1]*sin(r));
B[i][1]=y/2-(A[i][1]*cos(r)-A[i][0]*sin(r));
}
setlinestyle(1,0,1);
setcolor(WHITE);
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
break;
case 4:
printf("enter first co-ordinates: ");
scanf(" %d %d",&A[0][0],&A[0][1]);
printf ("enter second co-ordinates: ");
scanf("%d %d",&A[1][0],&A[1][1]);
printf("enter third co-ordinates: ");
scanf("%d %d",&A[2][0],&A[2][1]);
for(i=0;i<3;i++)
{
A1[i][0]=x/2+A[i][0];
A1[i][1]=y/2-A[i][1];
}
A1[3][0]=A1[0][0];
A1[3][1]=A1[0][1];
setcolor(WHITE);
drawpoly(4,*A1);
printf("Reflection along\n1.X-axis\n2.Y-axis\n3.Origin\n4.Line y=x\n5.Line y=-x \n");
scanf("%d",&rf);
if(rf==1)
{
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=A1[i][0];
B[i][1]=y/2+A[i][1];
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
else if(rf==2)
{
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=x/2-A[i][0];
B[i][1]=A1[i][1];
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
else if(rf==3)
{
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=x/2-A[i][0];
B[i][1]=y/2+A[i][1];
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
else if(rf==4)
{
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=x/2+A[i][1];
B[i][1]=y/2-A[i][0];
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
else if(rf==5)
{
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<3;i++)
{
B[i][0]=x/2-A[i][1];
B[i][1]=y/2+A[i][0];
}
B[3][0]=B[0][0];
B[3][1]=B[0][1];
drawpoly(4,*B);
}
break;
case 5:
printf("enter first co-ordinates: ");
scanf(" %d %d",&A[0][0],&A[0][1]);
printf ("enter second co-ordinates: ");
scanf("%d %d",&A[1][0],&A[1][1]);
printf("enter third co-ordinates: ");
scanf("%d %d",&A[2][0],&A[2][1]);
printf("enter fourth co-ordinates: ");
scanf("%d %d",&A[3][0],&A[3][1]);
for(i=0;i<4;i++)
{
A1[i][0]=x/2+A[i][0];
A1[i][1]=y/2-A[i][1];
}
A1[4][0]=A1[0][0];
A1[4][1]=A1[0][1];
setcolor(WHITE);
drawpoly(5,*A1);
printf("1.X-shear\n2.Y-shear\n3.X-shear with Yref\n4.Y-shearwith X-ref \n");
scanf("%d",&sh);
if (sh==1)
{
printf("\nEnter shx :");
scanf("%d",&shx);
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<4;i++)
{
B[i][0]=x/2+(A[i][0]+(A[i][1]*shx));
B[i][1]=A1[i][1];
}
B[4][0]=B[0][0];
B[4][1]=B[0][1];
drawpoly(5,*B);
}
else if(sh==2)
{
printf("\nEnter shy :");
scanf("%d",­);
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<4;i++)
{
B[i][1]=y/2-(A[i][1]+(A[i][0]*shy));
B[i][0]=A1[i][0];
}
B[4][0]=B[0][0];
B[4][1]=B[0][1];
drawpoly(5,*B);
}
else if(sh==3)
{
printf("\nEnter shx and Y-ref: ");
scanf("%d %d",&shx,&yr);
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<4;i++)
{
B[i][0]=x/2+(A[i][0]+(A[i][1]*shx)-(shx*yr));
B[i][1]=A1[i][1];
}
B[4][0]=B[0][0];
B[4][1]=B[0][1];
drawpoly(5,*B);
}
else if(sh==4)
{
printf("\nEnter shy and X-ref: ");
scanf("%d %d",­,&xr);
setlinestyle(1,0,1);
setcolor(WHITE);
for(i=0;i<4;i++)
{
B[i][1]=y/2-((A[i][0]*shy)+A[i][1]-(shy*xr));
B[i][0]=A1[i][0];
}
B[4][0]=B[0][0];
B[4][1]=B[0][1];
drawpoly(5,*B);
}
break;
default:
printf("\nEnter a valid choice ");
goto enter;
}
printf("Do u want to continue? y/n ");
scanf("%s",&ch);
if(ch=='y')
{
goto enter;
}
getch();
closegraph();
restorecrtmode();
}
Write a program to Demonstrate Bresenham’s Circle Drawing Algorithm
CODE
#include
#include
#include
#include
#include
void main()
{
int gd=DETECT, gm;
int x,y,p,r;
char ch;
initgraph (&gd,&gm,"c:\\tc\\bgi");
x=getmaxx();
y=getmaxy();
setlinestyle(0,0,1);
setcolor(WHITE);
line (x/2,0,x/2,y);
line(0,y/2,x,y/2);
putpixel(x/2,y/2, BLACK);
outtextxy(x/2+2,y/2+2,"0");
putpixel(x/2+40,y/2, BLACK); //lits the pixel
outtextxy(x/2+40,y/2+2,"40");
putpixel(x/2+80,y/2, BLACK);
outtextxy(x/2+80,y/2+2,"80");
putpixel(x/2+120,y/2, BLACK);
outtextxy(x/2+120,y/2+2,"120");
putpixel(x/2+160,y/2, BLACK);
outtextxy(x/2+160,y/2+2,"160");
putpixel(x/2+200,y/2, BLACK);
outtextxy(x/2+200,y/2+2,"200");
putpixel(x/2+240,y/2, BLACK);
outtextxy(x/2+240,y/2+2,"240");
putpixel(x/2-40,y/2, BLACK);
outtextxy(x/2-40,y/2+2,"-40");
putpixel(x/2-80,y/2, BLACK);
outtextxy(x/2-80,y/2+2,"-80");
putpixel(x/2-120,y/2, BLACK);
outtextxy(x/2-120,y/2+2,"-120");
putpixel(x/2-160,y/2, BLACK);
outtextxy(x/2-160,y/2+2,"-160");
putpixel(x/2-200,y/2, BLACK);
outtextxy(x/2-200,y/2+2,"-200");
putpixel(x/2-240,y/2, BLACK);
outtextxy(x/2-240,y/2+2,"-240");
putpixel(x/2,y/2+40, BLACK);
outtextxy(x/2,y/2+40,"-40");
putpixel(x/2,y/2+80, BLACK);
outtextxy(x/2,y/2+80,"-80");
putpixel(x/2,y/2+120, BLACK);
outtextxy(x/2,y/2+120,"-120");
putpixel(x/2,y/2+160, BLACK);
outtextxy(x/2,y/2+160,"-160");
putpixel(x/2,y/2+200, BLACK);
outtextxy(x/2,y/2+200,"-200");
putpixel(x/2,y/2+240, BLACK);
outtextxy(x/2,y/2+240,"-240");
putpixel(x/2,y/2-40, BLACK);
outtextxy(x/2+2,y/2-40,"40");
putpixel(x/2,y/2-80, BLACK);
outtextxy(x/2+2,y/2-80,"80");
putpixel(x/2,y/2-120, BLACK);
outtextxy(x/2+2,y/2-120,"120");
putpixel(x/2,y/2-160, BLACK);
outtextxy(x/2+2,y/2-160,"160");
putpixel(x/2,y/2-200, BLACK);
outtextxy(x/2+2,y/2-200,"200");
putpixel(x/2,y/2-240, BLACK);
outtextxy(x/2+2,y/2-240,"240");
printf("Enter the radius ");
scanf("%d",&r);
x=0;y=r;
plot(x,y);
p=1-r;
while (x {
if(p<0)
{
x=x+1;
p=p+2*x+1;
}
else
{
x=x+1;
y=y-1;
p=p+2*(x-y)+1;
}
plot(x,y);
}
getch();
closegraph();
}
int plot(int x,int y)
{
int xc,yc;
xc=getmaxx()/2;
yc=getmaxy()/2;
putpixel(xc+x,yc+y,WHITE);
putpixel(xc-x,yc+y,WHITE);
putpixel(xc+x,yc-y,WHITE);
putpixel(xc-x,yc-y,WHITE);
putpixel(xc+y,yc+x,WHITE);
putpixel(xc-y,yc+x,WHITE);
putpixel(xc+y,yc-x,WHITE);
putpixel(xc-y,yc-x,WHITE);
return(0);
}
#include
#include
#include
#include
#include
void main()
{
int gd=DETECT, gm;
int x,y,p,r;
char ch;
initgraph (&gd,&gm,"c:\\tc\\bgi");
x=getmaxx();
y=getmaxy();
setlinestyle(0,0,1);
setcolor(WHITE);
line (x/2,0,x/2,y);
line(0,y/2,x,y/2);
putpixel(x/2,y/2, BLACK);
outtextxy(x/2+2,y/2+2,"0");
putpixel(x/2+40,y/2, BLACK); //lits the pixel
outtextxy(x/2+40,y/2+2,"40");
putpixel(x/2+80,y/2, BLACK);
outtextxy(x/2+80,y/2+2,"80");
putpixel(x/2+120,y/2, BLACK);
outtextxy(x/2+120,y/2+2,"120");
putpixel(x/2+160,y/2, BLACK);
outtextxy(x/2+160,y/2+2,"160");
putpixel(x/2+200,y/2, BLACK);
outtextxy(x/2+200,y/2+2,"200");
putpixel(x/2+240,y/2, BLACK);
outtextxy(x/2+240,y/2+2,"240");
putpixel(x/2-40,y/2, BLACK);
outtextxy(x/2-40,y/2+2,"-40");
putpixel(x/2-80,y/2, BLACK);
outtextxy(x/2-80,y/2+2,"-80");
putpixel(x/2-120,y/2, BLACK);
outtextxy(x/2-120,y/2+2,"-120");
putpixel(x/2-160,y/2, BLACK);
outtextxy(x/2-160,y/2+2,"-160");
putpixel(x/2-200,y/2, BLACK);
outtextxy(x/2-200,y/2+2,"-200");
putpixel(x/2-240,y/2, BLACK);
outtextxy(x/2-240,y/2+2,"-240");
putpixel(x/2,y/2+40, BLACK);
outtextxy(x/2,y/2+40,"-40");
putpixel(x/2,y/2+80, BLACK);
outtextxy(x/2,y/2+80,"-80");
putpixel(x/2,y/2+120, BLACK);
outtextxy(x/2,y/2+120,"-120");
putpixel(x/2,y/2+160, BLACK);
outtextxy(x/2,y/2+160,"-160");
putpixel(x/2,y/2+200, BLACK);
outtextxy(x/2,y/2+200,"-200");
putpixel(x/2,y/2+240, BLACK);
outtextxy(x/2,y/2+240,"-240");
putpixel(x/2,y/2-40, BLACK);
outtextxy(x/2+2,y/2-40,"40");
putpixel(x/2,y/2-80, BLACK);
outtextxy(x/2+2,y/2-80,"80");
putpixel(x/2,y/2-120, BLACK);
outtextxy(x/2+2,y/2-120,"120");
putpixel(x/2,y/2-160, BLACK);
outtextxy(x/2+2,y/2-160,"160");
putpixel(x/2,y/2-200, BLACK);
outtextxy(x/2+2,y/2-200,"200");
putpixel(x/2,y/2-240, BLACK);
outtextxy(x/2+2,y/2-240,"240");
printf("Enter the radius ");
scanf("%d",&r);
x=0;y=r;
plot(x,y);
p=1-r;
while (x
if(p<0)
{
x=x+1;
p=p+2*x+1;
}
else
{
x=x+1;
y=y-1;
p=p+2*(x-y)+1;
}
plot(x,y);
}
getch();
closegraph();
}
int plot(int x,int y)
{
int xc,yc;
xc=getmaxx()/2;
yc=getmaxy()/2;
putpixel(xc+x,yc+y,WHITE);
putpixel(xc-x,yc+y,WHITE);
putpixel(xc+x,yc-y,WHITE);
putpixel(xc-x,yc-y,WHITE);
putpixel(xc+y,yc+x,WHITE);
putpixel(xc-y,yc+x,WHITE);
putpixel(xc+y,yc-x,WHITE);
putpixel(xc-y,yc-x,WHITE);
return(0);
}
Write a program in c to Demonstrate Bresenham’s Line Drawing Algorithm
SOURCE CODE
#include
#include
#include
#include
main()
{
float x,y,x1,y1,x2,y2,dx,dy,e;
int i,gd,gm;
printf("enter the values of x1=\t");
scanf("%f",&x1);
printf("enter the values of x2=\t");
scanf("%f",&x2);
printf("enter the values of y1=\t");
scanf("%f",&y1);
printf("enter the values of y2=\t");
scanf("%f",&y2);
detectgraph(&gd,&gm);
initgraph(&gd,&gm," ");
setbkcolor(15);
dx=abs(x2-x1);
dy=abs(y2-y1);
x=x1;
y=y1;
e=2*dy-dx;
i=1;
do
{
putpixel(x,y,13);
while(e>=0)
{
y=y+1;
e=e-2*dx;
}
x=x+1;
e=e+2*dy;
i=i+1;
delay(25);
}
while(i<=dx);
getch();
closegraph();
return(0);
}
#include
#include
#include
#include
main()
{
float x,y,x1,y1,x2,y2,dx,dy,e;
int i,gd,gm;
printf("enter the values of x1=\t");
scanf("%f",&x1);
printf("enter the values of x2=\t");
scanf("%f",&x2);
printf("enter the values of y1=\t");
scanf("%f",&y1);
printf("enter the values of y2=\t");
scanf("%f",&y2);
detectgraph(&gd,&gm);
initgraph(&gd,&gm," ");
setbkcolor(15);
dx=abs(x2-x1);
dy=abs(y2-y1);
x=x1;
y=y1;
e=2*dy-dx;
i=1;
do
{
putpixel(x,y,13);
while(e>=0)
{
y=y+1;
e=e-2*dx;
}
x=x+1;
e=e+2*dy;
i=i+1;
delay(25);
}
while(i<=dx);
getch();
closegraph();
return(0);
}
Chi-Square Test
Write a c/c++ program to find Goodness of Fit Test for a given random number by
1. Chi-Square test for Poisson
2. Chi-Square test for Exponential
SOURCE CODE
#include
#include
#include
#include
void poisson();
void exponential();
void main()
{
int op, flag=1;
clrscr();
while(flag==1)
{
printf("\n1.poisson");
printf("\n2.exponential");
printf("\n3.Exit");
printf("\n Enter the above option");
scanf("%d",&op);
if (op>3)
{
printf("give the correct option");
getch();
exit(0);
}
switch(op)
{
case 1: poisson();
break;
case 2: exponential();
break;
case 3:exit(0);
}
}
getch();
}
void poisson()
{
double OEE[12],x,a,p[12],E[12],OE,OE2;
int i,j,k=12,f,O[12],sum=0;
double facti,s;
printf("\t*** Chi-square Test Applied to Poisson Assumption ***\n\n");
printf("Enter 12 Observed Frequency Values:\n");
for(i=0;i<12;i++)
{
scanf("%d",&O[i]);
}
for(i=0;i<12;i++)
{
sum=sum+(i*O[i]);
}
a=(float)sum/100;
p[0]=(float)(exp(-a));
E[0]=100.0*p[0];
for(i=1;i<12;i++)
{
facti=1.0;
for(s=1.0;s<=i;s++)
{
facti=facti*s;
}
p[i]=(exp(-a)*pow(a,i))/facti;
E[i]=100.0*p[i];
}
for(i=0;i
if(E[i]<5)
{
E[i]=E[i]+E[i+1];
O[i]=O[i]+O[i+1];
for(j=i+1;j+1
E[j]=E[j+1];
O[j]=O[j+1];
}
if(i!=8)
{
for(s=k-1;s<12;s++)
{
E[s]=0.0;O[s]=0;
}
}
k=k-1;
}
}
k=k+1;
for(i=k-1;i>=0;i--)
{
if(E[i]<5)
{
E[i-1]=E[i]+E[i-1];
O[i-1]=O[i]+O[i-1];
for(s=i;s<12;s++)
{
E[s]=0.0;O[s]=0;
}
k=k-1;
}
}
for(i=0;i<7;i++)
{
OE=(float)O[i]-E[i];
OE2=OE*OE;
OEE[i]=OE2/E[i];
x=x+OEE[i];
}
printf("-----------------------------------------------------\n");
printf("xi\tObserved\tExpected\t(Oi-Ei)^2/Ei\n\tfrequency,Oi\tfrequency,Ei\n");
printf("-----------------------------------------------------\n");
for(i=0;i<7;i++)
{
printf("%d\t%5d\t\t%2.1f\t\t%2.2f\n",i,O[i],E[i],OEE[i]);
}
printf("-----------------------------------------------------\n");
printf("\t\t\t\t\tx:%0.2f\n",x);
printf("-----------------------------------------------------\n");
printf("\nSince x0=%0.2f and x0.05=11.1\nNull hypothesis is rejected.",x);
}
void exponential()
{
float p=0.125,l=0.084,a[10],E,OEE[10],OE,OE2,x;
int i,O[10];
printf("*** Chi-square test for exponential distribution ***\n");
printf("\nEnter 8 observed freq values:\n");
for(i=0;i<7;i++)
{
scanf("%d\n",&O[i]);
}
E=p*50.0;
a[0]=0;
for(i=1;i<7;i++)
{
a[i]=-(1/l)*log(1-(i*p));
}
for(i=0;i<7;i++)
{
OE=(float)O[i]-E;
OE2=OE*OE;
OEE[i]=OE2/E;
x=x+OEE[i];
}
printf("\n----------------------------------------------------------\n");
printf("Class Interval\tObserved\tExpected\t(Oi-Ei)^2/Ei\n\t\tfrequency,Oi\tfrequency,Ei\n");
printf("------------------------------------------------------------\n");
for(i=0;i<7;i++)
{
printf("[%0.3f,%0.3f)\t%5d\t\t%5.2f\t\t%5.2f\n",a[i],a[i+1],O[i],E,OEE[i] );
}
printf("[%0.3f,--)\t%5d\t\t%5.2f\t\t%5.2f\n",a[7],O[7],E,OEE[7]);
printf("------------------------------------------------------------\n");
printf("\t\t\t\t\t\tx=%4.1f\n",x);
printf("------------------------------------------------------------\n");
printf("Since x0=%0.1f and x0.05=12.6\nNull hypothesis is rejected.",x);
}
Random Number test
Write a C/C++ / Excel Program to test the random number using
1. Frequency Test
A. Chi-square test: Accept N random numbers, level of significance a, number of intervals n, set of observed values and set of estimated values.
B. Kolmogrov –Smirnov Test. Accept n random numbers, number of observations n, the set of observations Ri, where 1<=i<=n.
2. Run Test : Accept n random numbers and level of significance a to reject or accept the given set of random numbers
A. Runs Up and Runs Down Test: Accept the total number of runs a, to find the mean and variance of a
B. Runs Below and Runs Above mean test: Accept the number of individual observation above and below the mean as n1 and n2, the total number of runs as B to fine the mean and variance for B
3. Auto Corelation Test: Accept n random numbers, level of significance a, the lag m, the starting number i, M such that i+(M+1)m<=n.
4. Gap Test: Accept n random numbers, levels of significance a, find the number of gaps for all digits occurring in the random number sequence.
SOURCE CODE
#include
#include
#include
#include
double min, max;
int minm(int n,int a[20]);
int upp[20],low[20],noofclass,freq[20];
int findr(int min,int max);
int findfreq(int noofclass, int n, int b[20], int upp[20],int low[20]);
void chisquare();
void Kols();
void clc();
void gap();
struct list
{
int count,t,t1;
float Mi,Ma,t2;
}
I[10];
void main()
{
int op, flag=1;
clrscr();
while(flag==1)
{
printf("\n1.Chisquare Test");
printf("\n2.Kolmogrov-smirnov test");
printf("\n3.combined linear congruential");
printf("\n4.Gap test");
printf("\n5.Exit");
printf("\n Enter the above option");
scanf("%d",&op);
if (op>7)
{
printf("give the correct option");
getch();
exit(0);
}
switch(op)
{
case 1: chisquare ();
break;
case 2: Kols();
break;
case 3: clc();
break;
case 4: gap();
break;
case 5:exit(0);
}
}
getch();
}
void chisquare()
{
int i,N,n,j;
float r[50],dif,ci,mi,ma,E,T=0,zo=0,zalp;
randomize();
printf("enter how many random numbers from 0 to 99\n\n");
scanf("%d",&N);
if(N<0)
{
printf("given value of N<0");
getch();
exit(0);
}
for(i=0;i r[i]=rand()%100/(float)100;
printf("%f",r[i]);
}
mi=r[0];
ma=r[0];
for(i=0;i {
if(mi>r[i])
ma=r[i];
}
printf("\nenter the num of interval");
scanf("%d",&n);
printf("\n enter the value of z(alpha,n-1)");
scanf("%f",&zalp);
E=N/n;
if(E<5)
{
printf("give another num of interval");
getch();
exit(0);
}
dif=ma-mi;
ci=dif/n;
I[0].Mi=mi;
I[0].Ma=mi+ci;
for(i=0;i I[i+1].Mi=I[j].Ma;
I[i+1].Ma=I[i+1].Mi+ci;
}
I[i].Ma=I[i].Ma+0.1;
for(j=0;j for(i=0;i {
if ((I[i].Mi<=r[j])&&(r[j]{
I[i].count=I[i].count+1;
}
}
for(i=0;i {
I[i].t=I[i].count-E;
I[i].t1=I[i].t*I[i].t;
I[i].t2=I[i].t/(float)E;
T=T+I[i].t1;
zo=zo+I[i].t2;
}
printf("\n\ninterval");
printf("\tobservation");
printf("\tequally");
printf("\t\tO-E");
printf("o-e2/e");
for(i=0;i {
printf("\n%f%f",I[i].Mi,I[i].Ma);
printf("\t%d",I[i].count);
printf("t%f",E);
printf("\t%d",I[i].t);
printf("\t%d",I[i].t1);
printf("\t%f",I[i].t2);
}
printf("\n\nzo %f",zo);
if(zo {
printf("\n\n Null hypothesis of uniform distribution is not rejected");
}
else
{
printf("\n\n Null hypothesis of uniform distribution is rejected");
}
}
void Kols()
{
int i,j,n;
float r[25],temp,d1[25],d2[25],dp,dm,d;
printf("enter n random nubers from 0 to 99\n\n");
scanf("%d",&n);
if(n<0)
{
printf("given value of n<0");
getch();
exit(0);
}
randomize();
for(i=1;i<=n;i++)
{
r[i]=rand()%100/100.0;
printf("%f",r[i]);
}
/* for(i=1;i<=n;i++)
{
printf("%f",r[i]);
} */
for(i=1;i<=n-1;i++)
{
for(j=i+1;j<=n;j++)
{
if(r[i]>r[j])
{
temp=r[i];
r[i]=r[j];
r[j]=temp;
}
}
}
printf("\n\n the ascending order of random number\n\n");
for(i=1;i<=n;i++)
{
printf("%f",r[i]);
}
for(i=1;i<=n;i++)
{
d1[i]=(i/n)-r[i];
d2[i]=r[i]-((i-1)/n);
if(d1[i]<0)
{
d1[i]=0.0;
}
if(d2[i]<0)
{
d2[i]=0.0;
}
}
printf("\n\n");
for(i=1;i<=n;i++)
{
printf("%f",d1[i]);
}
for(i=1;i<=n;i++)
{
printf("%f",d2[i]);
}
dp=d1[1];
dm=d2[1];
for(i=1;i<=n;i++)
{
if(dp {
dp=d1[i];
}
if(dm {
dm=d2[i];
}
}
printf("\n\n The value of dplus is %f and dminus is %f",dp,dm);
if(dp>dm)
{
d=dp;
}
else
d=dm;
printf("\n the max of dp and dm is %f",d);
}
void clc()
{
int i,no_of_g,n,j,a[10];
double R[10],X[10],x[10][10],temp=0,m[10];
clrscr();
printf("\n enter the no of generator:");
scanf("%d",&no_of_g);
printf("\nenter the nos random num to be generated");
scanf("%d",&n);
if(n<0 && no_of_g<0)
{
printf("\neither n<0 or no_of_g<0");
getch();
exit(0);
}
for(i=0;i {
printf("enter the value of a,m,x[i][0]");
scanf("%d%lf%lf",&a[i],&m[i],&x[i][0]);
for(j=0;j {
x[i][j+1]=fmod(a[i]*x[i][j],m[i]);
}
}
printf("\nindividual values\n");
for(i=0;i {
for(j=0;j {
printf("%lf\t",x[j][i]);
}
printf("\n");
}
for(i=0;i {
for(j=1;j temp=temp+pow((-1),j-1)*x[j][i];
X[i]=fmod(temp,(m[0]-1));
printf("\nthe X[%d] is %lf",i,X[i]);
if(X[i]>0)
{
R[i]=(float)X[i]/(float)m[0];
}
else
if(X[i]==0)
{
R[i]=((float)m[0]-1.0)/(float)m[0];
}
printf("\nthe R[%d] is %lf",i,R[i]);
}
}
void gap()
{
int n,i,j,flag=0,ctr=0,gap[20],m=0;
double FX[20],N1[20];
float Relfreq[20],cumul[20],Dalpha;
int a[110];
clrscr();
printf("enter how many random numbers you want to generate\n\n");
scanf("%d",&n);
printf("\n Enter Dalpha:");
scanf("%f",&Dalpha);
randomize();
printf("\n");
for(i=0;i {
a[i]=random(10);
printf("%d\t",a[i]);
}
printf("\n");
for(i=0;i<10;i++)
{
flag=1;
ctr=0;
for(j=0;j {
if(a[j]==i)
{
if(flag==1)
{
flag=2;
}
else
{
gap[m]=ctr;
m++;
ctr=0;
}
}
else
{
if(flag==2)
{
ctr=ctr+1;
}
}
}
}
printf("NO OF GAPS\n\n");
for(i=0;i {
printf("%d\t",gap[i]);
}
minm(m,gap);
findr(min,max);
printf("\n\n");
findfreq(noofclass,m,gap,upp,low);
printf("\n\nGAPLEN\tFREQUENCY\tRELATIVEFREQ\tCUMULATIVEFREQ\tF(X)\t|F(X)-Sn(X)|\n");
for(i=0;i {
Relfreq[i]=((float)freq[i]/100.0);
if(i==0)
{
cumul[i]=Relfreq[i];
}
else
{
cumul[i]=cumul[i-1]+Relfreq[i];
}
FX[i]=1-pow(0.9,(double)(upp[i]+1));
N1[i]=fabs(FX[i]-cumul[i]);
printf("%d%d\t\t%d\t\t%.2f\t\t%.2f\t%.2f\t%.2f\n",low[i],upp[i],Relfreq[i],cumul[i],FX[i],N1[i]);
}
printf("\n\n");
noofclass=i;
max=N1[0];
for(i=0;i {
if(N1[i]>max)
{
max=N1[1];
}
}
if(max {
printf("\n %.2f%d NULL HYPOTHESIS IS NOT REJECTED",max,noofclass);
}
else
{
printf("\n%.2f%d NULL HYPOTHESIS IS REJECTED",max,i);
}
}
int minm(int n,int a[15])
{
int i,j,temp=0;
min=0;
max=0;
for(i=0;i {
for(j=i+1;j {
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
min=a[0];
max=a[n-1];
return min,max;
}
int findr(int min,int max)
{
int a,i;
if(max<=10)
{
a=1;
}
if(max>10&&max<20)
{
a=2;
}
if(max>20&&max<30)
{
a=3;
}
if(a>30)
{
a=5;
}
low[0]=0;
upp[0]=a;
noofclass=1;
for(i=1;i {
low[i]=upp[i-1]+1;
upp[i]=low[i]+a;
noofclass++;
if(upp[i]>=max)
{
break;
}
}
min=min;
return low[20],upp[20];
}
int findfreq(int noofclass,int n,int b[15],int upp[20],int low[20])
{
int i,j,ctr=0;
for(j=0;j {
// ctr=0;
for(i=0;i {
if(b[i]<=upp[j]&&b[i]>=low[j])
{
ctr=ctr+1;
}
}
freq[j]=ctr;
}
return freq[20];
}
1. Frequency Test
A. Chi-square test: Accept N random numbers, level of significance a, number of intervals n, set of observed values and set of estimated values.
B. Kolmogrov –Smirnov Test. Accept n random numbers, number of observations n, the set of observations Ri, where 1<=i<=n.
2. Run Test : Accept n random numbers and level of significance a to reject or accept the given set of random numbers
A. Runs Up and Runs Down Test: Accept the total number of runs a, to find the mean and variance of a
B. Runs Below and Runs Above mean test: Accept the number of individual observation above and below the mean as n1 and n2, the total number of runs as B to fine the mean and variance for B
3. Auto Corelation Test: Accept n random numbers, level of significance a, the lag m, the starting number i, M such that i+(M+1)m<=n.
4. Gap Test: Accept n random numbers, levels of significance a, find the number of gaps for all digits occurring in the random number sequence.
SOURCE CODE
#include
#include
#include
#include
double min, max;
int minm(int n,int a[20]);
int upp[20],low[20],noofclass,freq[20];
int findr(int min,int max);
int findfreq(int noofclass, int n, int b[20], int upp[20],int low[20]);
void chisquare();
void Kols();
void clc();
void gap();
struct list
{
int count,t,t1;
float Mi,Ma,t2;
}
I[10];
void main()
{
int op, flag=1;
clrscr();
while(flag==1)
{
printf("\n1.Chisquare Test");
printf("\n2.Kolmogrov-smirnov test");
printf("\n3.combined linear congruential");
printf("\n4.Gap test");
printf("\n5.Exit");
printf("\n Enter the above option");
scanf("%d",&op);
if (op>7)
{
printf("give the correct option");
getch();
exit(0);
}
switch(op)
{
case 1: chisquare ();
break;
case 2: Kols();
break;
case 3: clc();
break;
case 4: gap();
break;
case 5:exit(0);
}
}
getch();
}
void chisquare()
{
int i,N,n,j;
float r[50],dif,ci,mi,ma,E,T=0,zo=0,zalp;
randomize();
printf("enter how many random numbers from 0 to 99\n\n");
scanf("%d",&N);
if(N<0)
{
printf("given value of N<0");
getch();
exit(0);
}
for(i=0;i
printf("%f",r[i]);
}
mi=r[0];
ma=r[0];
for(i=0;i
if(mi>r[i])
ma=r[i];
}
printf("\nenter the num of interval");
scanf("%d",&n);
printf("\n enter the value of z(alpha,n-1)");
scanf("%f",&zalp);
E=N/n;
if(E<5)
{
printf("give another num of interval");
getch();
exit(0);
}
dif=ma-mi;
ci=dif/n;
I[0].Mi=mi;
I[0].Ma=mi+ci;
for(i=0;i
I[i+1].Ma=I[i+1].Mi+ci;
}
I[i].Ma=I[i].Ma+0.1;
for(j=0;j
if ((I[i].Mi<=r[j])&&(r[j]{
I[i].count=I[i].count+1;
}
}
for(i=0;i
I[i].t=I[i].count-E;
I[i].t1=I[i].t*I[i].t;
I[i].t2=I[i].t/(float)E;
T=T+I[i].t1;
zo=zo+I[i].t2;
}
printf("\n\ninterval");
printf("\tobservation");
printf("\tequally");
printf("\t\tO-E");
printf("o-e2/e");
for(i=0;i
printf("\n%f%f",I[i].Mi,I[i].Ma);
printf("\t%d",I[i].count);
printf("t%f",E);
printf("\t%d",I[i].t);
printf("\t%d",I[i].t1);
printf("\t%f",I[i].t2);
}
printf("\n\nzo %f",zo);
if(zo
printf("\n\n Null hypothesis of uniform distribution is not rejected");
}
else
{
printf("\n\n Null hypothesis of uniform distribution is rejected");
}
}
void Kols()
{
int i,j,n;
float r[25],temp,d1[25],d2[25],dp,dm,d;
printf("enter n random nubers from 0 to 99\n\n");
scanf("%d",&n);
if(n<0)
{
printf("given value of n<0");
getch();
exit(0);
}
randomize();
for(i=1;i<=n;i++)
{
r[i]=rand()%100/100.0;
printf("%f",r[i]);
}
/* for(i=1;i<=n;i++)
{
printf("%f",r[i]);
} */
for(i=1;i<=n-1;i++)
{
for(j=i+1;j<=n;j++)
{
if(r[i]>r[j])
{
temp=r[i];
r[i]=r[j];
r[j]=temp;
}
}
}
printf("\n\n the ascending order of random number\n\n");
for(i=1;i<=n;i++)
{
printf("%f",r[i]);
}
for(i=1;i<=n;i++)
{
d1[i]=(i/n)-r[i];
d2[i]=r[i]-((i-1)/n);
if(d1[i]<0)
{
d1[i]=0.0;
}
if(d2[i]<0)
{
d2[i]=0.0;
}
}
printf("\n\n");
for(i=1;i<=n;i++)
{
printf("%f",d1[i]);
}
for(i=1;i<=n;i++)
{
printf("%f",d2[i]);
}
dp=d1[1];
dm=d2[1];
for(i=1;i<=n;i++)
{
if(dp
dp=d1[i];
}
if(dm
dm=d2[i];
}
}
printf("\n\n The value of dplus is %f and dminus is %f",dp,dm);
if(dp>dm)
{
d=dp;
}
else
d=dm;
printf("\n the max of dp and dm is %f",d);
}
void clc()
{
int i,no_of_g,n,j,a[10];
double R[10],X[10],x[10][10],temp=0,m[10];
clrscr();
printf("\n enter the no of generator:");
scanf("%d",&no_of_g);
printf("\nenter the nos random num to be generated");
scanf("%d",&n);
if(n<0 && no_of_g<0)
{
printf("\neither n<0 or no_of_g<0");
getch();
exit(0);
}
for(i=0;i
printf("enter the value of a,m,x[i][0]");
scanf("%d%lf%lf",&a[i],&m[i],&x[i][0]);
for(j=0;j
x[i][j+1]=fmod(a[i]*x[i][j],m[i]);
}
}
printf("\nindividual values\n");
for(i=0;i
for(j=0;j
printf("%lf\t",x[j][i]);
}
printf("\n");
}
for(i=0;i
for(j=1;j
X[i]=fmod(temp,(m[0]-1));
printf("\nthe X[%d] is %lf",i,X[i]);
if(X[i]>0)
{
R[i]=(float)X[i]/(float)m[0];
}
else
if(X[i]==0)
{
R[i]=((float)m[0]-1.0)/(float)m[0];
}
printf("\nthe R[%d] is %lf",i,R[i]);
}
}
void gap()
{
int n,i,j,flag=0,ctr=0,gap[20],m=0;
double FX[20],N1[20];
float Relfreq[20],cumul[20],Dalpha;
int a[110];
clrscr();
printf("enter how many random numbers you want to generate\n\n");
scanf("%d",&n);
printf("\n Enter Dalpha:");
scanf("%f",&Dalpha);
randomize();
printf("\n");
for(i=0;i
a[i]=random(10);
printf("%d\t",a[i]);
}
printf("\n");
for(i=0;i<10;i++)
{
flag=1;
ctr=0;
for(j=0;j
if(a[j]==i)
{
if(flag==1)
{
flag=2;
}
else
{
gap[m]=ctr;
m++;
ctr=0;
}
}
else
{
if(flag==2)
{
ctr=ctr+1;
}
}
}
}
printf("NO OF GAPS\n\n");
for(i=0;i
printf("%d\t",gap[i]);
}
minm(m,gap);
findr(min,max);
printf("\n\n");
findfreq(noofclass,m,gap,upp,low);
printf("\n\nGAPLEN\tFREQUENCY\tRELATIVEFREQ\tCUMULATIVEFREQ\tF(X)\t|F(X)-Sn(X)|\n");
for(i=0;i
Relfreq[i]=((float)freq[i]/100.0);
if(i==0)
{
cumul[i]=Relfreq[i];
}
else
{
cumul[i]=cumul[i-1]+Relfreq[i];
}
FX[i]=1-pow(0.9,(double)(upp[i]+1));
N1[i]=fabs(FX[i]-cumul[i]);
printf("%d%d\t\t%d\t\t%.2f\t\t%.2f\t%.2f\t%.2f\n",low[i],upp[i],Relfreq[i],cumul[i],FX[i],N1[i]);
}
printf("\n\n");
noofclass=i;
max=N1[0];
for(i=0;i
if(N1[i]>max)
{
max=N1[1];
}
}
if(max
printf("\n %.2f%d NULL HYPOTHESIS IS NOT REJECTED",max,noofclass);
}
else
{
printf("\n%.2f%d NULL HYPOTHESIS IS REJECTED",max,i);
}
}
int minm(int n,int a[15])
{
int i,j,temp=0;
min=0;
max=0;
for(i=0;i
for(j=i+1;j
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
min=a[0];
max=a[n-1];
return min,max;
}
int findr(int min,int max)
{
int a,i;
if(max<=10)
{
a=1;
}
if(max>10&&max<20)
{
a=2;
}
if(max>20&&max<30)
{
a=3;
}
if(a>30)
{
a=5;
}
low[0]=0;
upp[0]=a;
noofclass=1;
for(i=1;i
low[i]=upp[i-1]+1;
upp[i]=low[i]+a;
noofclass++;
if(upp[i]>=max)
{
break;
}
}
min=min;
return low[20],upp[20];
}
int findfreq(int noofclass,int n,int b[15],int upp[20],int low[20])
{
int i,j,ctr=0;
for(j=0;j
// ctr=0;
for(i=0;i
if(b[i]<=upp[j]&&b[i]>=low[j])
{
ctr=ctr+1;
}
}
freq[j]=ctr;
}
return freq[20];
}
Continuous Distribution
1. Write a C/C++ / Excel Program to find the Probability Density Function (pdf) and Cumulative disturibution function (cdf) for the Uniform Distribution. Accept the prameters, a and b from the user for the random variable X which is distributed uniformly between a and b.
2. Write a C/C++ / Excel Program to find the Probability Density Function
(pdf) and Cumulative disturibution function (cdf) for the Exponential Distribution. Accept the prameters of distribution λ>0
3. Write a C/C++ / Excel Program to find the Probability Density Function
(pdf) and Cumulative disturibution function (cdf) for the Gamma Distribution. Accept the prameters of distribution β and θ from the user.
4. Write a C/C++ / Excel Program to find the Probability Density Function
(pdf) and Cumulative disturibution function (cdf) for the Erlang Distribution. Accept the order k of the distribution and the parameters k2 from the user.
5. Write a C/C++ / Excel Program to find the Probability Density Function (pdf) and Cumulative disturibution function (cdf) for the Weibull Distribution. Accept for a random variable x with location parameter (υ), scale parameter (α) > 0 and the shape parameter (β)> 0 from the user.
6. Write a C/C++ / Excel Program to find the Probability Density Function (pdf) and Cumulative disturibution function (cdf) for the Triangular Distribution. Accept parameters a,b,c where a<=b<=c from the user.
SOURCE CODE
#include
#include
#include
#include
const int X[40];
void uniform();
void exponential();
void gamma();
void erlang();
void weibull();
void triangular();
void main()
{
int ch,j,flag=1,op;
clrscr();
while(flag==1)
{
printf("\n1:Uniform Distribution");
printf("\n2:Exponential Distribution");
printf("\n3:Gamma Distribution");
printf("\n4:Erlang Distribution");
printf("\n5:Weibull Distribution");
printf("\n6:Triangular Distribution");
printf("\n7:Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
uniform();
break;
case 2:
exponential();
break;
case 3:
gamma();
break;
case 4:
erlang();
break;
case 5:
weibull();
break;
case 6:
triangular();
break;
case 7:
exit(0);
break;
default:
flag=0;
exit(0);
}
getch();
}
}
void uniform()
{
float a,b,pdf,cdf,Ex,Vx,x;
int n;
clrscr();
printf("**********UNIFORM DISTRIBUTION************");
printf("\nenter value for a and b : ");
scanf("%f%f",&a,&b);
printf("\nenter value for x = ");
scanf("%f",&x);
printf("\nEnter your choice\n1*PDF\n2*CDF\n");
scanf("%d",&n);
switch(n)
{
case 1:
if (a<= x <=b)
pdf=1/(b-a);
else
pdf=0;
printf("pdf=%f",pdf);
break;
case 2:
if(x cdf=0;
else if(a<= x cdf=(x-a)/(b-a);
else if(x>=b)
cdf=1;
printf("cdf=%f",cdf);
break;
default:
printf("enter proper value");
}
Ex=(a+b)/2;
printf("E(x)=%f",Ex);
Vx=pow(b-a,2)/12;
printf("V(x)=%f",Vx);
getch();
}
/*------------------------------------------------------------------*/
void exponential()
{
float L,E,e,V,x,cdf,pdf;
int t,n;
clrscr();
printf("*************EXPONENTIAL DISTRIBUTION*******************");
printf("\nenter value for t=");
scanf("%d",&t);
printf("\nenter value for lambda & x = ");
scanf("%f%f",&L,&x);
printf("\nenter your choice");
scanf("%d",&n);
switch(n)
{
case 1:
if(x<=t)
pdf=L*exp(-L*x);
else
pdf=0;
printf("pdf=%f",pdf);
break;
case 2:
if (x>0 && x cdf=1-exp(-L*x);
else
cdf=0;
printf("cdf=%f",cdf);
break;
default:
exit(1);
}
E=1/L;
printf("E(x)=%f",E);
V=1/L*L;
printf("V(x)=%f",V);
getch();
}
/*--------------------------------------------------------------------*/
void gamma()
{
double calpdf(double, double, double, double);
double fact(double);
double x,B,T,th,pdf,b,factorial;
int i;
//B: Beta; T: Tau, th: thita,factorial : variable to calculate factorial
clrscr();
x=0;B=0;th=0;
printf("***************GAMMA DISTRIBUTION****************");
printf("\nEnter the values of x, B (beta), Thita\t");
scanf("%lf%lf%lf",&x,&B,&th);
if(B>=0 && B<=1)
{
if(th>=0 && th<=1)
{
if(B==1)
{
b=1;
}
else
{
b=B-1;
}
factorial=fact(b);
pdf=calpdf(B,th,factorial,x);
printf("Factorial= \t%lf\nPdf=\t%lf",factorial,pdf);
}
else
{
printf("\nthe value of thita should be between 0 and 1");
}
}
else
{
printf("\nthe value of beta should be between 0 and 1");
}
getch();
}
double calpdf(double Beta, double thita, double taub, double x)
{
double pdf=((Beta*thita)/taub)*(pow((Beta*thita*x),(Beta-1))*(exp(-Beta*thita*x)));
return(pdf);
}
double fact(double b)
{
int i;
double fact1=1;
for( i=1;i<=b;i++)
{
fact1=fact1*i;
}
return fact1;
}
/*--------------------------------------------------------------------------*/
void erlang()
{
double k,x,th,b,cdf,sum;
int i,j,facti,a;
clrscr();
printf("***************************************");
printf("\n \t Erling Distribution");
printf("\n***************************************");
printf("\n enter value for k x th = ");
scanf("%lf %lf %lf",&k,&x,&th);
if(x>=0)
{
facti=1;
sum=0;
for(i=0;i {
for(j=i;j>=1;j--)
{
facti=j*facti;
}
b=(exp(-(k*th*x))*pow((k*th*x),i))/facti;
sum=b+sum;
}
printf("\nsum=%lf",sum);
cdf=1-sum;
}
else
cdf=0;
printf("\ncdf=%lf",cdf);
getch();
}
/*------------------------------------------------------------------------*/
void weibull()
{
double Tau(double);
double pdf, cdf, B,a,v,x,temp,T,E,V,F;
int n=0;
clrscr();
printf("*************Weibul Distribution****************\n\n\n");
printf("Enter the values for a(alpha), B(beta), v, x");
scanf("%lf%lf%lf%lf",&a,&B,&v,&x);
printf("\nEnter Choice \n1* PDF\t2*CDF\n");
scanf("%d",&n);
switch(n)
{
case 1:
temp=0;
temp=exp(-(pow(((x-v)/a),B)));
F=(B/a)*(pow((x-v/a),(B-1)))*temp;
printf("pdf=%lf",F);
break;
case 2:
temp=0;
temp=pow((x-v)/a,B);
if(x>v)
{
F=1-(exp(-temp));
}
printf("cdf=%lf",F);
E=v+(a*Tau((1/B)+1));
V=(pow(a,2))*((Tau((2/B)+1))-Tau(pow(((1/B)+1),2)));
printf("\nE=%lf \n v=%lf",E,V);
break;
default:
printf("Enter a proper input\n");
}
getch();
}
double Tau(double t)
{
double fact1=1;
int i;
for(i=1;i {
fact1=fact1*i;
}
return fact1;
}
/*--------------------------------------------------------------------------*/
void triangular()
{
double fcdf(double,double,double,double);
double fpdf(double,double,double,double);
int n;
double a,b,c,x,pdf,cdf,E,V;
clrscr();
printf("Enter the values of a,b,c,d\n");
scanf("%lf%lf%lf%lf",&a,&b,&c,&x);
printf("Enter your choice\n1*PDF\n2*CDF\n");
scanf("%d",&n);
switch(n)
{
case 1:
pdf=fpdf(a,b,c,x);
printf("PDF=%lf",pdf);
break;
case 2:
cdf=fcdf(a,b,c,x);
printf("CDF=%lf",cdf);
break;
default:
printf("Please select appropriate input");
break;
}
E=(a+b+c)/3;
V=(3*E)-(a+c);
printf("\nMean =%lf",E);
printf("\nVariance =%lf",V);
getch();
}
double fcdf(double a,double b,double c,double x)
{
double cdf=0;
if(a {
cdf=pow((x-a),2)/((b-a)*(c-a));
}
else if(b {
cdf=1-(pow((c-x),2)/((c-b)*(c-a)));
}
else if(x<=a)
cdf=0;
else
cdf=1;
return cdf;
}
double fpdf(double a,double b,double c,double x)
{
double pdf=0;
if(a<=x && x<=b)
{
pdf=2*(x-a)/((b-a)*(c-a));
}
else if(b {
pdf=2*(c-x)/((c-b)*(c-a));
}
else pdf=0;
return pdf;
}
2. Write a C/C++ / Excel Program to find the Probability Density Function
(pdf) and Cumulative disturibution function (cdf) for the Exponential Distribution. Accept the prameters of distribution λ>0
3. Write a C/C++ / Excel Program to find the Probability Density Function
(pdf) and Cumulative disturibution function (cdf) for the Gamma Distribution. Accept the prameters of distribution β and θ from the user.
4. Write a C/C++ / Excel Program to find the Probability Density Function
(pdf) and Cumulative disturibution function (cdf) for the Erlang Distribution. Accept the order k of the distribution and the parameters k2 from the user.
5. Write a C/C++ / Excel Program to find the Probability Density Function (pdf) and Cumulative disturibution function (cdf) for the Weibull Distribution. Accept for a random variable x with location parameter (υ), scale parameter (α) > 0 and the shape parameter (β)> 0 from the user.
6. Write a C/C++ / Excel Program to find the Probability Density Function (pdf) and Cumulative disturibution function (cdf) for the Triangular Distribution. Accept parameters a,b,c where a<=b<=c from the user.
SOURCE CODE
#include
#include
#include
#include
const int X[40];
void uniform();
void exponential();
void gamma();
void erlang();
void weibull();
void triangular();
void main()
{
int ch,j,flag=1,op;
clrscr();
while(flag==1)
{
printf("\n1:Uniform Distribution");
printf("\n2:Exponential Distribution");
printf("\n3:Gamma Distribution");
printf("\n4:Erlang Distribution");
printf("\n5:Weibull Distribution");
printf("\n6:Triangular Distribution");
printf("\n7:Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
uniform();
break;
case 2:
exponential();
break;
case 3:
gamma();
break;
case 4:
erlang();
break;
case 5:
weibull();
break;
case 6:
triangular();
break;
case 7:
exit(0);
break;
default:
flag=0;
exit(0);
}
getch();
}
}
void uniform()
{
float a,b,pdf,cdf,Ex,Vx,x;
int n;
clrscr();
printf("**********UNIFORM DISTRIBUTION************");
printf("\nenter value for a and b : ");
scanf("%f%f",&a,&b);
printf("\nenter value for x = ");
scanf("%f",&x);
printf("\nEnter your choice\n1*PDF\n2*CDF\n");
scanf("%d",&n);
switch(n)
{
case 1:
if (a<= x <=b)
pdf=1/(b-a);
else
pdf=0;
printf("pdf=%f",pdf);
break;
case 2:
if(x cdf=0;
else if(a<= x cdf=(x-a)/(b-a);
else if(x>=b)
cdf=1;
printf("cdf=%f",cdf);
break;
default:
printf("enter proper value");
}
Ex=(a+b)/2;
printf("E(x)=%f",Ex);
Vx=pow(b-a,2)/12;
printf("V(x)=%f",Vx);
getch();
}
/*------------------------------------------------------------------*/
void exponential()
{
float L,E,e,V,x,cdf,pdf;
int t,n;
clrscr();
printf("*************EXPONENTIAL DISTRIBUTION*******************");
printf("\nenter value for t=");
scanf("%d",&t);
printf("\nenter value for lambda & x = ");
scanf("%f%f",&L,&x);
printf("\nenter your choice");
scanf("%d",&n);
switch(n)
{
case 1:
if(x<=t)
pdf=L*exp(-L*x);
else
pdf=0;
printf("pdf=%f",pdf);
break;
case 2:
if (x>0 && x
else
cdf=0;
printf("cdf=%f",cdf);
break;
default:
exit(1);
}
E=1/L;
printf("E(x)=%f",E);
V=1/L*L;
printf("V(x)=%f",V);
getch();
}
/*--------------------------------------------------------------------*/
void gamma()
{
double calpdf(double, double, double, double);
double fact(double);
double x,B,T,th,pdf,b,factorial;
int i;
//B: Beta; T: Tau, th: thita,factorial : variable to calculate factorial
clrscr();
x=0;B=0;th=0;
printf("***************GAMMA DISTRIBUTION****************");
printf("\nEnter the values of x, B (beta), Thita\t");
scanf("%lf%lf%lf",&x,&B,&th);
if(B>=0 && B<=1)
{
if(th>=0 && th<=1)
{
if(B==1)
{
b=1;
}
else
{
b=B-1;
}
factorial=fact(b);
pdf=calpdf(B,th,factorial,x);
printf("Factorial= \t%lf\nPdf=\t%lf",factorial,pdf);
}
else
{
printf("\nthe value of thita should be between 0 and 1");
}
}
else
{
printf("\nthe value of beta should be between 0 and 1");
}
getch();
}
double calpdf(double Beta, double thita, double taub, double x)
{
double pdf=((Beta*thita)/taub)*(pow((Beta*thita*x),(Beta-1))*(exp(-Beta*thita*x)));
return(pdf);
}
double fact(double b)
{
int i;
double fact1=1;
for( i=1;i<=b;i++)
{
fact1=fact1*i;
}
return fact1;
}
/*--------------------------------------------------------------------------*/
void erlang()
{
double k,x,th,b,cdf,sum;
int i,j,facti,a;
clrscr();
printf("***************************************");
printf("\n \t Erling Distribution");
printf("\n***************************************");
printf("\n enter value for k x th = ");
scanf("%lf %lf %lf",&k,&x,&th);
if(x>=0)
{
facti=1;
sum=0;
for(i=0;i
for(j=i;j>=1;j--)
{
facti=j*facti;
}
b=(exp(-(k*th*x))*pow((k*th*x),i))/facti;
sum=b+sum;
}
printf("\nsum=%lf",sum);
cdf=1-sum;
}
else
cdf=0;
printf("\ncdf=%lf",cdf);
getch();
}
/*------------------------------------------------------------------------*/
void weibull()
{
double Tau(double);
double pdf, cdf, B,a,v,x,temp,T,E,V,F;
int n=0;
clrscr();
printf("*************Weibul Distribution****************\n\n\n");
printf("Enter the values for a(alpha), B(beta), v, x");
scanf("%lf%lf%lf%lf",&a,&B,&v,&x);
printf("\nEnter Choice \n1* PDF\t2*CDF\n");
scanf("%d",&n);
switch(n)
{
case 1:
temp=0;
temp=exp(-(pow(((x-v)/a),B)));
F=(B/a)*(pow((x-v/a),(B-1)))*temp;
printf("pdf=%lf",F);
break;
case 2:
temp=0;
temp=pow((x-v)/a,B);
if(x>v)
{
F=1-(exp(-temp));
}
printf("cdf=%lf",F);
E=v+(a*Tau((1/B)+1));
V=(pow(a,2))*((Tau((2/B)+1))-Tau(pow(((1/B)+1),2)));
printf("\nE=%lf \n v=%lf",E,V);
break;
default:
printf("Enter a proper input\n");
}
getch();
}
double Tau(double t)
{
double fact1=1;
int i;
for(i=1;i
fact1=fact1*i;
}
return fact1;
}
/*--------------------------------------------------------------------------*/
void triangular()
{
double fcdf(double,double,double,double);
double fpdf(double,double,double,double);
int n;
double a,b,c,x,pdf,cdf,E,V;
clrscr();
printf("Enter the values of a,b,c,d\n");
scanf("%lf%lf%lf%lf",&a,&b,&c,&x);
printf("Enter your choice\n1*PDF\n2*CDF\n");
scanf("%d",&n);
switch(n)
{
case 1:
pdf=fpdf(a,b,c,x);
printf("PDF=%lf",pdf);
break;
case 2:
cdf=fcdf(a,b,c,x);
printf("CDF=%lf",cdf);
break;
default:
printf("Please select appropriate input");
break;
}
E=(a+b+c)/3;
V=(3*E)-(a+c);
printf("\nMean =%lf",E);
printf("\nVariance =%lf",V);
getch();
}
double fcdf(double a,double b,double c,double x)
{
double cdf=0;
if(a
cdf=pow((x-a),2)/((b-a)*(c-a));
}
else if(b
cdf=1-(pow((c-x),2)/((c-b)*(c-a)));
}
else if(x<=a)
cdf=0;
else
cdf=1;
return cdf;
}
double fpdf(double a,double b,double c,double x)
{
double pdf=0;
if(a<=x && x<=b)
{
pdf=2*(x-a)/((b-a)*(c-a));
}
else if(b
pdf=2*(c-x)/((c-b)*(c-a));
}
else pdf=0;
return pdf;
}
Subscribe to:
Posts (Atom)